forked from mtusi2026/mtusi2026lab7
Обновлять сертификат балансировщика без перезапуска процессов
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -17,5 +17,5 @@
|
||||
],
|
||||
"bootstrap": "/bootstrap",
|
||||
"kv": false,
|
||||
"reload_pid_one": true
|
||||
"haproxy_socket": "/proc/1/root/tmp/admin.sock"
|
||||
}
|
||||
|
||||
+104
-21
@@ -4,6 +4,7 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
@@ -40,26 +41,27 @@ type Outbound struct {
|
||||
Identity string `json:"server_identity"`
|
||||
}
|
||||
type Config struct {
|
||||
Outbounds []Outbound `json:"outbounds"`
|
||||
ServeOnly bool `json:"serve_only"`
|
||||
ReloadPIDOne bool `json:"reload_pid_one"`
|
||||
Role string `json:"role"`
|
||||
DNS []string `json:"dns"`
|
||||
IP []string `json:"ip"`
|
||||
Bao string `json:"bao"`
|
||||
Trust string `json:"trust"`
|
||||
Bootstrap string `json:"bootstrap"`
|
||||
Identity string `json:"identity"`
|
||||
Revoked string `json:"revoked"`
|
||||
TTL string `json:"ttl"`
|
||||
KV bool `json:"kv"`
|
||||
Servers []Boundary `json:"servers"`
|
||||
Outbounds []Outbound `json:"outbounds"`
|
||||
ServeOnly bool `json:"serve_only"`
|
||||
HAProxySocket string `json:"haproxy_socket"`
|
||||
Role string `json:"role"`
|
||||
DNS []string `json:"dns"`
|
||||
IP []string `json:"ip"`
|
||||
Bao string `json:"bao"`
|
||||
Trust string `json:"trust"`
|
||||
Bootstrap string `json:"bootstrap"`
|
||||
Identity string `json:"identity"`
|
||||
Revoked string `json:"revoked"`
|
||||
TTL string `json:"ttl"`
|
||||
KV bool `json:"kv"`
|
||||
Servers []Boundary `json:"servers"`
|
||||
}
|
||||
type Agent struct {
|
||||
c Config
|
||||
mu sync.Mutex
|
||||
token string
|
||||
tokenUntil time.Time
|
||||
c Config
|
||||
mu sync.Mutex
|
||||
token string
|
||||
tokenUntil time.Time
|
||||
lbBundleHash [32]byte
|
||||
}
|
||||
|
||||
func event(name string) { log.Print("{\"event\":\"" + name + "\"}") }
|
||||
@@ -300,10 +302,21 @@ func (a *Agent) refresh() error {
|
||||
return errors.New("unparsed certificate")
|
||||
}
|
||||
event("identity.certificate_issued")
|
||||
if a.c.ReloadPIDOne {
|
||||
if e = syscall.Kill(1, syscall.SIGUSR2); e != nil {
|
||||
return errors.New("certificate reload failed")
|
||||
|
||||
}
|
||||
if a.c.HAProxySocket != "" {
|
||||
bundle := filepath.Join(a.c.Identity, "current", "bundle.pem")
|
||||
raw, err := os.ReadFile(bundle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hash := sha256.Sum256(raw)
|
||||
if hash != a.lbBundleHash {
|
||||
if err = installHAProxyCertificate(a.c.HAProxySocket, bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
a.lbBundleHash = hash
|
||||
event("identity.certificate_applied")
|
||||
}
|
||||
}
|
||||
if a.c.KV {
|
||||
@@ -334,6 +347,68 @@ func (a *Agent) refresh() error {
|
||||
return atomicFile(filepath.Join(a.c.Identity, "agent.json"), []byte(`{"refreshed_at":`+strconv.FormatInt(now.Unix(), 10)+`}`))
|
||||
}
|
||||
|
||||
// The runtime transaction replaces BOTH frontend and backend certificate
|
||||
// contexts without restarting workers or discarding DNS/health-check state.
|
||||
// Keep the persisted generation for native process restarts. Do not log PEM
|
||||
// payloads or CLI responses, which may include sensitive material on errors.
|
||||
func haProxyCommand(socketPath, request string) (string, error) {
|
||||
conn, err := net.DialTimeout("unix", socketPath, 3*time.Second)
|
||||
if err != nil {
|
||||
return "", errors.New("HAProxy admin socket unavailable")
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err = io.WriteString(conn, request); err != nil {
|
||||
return "", errors.New("HAProxy admin write failed")
|
||||
}
|
||||
if err = conn.(*net.UnixConn).CloseWrite(); err != nil {
|
||||
return "", errors.New("HAProxy admin shutdown failed")
|
||||
}
|
||||
response, err := io.ReadAll(io.LimitReader(conn, 64*1024))
|
||||
if err != nil {
|
||||
return "", errors.New("HAProxy admin response failed")
|
||||
}
|
||||
return string(response), nil
|
||||
}
|
||||
|
||||
func installHAProxyCertificate(socketPath, bundlePath string) error {
|
||||
// Serialize agent and explicit operator updates in their shared identity
|
||||
// volume, using the same unprivileged UID as the native load balancer.
|
||||
lock, err := os.OpenFile(filepath.Join(filepath.Dir(filepath.Dir(bundlePath)), ".haproxy.lock"), os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lock.Close()
|
||||
if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
|
||||
return err
|
||||
}
|
||||
defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
|
||||
raw, err := os.ReadFile(bundlePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tls.X509KeyPair(raw, raw); err != nil {
|
||||
return errors.New("invalid HAProxy certificate bundle")
|
||||
}
|
||||
var lines []string
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
response, err := haProxyCommand(socketPath, "set ssl cert "+bundlePath+" <<\n"+strings.Join(lines, "\n")+"\n\n")
|
||||
if err != nil || (!strings.Contains(response, "Transaction created") && !strings.Contains(response, "Transaction updated")) {
|
||||
_, _ = haProxyCommand(socketPath, "abort ssl cert "+bundlePath+"\n")
|
||||
return errors.New("HAProxy certificate transaction failed")
|
||||
}
|
||||
response, err = haProxyCommand(socketPath, "commit ssl cert "+bundlePath+"\n")
|
||||
if err != nil || !strings.Contains(response, "Success!") {
|
||||
_, _ = haProxyCommand(socketPath, "abort ssl cert "+bundlePath+"\n")
|
||||
return errors.New("HAProxy certificate commit failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type boundedListener struct {
|
||||
net.Listener
|
||||
slots chan struct{}
|
||||
@@ -601,6 +676,14 @@ func runTCP(c Config, b Boundary) error {
|
||||
}
|
||||
}
|
||||
func main() {
|
||||
if len(os.Args) == 2 && os.Args[1] == "--reload-lb-cert" {
|
||||
if installHAProxyCertificate("/proc/1/root/tmp/admin.sock", "/run/identity/current/bundle.pem") != nil {
|
||||
event("identity.certificate_apply_failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
event("identity.certificate_applied")
|
||||
return
|
||||
}
|
||||
if len(os.Args) != 2 {
|
||||
event("gateway.invalid_configuration")
|
||||
os.Exit(2)
|
||||
|
||||
@@ -217,3 +217,88 @@ func TestClientAuthorizationUsesCurrentChainIdentityExpiryAndRevocation(t *testi
|
||||
t.Fatal("missing revocation policy did not fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
// A failed native commit must be reported and aborted so the agent retries;
|
||||
// persisting a new PEM alone does not prove that the native process uses it.
|
||||
func TestHAProxyCertificateTransaction(t *testing.T) {
|
||||
for _, success := range []bool{true, false} {
|
||||
t.Run(fmt.Sprint(success), func(t *testing.T) {
|
||||
ca := root(t)
|
||||
key, err := x509.MarshalECPrivateKey(ca.key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
directory, err := os.MkdirTemp("", "lb-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(directory) })
|
||||
current := filepath.Join(directory, "current")
|
||||
if err = os.Mkdir(current, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bundle := filepath.Join(current, "bundle.pem")
|
||||
raw := append(ca.pem, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: key})...)
|
||||
if err = os.WriteFile(bundle, raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
socket := filepath.Join(directory, "admin.sock")
|
||||
listener, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
commands := []string{"set ssl cert ", "commit ssl cert "}
|
||||
if !success {
|
||||
commands = append(commands, "abort ssl cert ")
|
||||
}
|
||||
for _, prefix := range commands {
|
||||
conn, e := listener.Accept()
|
||||
if e != nil {
|
||||
done <- e
|
||||
return
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
request, e := io.ReadAll(conn)
|
||||
if e != nil {
|
||||
conn.Close()
|
||||
done <- e
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(string(request), prefix+bundle) {
|
||||
conn.Close()
|
||||
done <- fmt.Errorf("unexpected command prefix")
|
||||
return
|
||||
}
|
||||
reply := "Transaction created for certificate\n"
|
||||
if strings.HasPrefix(prefix, "set") && (!strings.HasSuffix(string(request), "\n\n") || !strings.Contains(string(request), "-----BEGIN EC PRIVATE KEY-----")) {
|
||||
conn.Close()
|
||||
done <- fmt.Errorf("missing bounded PEM payload")
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(prefix, "commit") {
|
||||
reply = "Success!\n"
|
||||
if !success {
|
||||
reply = "synthetic failure contains PRIVATE response\n"
|
||||
}
|
||||
}
|
||||
io.WriteString(conn, reply)
|
||||
conn.Close()
|
||||
}
|
||||
done <- nil
|
||||
}()
|
||||
err = installHAProxyCertificate(socket, bundle)
|
||||
if (err == nil) != success {
|
||||
t.Fatal("native commit result was ignored")
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), "PRIVATE") {
|
||||
t.Fatal("native response leaked")
|
||||
}
|
||||
if e := <-done; e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ from scripts.bootstrap_security import OPERATOR, ROLES, TRUST, write_private
|
||||
from scripts.prepare_dependencies import attach_policy
|
||||
from scripts.stand import compose
|
||||
|
||||
INSTALL = """import json,os,pathlib,signal,sys,tempfile
|
||||
INSTALL = """import json,os,pathlib,subprocess,sys,tempfile
|
||||
data=json.load(sys.stdin)
|
||||
base=pathlib.Path('/run/identity')
|
||||
directory=pathlib.Path(tempfile.mkdtemp(prefix='generation-',dir=base))
|
||||
@@ -28,7 +28,7 @@ certificate=data['certificate']+'\\n'+'\\n'.join(data.get('ca_chain',[]))
|
||||
for name,value in [('cert.pem',certificate),('key.pem',data['private_key']),('bundle.pem',certificate+'\\n'+data['private_key'])]:
|
||||
path=directory/name;path.write_text(value);path.chmod(0o600)
|
||||
link=base/'operator-next';link.unlink(missing_ok=True);link.symlink_to(directory.name);link.replace(base/'current')
|
||||
if data.get('reload_lb'):os.kill(1,signal.SIGUSR2)
|
||||
if data.get('reload_lb'):subprocess.run(['tls-gateway','--reload-lb-cert'],check=True)
|
||||
print('Operator installed a scoped short-lived leaf')
|
||||
"""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user