carlos / platform Public

region HA P3b T5: fence admitted local ingress EIPs

Install group-only local ingress EIPs behind a verified root-owned nft
fence. Bind activation, removal and verified public client identity to
admission and the current agent process, retaining the existing private
and metadata restrictions.

Add ordering, race and mutation guards plus the tagged kernel witness.
Local checks pass; root-runner execution and integrated census approval
remain with the controller.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d77af518ac3f85941fb3d6f593ece76b6339b5fc parent 77a57e4
29 files changed, +2,767 −24
  • infra/modules/region-host/group-init.sh.tftpl +69 −6
  • internal/edge/edge.go +12 −0
  • internal/edge/hairpin.go +149 −0
  • internal/edge/hairpin_linux.go +5 −0
  • internal/edge/hairpin_other.go +7 −0
  • internal/edge/hairpin_test.go +49 −0
  • internal/hairpin/lifecycle.go +70 −0
  • internal/hairpin/lifecycle_test.go +99 −0
  • internal/hairpin/native_linux.go +404 −0
  • internal/hairpin/native_linux_test.go +65 −0
  • internal/hairpin/native_other.go +38 −0
  • internal/hairpin/rules.go +148 −0
  • internal/hairpin/rules_test.go +92 −0
  • internal/hairpin/snapshot.go +76 −0
  • internal/host/agent.go +7 −0
  • internal/host/awsaddr.go +18 −0
  • internal/host/claimstop_run.go +26 −0
  • internal/host/group_admission.go +32 −6
  • internal/host/group_boot.go +3 −0
  • internal/host/group_boot_budget_test.go +20 −5
  • internal/host/group_config_linux.go +4 −0
  • internal/host/group_hairpin.go +57 −0
  • internal/host/group_hairpin_rootrunner_linux_test.go +926 −0
  • internal/host/group_hairpin_test.go +92 −0
  • internal/host/group_maintenance.go +2 −2
  • internal/host/group_metrics.go +5 −1
  • internal/instancectl/hairpin.go +266 −0
  • internal/instancectl/hardening.go +14 −4
  • internal/instancectl/server.go +12 −0

Intent

Human

<task-notification> <task-id>a6a1eb9a9571428ec</task-id> <tool-use-id>toolu_01GT8PWbN64dEXL4fcHvJsad</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/a6a1eb9a9571428ec.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: no P1, so round 1 is the stopping round.** Counts are P1 0, P2 2, P3 5. I wrote the review to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group/task-4-review-r1.md`. I did not re-run any tests and made no changes to the worktree. On spec compliance: - **Permit checks:** the guard reads only the root marker and the permit at `/run/carlos-group-maintenance/permit.json`. Decoding is strict and every field must match exactly. A used action can't be replayed, and nothing the agent can write counts as a permit. - **Restart entries:** every restart-capable step is checked under the mutation lock before it does anything. That covers apply, recover, rollback, quiesce, repoint, unit repair, bootstrap and install-channel reentry. - **Units:** the group self-update leg is disabled. The update path, update service and recover service are masked. Unit repair keeps the masks and the `Restart=no` drop-in. - **Fixed boxes:** without the marker they behave exactly as before. **Carried P3-1 is resolved.** The update path is now masked and left out of the boot plan. `carlos-adopt.timer` and `carlos-restart.path` only restart app routes and never `carlos-edge`. Their one root-unit change goes through unit repair, which needs a `repair` permit. **P2** - **P2-1 (T1/I4, fixed-box identity):** the launch-time group branch of bootstrap (`bootstrap.go:397,551,628-633,668-671`) has no test. That branch skips the automatic units, masks them and filters the enable/start plan. Only the helpers it calls are tested. A regression there would arm `carlos-system-update.path` on every new member. Fix: add a seam and a test of the group plan. - **P2-2 (T1/I4):** the fake return protocol gets stuck after a lost CONTINUE when the member is still in Pending:Wait (`group_maintenance_protocol_test.go:167`). It keeps returning "completion unknown" without retrying within the 4-attempt budget, recording FAIL or alerting, so AWS's default ABANDON would end the member at 900 s. Task 7 builds against this model. Fix: after reading the phase, retry while budget remains, otherwise fail and alert before the deadline. Add a test case where the completion never landed. **P3** - **P3-1 (T1):** `quiesce` returns nil on refusal (`systemapply.go:787-790`). Safety depends on the next activation check also refusing. - **P3-2 (N1/T1):** a generic `"mutation"` check accepts any permit action. As a result `rearmPending` (`systemapply.go:384`) can run under a repair, install or rollback permit. Also, a rollback permit gets used up by the staging check before that check refuses it. - **P3-3 (quality):** every adopt pass on a group box without a permit logs a bare `group_maintenance_required` with no prefix (`systemunits.go:93,97`). - **P3-4 (I4, test strength):** the fake operator's readiness isn't tied to the real admission state, and the S3/SSM outage is modelled as empty facts. - **P3-5:** group recovery always rolls back, even from the gated phase (`systemapply.go:2089-2094`). This is deliberate and conservative; worth a line in the Task 7 runbook.</result> <usage><subagent_tokens>179577</subagent_tokens><tool_uses>37</tool_uses><duration_ms>542313</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bgcwnb47k</task-id> <tool-use-id>toolu_019voEkqDCrXDM426udfvHUo</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bgcwnb47k.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t6 $D/task-6-report.md" completed (exit code 0)</summary> </task-notification>

diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl
index 2c90627bc..70e652d06 100644
--- a/infra/modules/region-host/group-init.sh.tftpl
+++ b/infra/modules/region-host/group-init.sh.tftpl
@@ -57,7 +57,7 @@ for path, body in files.items():
PY
export NEEDRESTART_MODE=l
apt-get -q update
-apt-get -y -q install nftables chrony awscli
+apt-get -y -q install nftables chrony awscli iproute2
getent passwd carlos >/dev/null || useradd --system --home-dir /data --shell /usr/sbin/nologin carlos
CARLOS_UID=$(id -u carlos)
export CARLOS_UID
@@ -160,10 +160,13 @@ with open(work + 'bootstrap', 'rb') as f:
if hashlib.file_digest(f, 'sha256').hexdigest() != sha:
raise SystemExit('group_boot_hash')
os.chmod(work + 'bootstrap', 0o755)
-# Three IMDS requests, reused by the agent through the signed root snapshot.
+# Seven IMDS requests, reused through root snapshots. No runtime address poll.
+class NoMetadataRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, request, response, code, message, headers, target):
+ return None
def imds(path, method='GET', headers=None):
request = urllib.request.Request('http://169.254.169.254' + path, method=method, headers=headers or {})
- with urllib.request.urlopen(request, timeout=2) as response:
+ with urllib.request.build_opener(urllib.request.ProxyHandler({}), NoMetadataRedirect()).open(request, timeout=2) as response:
return response.read(65537)
token = imds('/latest/api/token', 'PUT', {'X-aws-ec2-metadata-token-ttl-seconds': '60'}).decode().strip()
headers = {'X-aws-ec2-metadata-token': token}
@@ -177,6 +180,28 @@ ref = 'g-' + hashlib.sha256(('carlos-box-ref-v1|' + identity['accountId'] + '|'
record = dict(v=1, box=ref, identity_document=base64.b64encode(doc).decode(), identity_signature=sig, written_at=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'))
write('/etc/carlos/group-identity.json', json.dumps(record, separators=(',', ':')).encode())
boot_id = open('/proc/sys/kernel/random/boot_id').read().strip()
+public_ip = imds('/latest/meta-data/public-ipv4', headers=headers).decode().strip()
+primary_ip = imds('/latest/meta-data/local-ipv4', headers=headers).decode().strip()
+# Canonical, globally usable IPv4 only. The Go reader independently applies
+# the same reserved-range exclusions before this snapshot grants authority.
+def public_v4(ip):
+ address = ipaddress.ip_address(ip)
+ return address.version == 4 and str(address) == ip and address.is_global and not address.is_multicast and not address.is_reserved and address not in ipaddress.ip_network('192.0.0.0/24') and address not in ipaddress.ip_network('192.88.99.0/24')
+if not public_v4(public_ip) or ipaddress.ip_address(primary_ip).version != 4 or not ipaddress.ip_address(primary_ip).is_private or primary_ip != identity['privateIp']:
+ raise SystemExit('group_hairpin_identity')
+mac = imds('/latest/meta-data/mac', headers=headers).decode().strip()
+if not re.fullmatch('[0-9a-f]{2}(:[0-9a-f]{2}){5}', mac):
+ raise SystemExit('group_hairpin_identity')
+blocks = imds('/latest/meta-data/network/interfaces/macs/' + mac + '/vpc-ipv4-cidr-blocks', headers=headers).decode().split()
+networks = [ipaddress.ip_network(block, strict=True) for block in blocks]
+networks = [network for network in networks if network.version == 4 and network.is_private and ipaddress.ip_address(primary_ip) in network]
+if not networks:
+ raise SystemExit('group_hairpin_identity')
+private_cidr = str(max(networks, key=lambda network: network.prefixlen))
+if E.get('CARLOS_PRIVATE_CIDR', private_cidr) != private_cidr:
+ raise SystemExit('group_hairpin_override')
+if E.get('CARLOS_PUBLIC_IP', public_ip) != public_ip or E.get('CARLOS_PRIVATE_IP', primary_ip) != primary_ip:
+ raise SystemExit('group_hairpin_override')
deadline = int(datetime.datetime.fromisoformat(identity['pendingTime'].replace('Z', '+00:00')).timestamp()) + 900
if time.time() >= deadline:
raise SystemExit('group_boot_deadline')
@@ -191,16 +216,54 @@ if not isinstance(ips, list) or not ips or len(ips) != len(set(ips)) or len(ips)
raise SystemExit('group_boot_ingress')
for ip in ips:
address = ipaddress.ip_address(ip)
- if address.version != 4 or not address.is_global:
+ if not public_v4(ip) or ip == public_ip:
raise SystemExit('group_boot_ingress')
-write('/etc/carlos/group-ingress.json', json.dumps(dict(v=1, region=E['CARLOS_REGION'], public_ips=ips), separators=(',', ':')).encode())
marker = dict(v=1, data_bucket=E['CARLOS_GROUP_DATA_BUCKET'], deployment_aws_region=obj['deployment_aws_region'], account=identity['accountId'], aws_region=E['AWS_REGION'], region=E['CARLOS_REGION'], deployment=E['CARLOS_DEPLOYMENT'], bucket=E['CARLOS_DEPLOYMENT_BUCKET'], group=E['CARLOS_GROUP_NAME'], hook=E['CARLOS_LAUNCH_HOOK_NAME'], placement=E['CARLOS_PLACEMENT_REGION'], pools=E['CARLOS_POOLS'].split(','), known_readers=obj['known_readers'], release=E['CARLOS_RELEASE'], instance_id=iid, boot_id=boot_id, deadline=deadline, queue_url=values[names[2]])
marker['config_digest'] = hashlib.sha256(json.dumps(marker, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
write('/etc/carlos/group.json', json.dumps(marker, separators=(',', ':')).encode())
+# Verify the signed document against the root marker before publishing the
+# address snapshot. The public-IP leaf's provenance is protected IMDSv2.
+subprocess.check_call([work + 'bootstrap', 'instance-control', '--group-hairpin-verify-identity'], timeout=10)
+write('/etc/carlos/group-ingress.json', json.dumps(dict(v=1, region=E['CARLOS_REGION'], public_ips=ips, public_ipv4=public_ip, primary_ipv4=primary_ip, private_cidr=private_cidr, boot_id=boot_id, account=identity['accountId'], iid=iid), separators=(',', ':')).encode())
PY
# install dormant hairpin
-# Deliberate no-op until Task 5 supplies the rules and admission activation.
+# The verified bootstrap revalidates the signed identity and this boot's
+# protected address snapshot before installing the owned fence and empty dummy.
+# The IMDS table remains independently owned and unchanged.
+python3 - <<'PYHAIRPIN'
+import os
+files = {
+ '/etc/sysctl.d/99-carlos-hairpin.conf': 'net.ipv4.conf.all.arp_ignore=1\nnet.ipv4.conf.default.arp_ignore=1\nnet.ipv4.conf.all.arp_announce=2\nnet.ipv4.conf.default.arp_announce=2\n',
+ '/etc/systemd/system/carlos-edge.service.d/60-hairpin.conf': '[Service]\nRestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK\nExecStartPre=+/usr/bin/systemctl start carlos-hairpin-reset.service\nExecStop=+/usr/bin/systemctl start carlos-hairpin-reset.service\nExecStopPost=+/usr/bin/systemctl start carlos-hairpin-reset.service\n',
+ '/etc/systemd/system/carlos-hairpin-reset.service': '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nType=oneshot\nExecStart=/opt/carlos/carlos instance-control --group-hairpin-reset\nTimeoutStartSec=70\n',
+ '/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf': '[Service]\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\nReadWritePaths=/run/carlos-hairpin\n',
+}
+os.mkdir('/etc/systemd/system/carlos-instance-control.service.d', 0o755)
+for path, body in files.items():
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
+ os.fchmod(fd, 0o644)
+ with os.fdopen(fd, 'w') as f:
+ f.write(body)
+ f.flush()
+ os.fsync(f.fileno())
+PYHAIRPIN
+sysctl -p /etc/sysctl.d/99-carlos-hairpin.conf
+/run/carlos-group-boot/bootstrap instance-control --group-hairpin-install
+# Persist only the dormant owned tables; never persist assigned EIPs or an
+# exemption. On reboot the reset operation refuses a stale boot snapshot.
+python3 - <<'PYHAIRPIN'
+import os, subprocess
+body = b''.join(subprocess.check_output(['nft', '-s', 'list', 'table', 'inet', table]) for table in ['carlos_group_imds', 'carlos_hairpin'])
+path = '/etc/.carlos-hairpin-nftables'
+fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
+os.fchmod(fd, 0o644)
+with os.fdopen(fd, 'wb') as f:
+ f.write(body)
+ f.flush()
+ os.fsync(f.fileno())
+os.replace(path, '/etc/nftables.conf')
+PYHAIRPIN
# Task 4 supplies root restart authorization and preserves this drop-in.
test "$(cat /etc/systemd/system/carlos-edge.service.d/50-group.conf)" = "$(printf '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nRestart=no')"
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index e667fa15f..922744af2 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4539,6 +4539,10 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
if err != nil {
log.Fatal(err)
}
+ ln, err = ConfigureGroupHairpin(srv, ln)
+ if err != nil {
+ log.Fatal(err)
+ }
log.Print(listenersLine(ln, *httpAddr, nil, ""))
go func() {
log.Printf("edge: DEV MODE — plain HTTP, serving %d route(s) on %s (registry %s)",
@@ -4720,6 +4724,14 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
if err != nil {
log.Fatal(err)
}
+ httpLn, err = ConfigureGroupHairpin(httpSrv, httpLn)
+ if err != nil {
+ log.Fatal(err)
+ }
+ httpsLn, err = ConfigureGroupHairpin(httpsSrv, httpsLn)
+ if err != nil {
+ log.Fatal(err)
+ }
log.Print(listenersLine(httpLn, *httpAddr, httpsLn, *httpsAddr))
// :80 serves the ACME HTTP-01 challenge and redirects everything else.
diff --git a/internal/edge/hairpin.go b/internal/edge/hairpin.go
new file mode 100644
index 000000000..716a84bcc
--- /dev/null
+++ b/internal/edge/hairpin.go
@@ -0,0 +1,149 @@
+package edge
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "net"
+ "net/http"
+ "net/netip"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/hairpin"
+)
+
+type hairpinContextKey struct{}
+type hairpinIngress struct {
+ config hairpin.Config
+ local map[netip.Addr]bool
+}
+type hairpinConnection struct {
+ net.Conn
+ public string
+}
+type hairpinListener struct {
+ net.Listener
+ ingress *hairpinIngress
+}
+
+// Only the accept path can create this mark, before TLS. Headers, connection
+// marks set by callers and the request's Host never select the hairpin path.
+func (h *hairpinIngress) classify(local, peer net.Addr) (string, error) {
+ dst, ok := local.(*net.TCPAddr)
+ if !ok {
+ return "", hairpin.ErrConfig
+ }
+ a, ok := netip.AddrFromSlice(dst.IP)
+ if !ok {
+ return "", hairpin.ErrConfig
+ }
+ a = a.Unmap()
+ ingress := false
+ for _, ip := range h.config.PublicIPs {
+ if a.String() == ip {
+ ingress = true
+ break
+ }
+ }
+ if !ingress {
+ return "", nil
+ }
+ src, ok := peer.(*net.TCPAddr)
+ if !ok {
+ return "", hairpin.ErrConfig
+ }
+ p, ok := netip.AddrFromSlice(src.IP)
+ if !ok || (!h.local[p.Unmap()] && !p.Unmap().IsLoopback()) || (dst.Port != 80 && dst.Port != 443) {
+ return "", hairpin.ErrConfig
+ }
+ if !hairpin.PublicIPv4(h.config.PublicIPv4) {
+ return "", hairpin.ErrConfig
+ }
+ return h.config.PublicIPv4, nil
+}
+func (l *hairpinListener) Accept() (net.Conn, error) {
+ for {
+ c, err := l.Listener.Accept()
+ if err != nil {
+ return nil, err
+ }
+ mark, err := l.ingress.classify(c.LocalAddr(), c.RemoteAddr())
+ if err != nil {
+ c.Close()
+ continue
+ }
+ if mark != "" {
+ return &hairpinConnection{Conn: c, public: mark}, nil
+ }
+ return c, nil
+ }
+}
+func hairpinConnContext(ctx context.Context, c net.Conn) context.Context {
+ if secure, ok := c.(*tls.Conn); ok {
+ c = secure.NetConn()
+ }
+ if h, ok := c.(*hairpinConnection); ok {
+ return context.WithValue(ctx, hairpinContextKey{}, h.public)
+ }
+ return ctx
+}
+func normalizeHairpin(r *http.Request) {
+ public, ok := r.Context().Value(hairpinContextKey{}).(string)
+ if !ok {
+ return
+ }
+ _, port, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ port = "0"
+ }
+ r.RemoteAddr = net.JoinHostPort(public, port)
+ // The ordinary public path reconstructs client forwarding and its proof.
+ // A local connection has no right to supply any prior forwarding identity.
+ for key := range r.Header {
+ lower := strings.ToLower(key)
+ if strings.HasPrefix(lower, "x-forwarded-") || lower == "forwarded" || lower == "x-real-ip" || lower == "x-carlos-hairpin" {
+ delete(r.Header, key)
+ }
+ }
+}
+
+// ConfigureGroupHairpin preserves the exact fixed-box listener/server objects.
+// Root ownership, signed instance identity and the boot binding are checked
+// once before any group listener serves. Public requests retain socket identity.
+func ConfigureGroupHairpin(srv *http.Server, ln net.Listener) (net.Listener, error) {
+ c, err := hairpin.Load()
+ if err != nil || c == nil {
+ return ln, err
+ }
+ if err := hairpinSupported(); err != nil {
+ return nil, err
+ }
+ addrs, err := net.InterfaceAddrs()
+ if err != nil {
+ return nil, err
+ }
+ h := &hairpinIngress{config: *c, local: map[netip.Addr]bool{}}
+ for _, addr := range addrs {
+ p, err := netip.ParsePrefix(addr.String())
+ if err != nil {
+ return nil, err
+ }
+ h.local[p.Addr().Unmap()] = true
+ }
+ if !h.local[netip.MustParseAddr(c.PrimaryIPv4)] {
+ return nil, errors.New("group_hairpin_primary_address")
+ }
+ for _, ip := range c.PublicIPs {
+ h.local[netip.MustParseAddr(ip)] = true
+ }
+ previous := srv.ConnContext
+ srv.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
+ if previous != nil {
+ ctx = previous(ctx, c)
+ }
+ return hairpinConnContext(ctx, c)
+ }
+ handler := srv.Handler
+ srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { normalizeHairpin(r); handler.ServeHTTP(w, r) })
+ return &hairpinListener{Listener: ln, ingress: h}, nil
+}
diff --git a/internal/edge/hairpin_linux.go b/internal/edge/hairpin_linux.go
new file mode 100644
index 000000000..6626d9580
--- /dev/null
+++ b/internal/edge/hairpin_linux.go
@@ -0,0 +1,5 @@
+//go:build linux
+
+package edge
+
+func hairpinSupported() error { return nil }
diff --git a/internal/edge/hairpin_other.go b/internal/edge/hairpin_other.go
new file mode 100644
index 000000000..301cc5b27
--- /dev/null
+++ b/internal/edge/hairpin_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package edge
+
+import "github.com/carlosframework/platform/internal/hairpin"
+
+func hairpinSupported() error { return hairpin.ErrUnsupported }
diff --git a/internal/edge/hairpin_test.go b/internal/edge/hairpin_test.go
new file mode 100644
index 000000000..13ceaaef8
--- /dev/null
+++ b/internal/edge/hairpin_test.go
@@ -0,0 +1,49 @@
+package edge
+
+import (
+ "context"
+ "net"
+ "net/http/httptest"
+ "net/netip"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hairpin"
+)
+
+func TestHairpinOriginalDestination(t *testing.T) {
+ c := hairpin.Config{V: 1, Region: "ie", PublicIPs: []string{"8.8.8.8", "9.9.9.9"}, PublicIPv4: "1.1.1.1", PrivateCIDR: "172.31.0.0/16", PrimaryIPv4: "172.31.7.19", BootID: "12345678-1234-1234-1234-123456789abc", Account: "123456789012", InstanceID: "i-0123456789abcdef0"}
+ h := hairpinIngress{config: c, local: map[netip.Addr]bool{netip.MustParseAddr(c.PrimaryIPv4): true, netip.MustParseAddr("127.0.0.1"): true}}
+ for _, tc := range []struct {
+ dst, peer string
+ marked, refused bool
+ }{{"8.8.8.8:80", "172.31.7.19:40000", true, false}, {"9.9.9.9:443", "127.0.0.1:40000", true, false}, {"8.8.8.8:80", "127.0.0.2:40000", true, false}, {"8.8.8.8:443", "8.8.4.4:40000", false, true}, {"8.8.8.8:8080", "172.31.7.19:40000", false, true}, {"172.31.7.19:443", "8.8.4.4:40000", false, false}} {
+ mark, err := h.classify(mustTCP(t, tc.dst), mustTCP(t, tc.peer))
+ if (err != nil) != tc.refused || (mark != "") != tc.marked {
+ t.Errorf("%+v: %q %v", tc, mark, err)
+ }
+ if tc.marked && mark != c.PublicIPv4 {
+ t.Fatal(mark)
+ }
+ }
+ r := httptest.NewRequest("POST", "https://shop.example/path", nil)
+ r.RemoteAddr = "8.8.4.4:40000"
+ r.Header.Set("X-Carlos-Hairpin", "1")
+ r.Header.Set("X-Forwarded-For", "127.0.0.1")
+ normalizeHairpin(r)
+ if r.RemoteAddr != "8.8.4.4:40000" {
+ t.Fatal("header forged hairpin")
+ }
+ r = r.WithContext(context.WithValue(r.Context(), hairpinContextKey{}, c.PublicIPv4))
+ normalizeHairpin(r)
+ if r.RemoteAddr != c.PublicIPv4+":40000" || r.Header.Get("X-Forwarded-For") != "" || r.Host != "shop.example" || r.Method != "POST" {
+ t.Fatalf("normalization: %+v", r)
+ }
+}
+func mustTCP(t *testing.T, s string) *net.TCPAddr {
+ t.Helper()
+ a, err := net.ResolveTCPAddr("tcp", s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return a
+}
diff --git a/internal/hairpin/lifecycle.go b/internal/hairpin/lifecycle.go
new file mode 100644
index 000000000..a617aaf20
--- /dev/null
+++ b/internal/hairpin/lifecycle.go
@@ -0,0 +1,70 @@
+package hairpin
+
+import (
+ "context"
+ "errors"
+ "os"
+ "time"
+)
+
+// Operations runs while the root process holds the cross-process hairpin lock.
+// The deny refresher and both probes take the same lock. Configuration and
+// addresses are captured by root, never supplied in the agent's request.
+type Operations struct {
+ Install func(context.Context) error
+ Verify func(context.Context) error
+ Addresses func(context.Context, bool) error
+ Exempt func(context.Context, bool) error
+ Save func(bool) error
+}
+
+func (o Operations) Enable(ctx context.Context) (err error) {
+ defer func() {
+ if err != nil {
+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
+ defer cancel()
+ err = errors.Join(err, o.Disable(cleanup))
+ }
+ }()
+ if err = o.Install(ctx); err != nil {
+ return err
+ }
+ if err = o.Verify(ctx); err != nil {
+ return err
+ }
+ if err = o.Addresses(ctx, true); err != nil {
+ return err
+ }
+ if err = o.Exempt(ctx, true); err != nil {
+ return err
+ }
+ return o.Save(true)
+}
+
+// The dormant fence stays installed. Removal of a fence is reserved for root
+// reseeding under maintenance, after removal of all addresses and exemptions.
+// Even a failed address removal attempts to restore the full #367 deny.
+func (o Operations) Disable(ctx context.Context) error {
+ saved := o.Save(false)
+ removed := o.Addresses(ctx, false)
+ denied := o.Exempt(ctx, false)
+ return errors.Join(saved, removed, denied)
+}
+
+const RuntimeDir = "/run/carlos-hairpin"
+
+type Process struct {
+ PID int `json:"pid"`
+ Start string `json:"start"`
+ Boot string `json:"boot"`
+}
+type State struct {
+ Process Process `json:"process"`
+ Active bool `json:"active"`
+ Closed bool `json:"closed"`
+}
+type Lease struct {
+ Config Config
+ State State
+ lock *os.File
+}
diff --git a/internal/hairpin/lifecycle_test.go b/internal/hairpin/lifecycle_test.go
new file mode 100644
index 000000000..38af57d86
--- /dev/null
+++ b/internal/hairpin/lifecycle_test.go
@@ -0,0 +1,99 @@
+package hairpin
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+)
+
+func TestHairpinAdmissionLifecycle(t *testing.T) {
+ for _, fail := range []string{"", "install", "verify", "addresses-on", "exempt-on", "save-on"} {
+ t.Run(fail, func(t *testing.T) {
+ var calls []string
+ op := func(name string) error {
+ calls = append(calls, name)
+ if name == fail {
+ return errors.New(name)
+ }
+ return nil
+ }
+ fence, addresses, exempt := false, false, false
+ ops := Operations{
+ Install: func(context.Context) error {
+ err := op("install")
+ if err == nil {
+ fence = true
+ }
+ return err
+ },
+ Verify: func(context.Context) error {
+ if !fence {
+ return errors.New("absent")
+ }
+ return op("verify")
+ },
+ Addresses: func(_ context.Context, on bool) error {
+ n := "addresses-off"
+ if on {
+ n = "addresses-on"
+ if !fence {
+ t.Fatal("address without fence")
+ }
+ }
+ err := op(n)
+ if err == nil {
+ addresses = on
+ }
+ return err
+ },
+ Exempt: func(_ context.Context, on bool) error {
+ n := "exempt-off"
+ if on {
+ n = "exempt-on"
+ if !fence {
+ t.Fatal("exemption without fence")
+ }
+ }
+ err := op(n)
+ if err == nil {
+ exempt = on
+ }
+ return err
+ },
+ Save: func(on bool) error {
+ n := "save-off"
+ if on {
+ n = "save-on"
+ }
+ return op(n)
+ },
+ }
+ err := ops.Enable(context.Background())
+ if fail == "" {
+ if err != nil || !addresses || !exempt {
+ t.Fatalf("activation: %v %v", err, calls)
+ }
+ if !reflect.DeepEqual(calls, []string{"install", "verify", "addresses-on", "exempt-on", "save-on"}) {
+ t.Fatal(calls)
+ }
+ calls = nil
+ if err := ops.Disable(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(calls, []string{"save-off", "addresses-off", "exempt-off"}) {
+ t.Fatal(calls)
+ }
+ } else if err == nil || addresses || exempt {
+ t.Fatalf("rollback: %v %v addresses=%v exempt=%v", err, calls, addresses, exempt)
+ }
+ })
+ }
+ t.Run("failed-removal-keeps-fence-and-restores-deny", func(t *testing.T) {
+ var calls []string
+ ops := Operations{Save: func(bool) error { calls = append(calls, "save"); return nil }, Addresses: func(context.Context, bool) error { calls = append(calls, "remove"); return errors.New("ip") }, Exempt: func(context.Context, bool) error { calls = append(calls, "deny"); return nil }}
+ if ops.Disable(context.Background()) == nil || !reflect.DeepEqual(calls, []string{"save", "remove", "deny"}) {
+ t.Fatal(calls)
+ }
+ })
+}
diff --git a/internal/hairpin/native_linux.go b/internal/hairpin/native_linux.go
new file mode 100644
index 000000000..3f85f7eed
--- /dev/null
+++ b/internal/hairpin/native_linux.go
@@ -0,0 +1,404 @@
+//go:build linux
+
+package hairpin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+ "os/user"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hostenv"
+ "golang.org/x/sys/unix"
+)
+
+func Identity(pid int) (Process, error) {
+ var p Process
+ if pid <= 0 {
+ return p, ErrConfig
+ }
+ b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if err != nil {
+ return p, err
+ }
+ // comm may contain spaces and parentheses; starttime is field 22.
+ i := strings.LastIndexByte(string(b), ')')
+ if i < 0 {
+ return p, ErrConfig
+ }
+ fields := strings.Fields(string(b[i+1:]))
+ if len(fields) < 20 {
+ return p, ErrConfig
+ }
+ if _, err := strconv.ParseUint(fields[19], 10, 64); err != nil {
+ return p, err
+ }
+ boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ if err != nil {
+ return p, err
+ }
+ return Process{PID: pid, Start: fields[19], Boot: strings.TrimSpace(string(boot))}, nil
+}
+
+func Authenticate(ctx context.Context, conn net.Conn, p Process) error {
+ u, err := user.Lookup("carlos")
+ if err != nil {
+ return err
+ }
+ uid, err := strconv.Atoi(u.Uid)
+ if err != nil {
+ return err
+ }
+ c, ok := conn.(*net.UnixConn)
+ if !ok {
+ return ErrConfig
+ }
+ raw, err := c.SyscallConn()
+ if err != nil {
+ return err
+ }
+ var cred *unix.Ucred
+ var inner error
+ err = raw.Control(func(fd uintptr) { cred, inner = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) })
+ if err != nil || inner != nil || cred == nil || int(cred.Uid) != uid || int(cred.Pid) != p.PID {
+ return ErrConfig
+ }
+ return Current(ctx, p)
+}
+func MainProcess(ctx context.Context) (Process, error) {
+ raw, err := exec.CommandContext(ctx, "systemctl", "show", "carlos-edge.service", "--property=MainPID", "--property=LoadState").CombinedOutput()
+ fields := map[string]string{}
+ for _, line := range strings.Split(string(raw), "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok {
+ fields[k] = v
+ }
+ }
+ if fields["LoadState"] == "not-found" && (fields["MainPID"] == "0" || fields["MainPID"] == "") {
+ return Process{}, nil
+ }
+ if err != nil {
+ return Process{}, err
+ }
+ pid, err := strconv.Atoi(fields["MainPID"])
+ if err != nil || pid < 0 {
+ return Process{}, ErrConfig
+ }
+ if pid == 0 {
+ return Process{}, nil
+ }
+ return Identity(pid)
+}
+func Current(ctx context.Context, p Process) error {
+ now, err := MainProcess(ctx)
+ if err != nil || p.PID <= 0 || now != p {
+ return ErrConfig
+ }
+ return nil
+}
+
+// Acquire serializes changes, the #367 refresh and both probe variants across
+// root processes. The caller must provide a deadline. No background poll exists.
+func Acquire(ctx context.Context) (*Lease, error) {
+ c, err := Load()
+ if err != nil || c == nil {
+ return nil, err
+ }
+ if _, ok := ctx.Deadline(); !ok {
+ return nil, ErrConfig
+ }
+ if err := os.Mkdir(RuntimeDir, 0700); err != nil && !errors.Is(err, os.ErrExist) {
+ return nil, err
+ }
+ fd, err := unix.Openat2(unix.AT_FDCWD, RuntimeDir+"/lock", &unix.OpenHow{Flags: unix.O_RDWR | unix.O_CLOEXEC | unix.O_NOFOLLOW | unix.O_CREAT, Mode: 0600, Resolve: unix.RESOLVE_NO_SYMLINKS})
+ if err != nil {
+ return nil, err
+ }
+ f := os.NewFile(uintptr(fd), "hairpin lock")
+ fail := func(err error) (*Lease, error) { f.Close(); return nil, err }
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil || st.Uid != 0 || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0777 != 0600 || st.Nlink != 1 {
+ return fail(ErrConfig)
+ }
+ // The protected directory is read through the file checker as well.
+ if _, err := hostenv.ReadGroupFile(RuntimeDir+"/lock", 0, 0600); err != nil {
+ return fail(err)
+ }
+ for {
+ err = unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB)
+ if err == nil {
+ break
+ }
+ if !errors.Is(err, unix.EWOULDBLOCK) {
+ return fail(err)
+ }
+ timer := time.NewTimer(20 * time.Millisecond)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return fail(ctx.Err())
+ case <-timer.C:
+ }
+ }
+ l := &Lease{Config: *c, lock: f}
+ b, err := hostenv.ReadGroupFile(RuntimeDir+"/state.json", 0, 0600)
+ if errors.Is(err, os.ErrNotExist) {
+ return l, nil
+ }
+ if err != nil || json.Unmarshal(b, &l.State) != nil {
+ return fail(ErrConfig)
+ }
+ return l, nil
+}
+func (l *Lease) Close() { l.lock.Close() }
+func (l *Lease) Save(state State) error {
+ b, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ // Only root can create these siblings. A prior interrupted write is replaced
+ // without following its leaf; no agent-owned directory appears in the path.
+ path := RuntimeDir + "/state.new"
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if errors.Is(err, os.ErrExist) {
+ if err = os.Remove(path); err != nil {
+ return err
+ }
+ f, err = os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ }
+ if err != nil {
+ return err
+ }
+ defer os.Remove(path)
+ _, err = f.Write(b)
+ if err == nil {
+ err = f.Sync()
+ }
+ closed := f.Close()
+ if err != nil {
+ return err
+ }
+ if closed != nil {
+ return closed
+ }
+ if err = os.Rename(path, RuntimeDir+"/state.json"); err != nil {
+ return err
+ }
+ dir, err := os.Open(RuntimeDir)
+ if err != nil {
+ return err
+ }
+ defer dir.Close()
+ if err = dir.Sync(); err == nil {
+ l.State = state
+ }
+ return err
+}
+
+func run(ctx context.Context, input string, args ...string) ([]byte, error) {
+ c := exec.CommandContext(ctx, args[0], args[1:]...)
+ if input != "" {
+ c.Stdin = strings.NewReader(input)
+ }
+ out, err := c.CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("group_hairpin_operation: %s: %w", args[0], err)
+ }
+ return out, nil
+}
+
+// nft's numeric, stateless output has stable tokens. Comparing every token
+// refuses an extra rule, chain, port, address or conntrack bypass as well as a
+// missing rule. No request text enters either the script or the comparison.
+func (l *Lease) Verify(ctx context.Context) error {
+ want, err := l.Config.Rules()
+ if err != nil {
+ return err
+ }
+ got, err := run(ctx, "", "nft", "-s", "-nn", "-y", "list", "table", "inet", Table)
+ if err != nil {
+ return err
+ }
+ compact := func(s string) string { return strings.Join(strings.Fields(s), "") }
+ if compact(string(got)) != compact(want) {
+ return ErrConfig
+ }
+ return nil
+}
+func (l *Lease) Install(ctx context.Context) error {
+ rules, err := l.Config.Rules()
+ if err != nil {
+ return err
+ }
+ // add is idempotent for a table. Delete+recreate in this single transaction
+ // replaces only our table, never the independently owned IMDS denial.
+ _, err = run(ctx, "add table inet "+Table+"\ndelete table inet "+Table+"\n"+rules, "nft", "-f", "-")
+ return err
+}
+func (l *Lease) Addresses(ctx context.Context, on bool) error {
+ // Refuse a replaced or foreign interface before modifying anything.
+ found, err := l.dummyPresent(ctx)
+ if err != nil {
+ return err
+ }
+ if !found {
+ if !on {
+ return nil
+ }
+ return ErrConfig
+ }
+ if !on {
+ _, err = run(ctx, "", "ip", "-4", "addr", "flush", "dev", Interface)
+ if err != nil {
+ return err
+ }
+ return l.CheckAddresses(ctx, false)
+ }
+ for _, setting := range []struct{ name, value string }{{"arp_ignore", "1"}, {"arp_announce", "2"}} {
+ b, err := os.ReadFile(filepath.Join("/proc/sys/net/ipv4/conf/all", setting.name))
+ if err != nil || strings.TrimSpace(string(b)) != setting.value {
+ return ErrConfig
+ }
+ }
+ // No broader destination can reach the interface, even after a partial
+ // activation. Removing old addresses precedes every new assignment.
+ if _, err = run(ctx, "", "ip", "-4", "addr", "flush", "dev", Interface); err != nil {
+ return err
+ }
+ for _, ip := range l.Config.PublicIPs {
+ if _, err = run(ctx, "", "ip", "addr", "add", ip+"/32", "dev", Interface); err != nil {
+ return err
+ }
+ // Without a preferred primary source, Linux selects the destination EIP as
+ // the client source. Replies to its ephemeral port would meet the fence.
+ if _, err = run(ctx, "", "ip", "route", "replace", "table", "local", "local", ip+"/32", "dev", Interface, "src", l.Config.PrimaryIPv4); err != nil {
+ return err
+ }
+ }
+ return l.CheckAddresses(ctx, true)
+}
+
+// WatchExit uses a kernel process descriptor, not a new polling cadence. The
+// descriptor pins the process across PID reuse. Call cancel on failed enable.
+func WatchExit(p Process, exited func()) (func(), error) {
+ fd, err := unix.PidfdOpen(p.PID, 0)
+ if err != nil {
+ return nil, err
+ }
+ now, err := Identity(p.PID)
+ if err != nil || now != p {
+ unix.Close(fd)
+ return nil, ErrConfig
+ }
+ stopR, stopW, err := os.Pipe()
+ if err != nil {
+ unix.Close(fd)
+ return nil, err
+ }
+ go func() {
+ defer unix.Close(fd)
+ defer stopR.Close()
+ defer stopW.Close()
+ fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}, {Fd: int32(stopR.Fd()), Events: unix.POLLIN}}
+ for {
+ _, err := unix.Poll(fds, -1)
+ if err == unix.EINTR {
+ continue
+ }
+ if err == nil && fds[0].Revents != 0 {
+ exited()
+ }
+ return
+ }
+ }()
+ return func() { stopW.Close() }, nil
+}
+
+func Load() (*Config, error) { return loadSnapshot() }
+
+// Prepare creates only the dormant interface. It never assigns an EIP.
+func (l *Lease) Prepare(ctx context.Context) error {
+ present, err := l.dummyPresent(ctx)
+ if err != nil {
+ return err
+ }
+ if !present {
+ if _, err = run(ctx, "", "ip", "link", "add", Interface, "type", "dummy"); err != nil {
+ return err
+ }
+ }
+ if err := l.CheckAddresses(ctx, false); err != nil {
+ return err
+ }
+ if _, err := run(ctx, "", "ip", "link", "set", "dev", Interface, "up"); err != nil {
+ return err
+ }
+ if err := l.Install(ctx); err != nil {
+ return err
+ }
+ return l.Verify(ctx)
+}
+
+// Read back the complete IPv4 inventory. An extra non-ingress address must
+// never inherit the exemption or be silently treated as an ingress address.
+func (l *Lease) CheckAddresses(ctx context.Context, on bool) error {
+ raw, err := run(ctx, "", "ip", "-j", "-4", "addr", "show", "dev", Interface)
+ if err != nil {
+ return err
+ }
+ var links []struct {
+ Addrs []struct {
+ Local string `json:"local"`
+ Prefix int `json:"prefixlen"`
+ } `json:"addr_info"`
+ }
+ if json.Unmarshal(raw, &links) != nil || len(links) != 1 {
+ return ErrConfig
+ }
+ seen := map[string]bool{}
+ for _, a := range links[0].Addrs {
+ if !on || a.Prefix != 32 || !slices.Contains(l.Config.PublicIPs, a.Local) || seen[a.Local] {
+ return ErrConfig
+ }
+ seen[a.Local] = true
+ }
+ if on && len(seen) != len(l.Config.PublicIPs) {
+ return ErrConfig
+ }
+ return nil
+}
+
+func (l *Lease) dummyPresent(ctx context.Context) (bool, error) {
+ raw, err := run(ctx, "", "ip", "-j", "-d", "link", "show")
+ if err != nil {
+ return false, err
+ }
+ var links []struct {
+ Name string `json:"ifname"`
+ LinkInfo struct {
+ Kind string `json:"info_kind"`
+ } `json:"linkinfo"`
+ }
+ if json.Unmarshal(raw, &links) != nil {
+ return false, ErrConfig
+ }
+ found := false
+ for _, link := range links {
+ if link.Name == Interface {
+ if link.LinkInfo.Kind != "dummy" {
+ return false, ErrConfig
+ }
+ found = true
+ }
+ }
+
+ return found, nil
+}
diff --git a/internal/hairpin/native_linux_test.go b/internal/hairpin/native_linux_test.go
new file mode 100644
index 000000000..656e79f80
--- /dev/null
+++ b/internal/hairpin/native_linux_test.go
@@ -0,0 +1,65 @@
+//go:build linux
+
+package hairpin
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestHairpinFenceReadback(t *testing.T) {
+ c := fixtureConfig()
+ rules, err := c.Rules()
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ t.Setenv("PATH", dir)
+ for _, tc := range []struct {
+ name, body string
+ ok bool
+ }{
+ {"verified", rules, true},
+ {"missing", "", false},
+ {"extra-port", strings.Replace(rules, "{ 80, 443 }", "{ 80, 443, 3333 }", 1), false},
+ {"missing-input", strings.Replace(rules, "hook input", "hook forward", 1), false},
+ {"foreign-address", strings.ReplaceAll(rules, "9.9.9.9", "8.8.4.4"), false},
+ {"established-bypass", strings.Replace(rules, " ip daddr", " ct state established accept\n ip daddr", 1), false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ script := "#!/bin/sh\n/bin/cat <<'RULES'\n" + tc.body + "\nRULES\n"
+ if err := os.WriteFile(filepath.Join(dir, "nft"), []byte(script), 0700); err != nil {
+ t.Fatal(err)
+ }
+ l := &Lease{Config: c}
+ if err := l.Verify(context.Background()); (err == nil) != tc.ok {
+ t.Fatalf("readback %s: %v", tc.name, err)
+ }
+ })
+ }
+}
+
+func TestHairpinAddressReadback(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("PATH", dir)
+ for _, tc := range []struct {
+ body string
+ on, ok bool
+ }{
+ {`[{"addr_info":[{"local":"8.8.8.8","prefixlen":32},{"local":"9.9.9.9","prefixlen":32}]}]`, true, true},
+ {`[{"addr_info":[{"local":"8.8.8.8","prefixlen":32},{"local":"9.9.9.9","prefixlen":32},{"local":"8.8.4.4","prefixlen":32}]}]`, true, false},
+ {`[{"addr_info":[{"local":"8.8.8.8","prefixlen":24},{"local":"9.9.9.9","prefixlen":32}]}]`, true, false},
+ {`[{"addr_info":[]}]`, false, true},
+ {`[{"addr_info":[{"local":"8.8.8.8","prefixlen":32}]}]`, false, false},
+ } {
+ if err := os.WriteFile(filepath.Join(dir, "ip"), []byte("#!/bin/sh\n/bin/cat <<'JSON'\n"+tc.body+"\nJSON\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := (&Lease{Config: fixtureConfig()}).CheckAddresses(context.Background(), tc.on); (err == nil) != tc.ok {
+ t.Fatalf("%s: %v", tc.body, err)
+ }
+ }
+}
diff --git a/internal/hairpin/native_other.go b/internal/hairpin/native_other.go
new file mode 100644
index 000000000..6dd021baa
--- /dev/null
+++ b/internal/hairpin/native_other.go
@@ -0,0 +1,38 @@
+//go:build !linux
+
+package hairpin
+
+import (
+ "context"
+ "net"
+)
+
+func Load() (*Config, error) {
+ if !GroupPresent() {
+ return nil, nil
+ }
+ return nil, ErrUnsupported
+}
+
+func Identity(int) (Process, error) { return Process{}, ErrUnsupported }
+func Authenticate(context.Context, net.Conn, Process) error { return ErrUnsupported }
+func Current(context.Context, Process) error { return ErrUnsupported }
+func Acquire(context.Context) (*Lease, error) {
+ c, err := Load()
+ if err != nil || c == nil {
+ return nil, err
+ }
+ return nil, ErrUnsupported
+}
+func (l *Lease) Close() {}
+func (l *Lease) Save(State) error { return ErrUnsupported }
+func (l *Lease) Verify(context.Context) error { return ErrUnsupported }
+func (l *Lease) Install(context.Context) error { return ErrUnsupported }
+func (l *Lease) Addresses(context.Context, bool) error { return ErrUnsupported }
+func WatchExit(Process, func()) (func(), error) { return nil, ErrUnsupported }
+
+func (l *Lease) Prepare(context.Context) error { return ErrUnsupported }
+
+func (l *Lease) CheckAddresses(context.Context, bool) error { return ErrUnsupported }
+
+func MainProcess(context.Context) (Process, error) { return Process{}, ErrUnsupported }
diff --git a/internal/hairpin/rules.go b/internal/hairpin/rules.go
new file mode 100644
index 000000000..e8c707bba
--- /dev/null
+++ b/internal/hairpin/rules.go
@@ -0,0 +1,148 @@
+// Package hairpin owns the group-only local ingress configuration and fence.
+package hairpin
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/netip"
+ "regexp"
+ "slices"
+ "strings"
+)
+
+const ConfigPath = "/etc/carlos/group-ingress.json"
+const Interface = "carlos-hairpin"
+const Table = "carlos_hairpin"
+
+var ErrConfig = errors.New("group_hairpin_configuration")
+var ErrUnsupported = errors.New("group_hairpin_unsupported")
+
+// Config extends Task 3's sole root-owned ingress snapshot. PublicIPv4 comes
+// from protected IMDSv2, not the signed document's private address or an EIP.
+type Config struct {
+ V int `json:"v"`
+ Region string `json:"region"`
+ PublicIPs []string `json:"public_ips"`
+ PublicIPv4 string `json:"public_ipv4"`
+ PrivateCIDR string `json:"private_cidr"`
+ PrimaryIPv4 string `json:"primary_ipv4"`
+ BootID string `json:"boot_id"`
+ Account string `json:"account"`
+ InstanceID string `json:"iid"`
+}
+
+var bootID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
+var accountID = regexp.MustCompile(`^[0-9]{12}$`)
+var instanceID = regexp.MustCompile(`^i-[0-9a-f]{8,17}$`)
+var regionCode = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
+var nonpublic = []netip.Prefix{
+ netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8"),
+ netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("127.0.0.0/8"),
+ netip.MustParsePrefix("169.254.0.0/16"), netip.MustParsePrefix("172.16.0.0/12"),
+ netip.MustParsePrefix("192.0.0.0/24"), netip.MustParsePrefix("192.0.2.0/24"),
+ netip.MustParsePrefix("192.88.99.0/24"), netip.MustParsePrefix("192.168.0.0/16"),
+ netip.MustParsePrefix("198.18.0.0/15"), netip.MustParsePrefix("198.51.100.0/24"),
+ netip.MustParsePrefix("203.0.113.0/24"), netip.MustParsePrefix("224.0.0.0/4"), netip.MustParsePrefix("240.0.0.0/4"),
+}
+
+func PublicIPv4(s string) bool {
+ a, err := netip.ParseAddr(s)
+ if err != nil || !a.Is4() || a.String() != s || !a.IsGlobalUnicast() {
+ return false
+ }
+ for _, p := range nonpublic {
+ if p.Contains(a) {
+ return false
+ }
+ }
+ return true
+}
+
+func (c Config) Validate() error {
+ if c.V != 1 || !regionCode.MatchString(c.Region) || !bootID.MatchString(c.BootID) || !accountID.MatchString(c.Account) || !instanceID.MatchString(c.InstanceID) || !PublicIPv4(c.PublicIPv4) || len(c.PublicIPs) < 1 || len(c.PublicIPs) > 16 {
+ return ErrConfig
+ }
+ primary, err := netip.ParseAddr(c.PrimaryIPv4)
+ if err != nil || !primary.Is4() || !primary.IsPrivate() || primary.String() != c.PrimaryIPv4 {
+ return ErrConfig
+ }
+ cidr, err := netip.ParsePrefix(c.PrivateCIDR)
+ if err != nil || !cidr.Addr().Is4() || !cidr.Addr().IsPrivate() || cidr.Masked().String() != c.PrivateCIDR || !cidr.Contains(primary) {
+ return ErrConfig
+ }
+ seen := map[string]bool{}
+ for _, ip := range c.PublicIPs {
+ if !PublicIPv4(ip) || seen[ip] || ip == c.PublicIPv4 {
+ return ErrConfig
+ }
+ seen[ip] = true
+ }
+ return nil
+}
+
+// Exact keys, no duplicates, no nulls, and one object only. Go's ordinary
+// decoder alone accepts duplicate and case-insensitive field names.
+func Parse(raw []byte, region, boot, account, iid string) (Config, error) {
+ var c Config
+ if len(raw) > 65536 {
+ return c, ErrConfig
+ }
+ d := json.NewDecoder(bytes.NewReader(raw))
+ tok, err := d.Token()
+ if err != nil || tok != json.Delim('{') {
+ return c, ErrConfig
+ }
+ keys := map[string]bool{}
+ for d.More() {
+ tok, err := d.Token()
+ if err != nil {
+ return c, ErrConfig
+ }
+ key, ok := tok.(string)
+ if !ok || keys[key] || !slices.Contains([]string{"v", "region", "public_ips", "public_ipv4", "primary_ipv4", "private_cidr", "boot_id", "account", "iid"}, key) {
+ return c, ErrConfig
+ }
+ keys[key] = true
+ var value json.RawMessage
+ if d.Decode(&value) != nil || bytes.Equal(value, []byte("null")) {
+ return c, ErrConfig
+ }
+ }
+ if _, err := d.Token(); err != nil || len(keys) != 9 {
+ return c, ErrConfig
+ }
+ if d.Decode(new(any)) != io.EOF || json.Unmarshal(raw, &c) != nil {
+ return c, ErrConfig
+ }
+ if c.Region != region || c.BootID != boot || c.Account != account || c.InstanceID != iid {
+ return c, ErrConfig
+ }
+ return c, c.Validate()
+}
+
+// From any tenant, sidecar or rootfs process, the only box-local endpoints reachable on an ingress EIP are TCP 80 and 443; every other port and protocol to those addresses is dropped.
+//
+// Both hooks enforce this one fence. OUTPUT also preserves the existing UDP
+// probe's synchronous EPERM contract. INPUT covers local delivery, including
+// any routed namespace traffic. There is deliberately no established-flow
+// exception: an earlier connection cannot retain access to another port.
+func (c Config) Rules() (string, error) {
+ if err := c.Validate(); err != nil {
+ return "", err
+ }
+ ips := append([]string{}, c.PublicIPs...)
+ slices.Sort(ips)
+ dst := strings.Join(ips, ", ")
+ var out strings.Builder
+ fmt.Fprintf(&out, "table inet %s {\n", Table)
+ for _, hook := range []string{"output", "input"} {
+ fmt.Fprintf(&out, " chain %s { type filter hook %s priority -300; policy accept;\n", hook, hook)
+ fmt.Fprintf(&out, " ip daddr { %s } tcp dport { 80, 443 } accept\n", dst)
+ fmt.Fprintf(&out, " ip daddr { %s } drop\n }\n", dst)
+ }
+ out.WriteString("}\n")
+ return out.String(), nil
+}
diff --git a/internal/hairpin/rules_test.go b/internal/hairpin/rules_test.go
new file mode 100644
index 000000000..67cd61ed6
--- /dev/null
+++ b/internal/hairpin/rules_test.go
@@ -0,0 +1,92 @@
+package hairpin
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func fixtureConfig() Config {
+ return Config{V: 1, Region: "ie", PublicIPs: []string{"8.8.8.8", "9.9.9.9"}, PublicIPv4: "1.1.1.1", PrivateCIDR: "172.31.0.0/16", PrimaryIPv4: "172.31.7.19", BootID: "12345678-1234-1234-1234-123456789abc", Account: "123456789012", InstanceID: "i-0123456789abcdef0"}
+}
+
+func TestHairpinRules(t *testing.T) {
+ c := fixtureConfig()
+ rules, err := c.Rules()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range []string{"table inet carlos_hairpin", "hook output", "hook input", "tcp dport { 80, 443 }", "ip daddr { 8.8.8.8, 9.9.9.9 } drop"} {
+ if !strings.Contains(rules, s) {
+ t.Errorf("missing %s in %s", s, rules)
+ }
+ }
+ if strings.Count(rules, " accept\n") != 2 || strings.Count(rules, " drop\n") != 2 {
+ t.Fatal("unexpected fence verdict", rules)
+ }
+ for _, s := range []string{"dnat", "redirect", "route_localnet", "18080", "18443", "carlos_group_imds", "ct state established"} {
+ if strings.Contains(rules, s) {
+ t.Errorf("unexpected %s", s)
+ }
+ }
+ for _, ips := range [][]string{nil, {"8.8.8.8", "8.8.8.8"}, {"8.8.8.8; flush ruleset"}, {"example.com"}, {"10.0.0.1"}, {"224.0.0.1"}, {"192.0.2.1"}, {"100.64.0.1"}, {"240.0.0.1"}, {"::ffff:8.8.8.8"}} {
+ bad := c
+ bad.PublicIPs = ips
+ if _, err := bad.Rules(); err == nil {
+ t.Errorf("accepted %v", ips)
+ }
+ }
+}
+
+func TestHairpinPublicIdentity(t *testing.T) {
+ c := fixtureConfig()
+ raw, _ := json.Marshal(c)
+ if _, err := Parse(raw, c.Region, c.BootID, c.Account, c.InstanceID); err != nil {
+ t.Fatal(err)
+ }
+ for _, ip := range []string{"", "10.0.0.1", "127.0.0.1", "192.0.2.1", "198.18.0.1", "100.64.0.1", "0.1.2.3", "224.0.0.1", "255.255.255.255", "192.0.0.9", "192.88.99.1", "::ffff:1.1.1.1", "8.8.8.8"} {
+ bad := c
+ bad.PublicIPv4 = ip
+ b, _ := json.Marshal(bad)
+ if _, err := Parse(b, c.Region, c.BootID, c.Account, c.InstanceID); err == nil {
+ t.Errorf("accepted source %q", ip)
+ }
+ }
+ for _, raw := range [][]byte{append(raw, []byte("{}")...), []byte(strings.Replace(string(raw), `"v":1`, `"v":1,"v":1`, 1)), []byte(strings.Replace(string(raw), `"v":1`, `"v":2`, 1)), []byte(strings.Replace(string(raw), `"v":1`, `"v":1,"unknown":true`, 1))} {
+ if _, err := Parse(raw, c.Region, c.BootID, c.Account, c.InstanceID); err == nil {
+ t.Errorf("accepted %s", raw)
+ }
+ }
+ for _, mismatch := range []struct{ region, boot, account, iid string }{{"us", c.BootID, c.Account, c.InstanceID}, {c.Region, "other", c.Account, c.InstanceID}, {c.Region, c.BootID, "other", c.InstanceID}, {c.Region, c.BootID, c.Account, "other"}} {
+ if _, err := Parse(raw, mismatch.region, mismatch.boot, mismatch.account, mismatch.iid); err == nil {
+ t.Fatal("accepted mismatched binding")
+ }
+ }
+}
+
+func TestHairpinFixedSelection(t *testing.T) {
+ root := t.TempDir()
+ missing := filepath.Join(root, "missing", "group.json")
+ if groupPresentAt(missing, "") {
+ t.Fatal("fixed box selected")
+ }
+ if !groupPresentAt(missing, "group") {
+ t.Fatal("group flag did not refuse missing marker")
+ }
+ marker := filepath.Join(root, "group.json")
+ if err := os.Symlink("missing", marker); err != nil {
+ t.Fatal(err)
+ }
+ if !groupPresentAt(marker, "") {
+ t.Fatal("dangling marker fell back to fixed")
+ }
+ file := filepath.Join(root, "file")
+ if err := os.WriteFile(file, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if groupPresentAt(filepath.Join(file, "group.json"), "") {
+ t.Fatal("unrelated invalid fixed directory selected group")
+ }
+}
diff --git a/internal/hairpin/snapshot.go b/internal/hairpin/snapshot.go
new file mode 100644
index 000000000..990f527ea
--- /dev/null
+++ b/internal/hairpin/snapshot.go
@@ -0,0 +1,76 @@
+package hairpin
+
+import (
+ "crypto/sha256"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/hostenv"
+)
+
+// Load is inert without a group marker. A present but invalid marker refuses;
+// flags cannot select the fixed path. Every reader verifies boot and ownership.
+func loadGroupIdentity() (*hostenv.GroupConfig, error) {
+ if !GroupPresent() {
+ return nil, nil
+ }
+ marker, err := hostenv.ReadGroupFile(hostenv.GroupConfigPath, 0, 0644)
+ if err != nil {
+ return nil, err
+ }
+ g, err := hostenv.ParseGroupConfig(marker)
+ if err != nil {
+ return nil, err
+ }
+ boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ if err != nil || g.BootID != strings.TrimSpace(string(boot)) {
+ return nil, ErrConfig
+ }
+ identity, err := hostenv.ReadGroupFile("/etc/carlos/group-identity.json", 0, 0644)
+ if err != nil {
+ return nil, err
+ }
+ certs, err := boxid.EmbeddedCerts()
+ if err != nil {
+ return nil, err
+ }
+ verifier := boxid.Verifier{Account: g.Account, Certs: certs}
+ // Enroll checks the record's derived box reference as well as the document.
+ sum := sha256.Sum256([]byte("carlos-box-ref-v1|" + g.Account + "|" + g.InstanceID))
+ ref := fmt.Sprintf("g-%x", sum[:10])
+ if _, err = verifier.Enroll(identity, boxid.Expect{Box: ref, AWSRegion: g.AWSRegion, TofuInstanceID: g.InstanceID}); err != nil {
+ return nil, err
+ }
+ return &g, nil
+}
+
+func VerifyIdentity() error { _, err := loadGroupIdentity(); return err }
+
+func loadSnapshot() (*Config, error) {
+ g, err := loadGroupIdentity()
+ if err != nil || g == nil {
+ return nil, err
+ }
+ raw, err := hostenv.ReadGroupFile(ConfigPath, 0, 0644)
+ if err != nil {
+ return nil, err
+ }
+ c, err := Parse(raw, g.Region, g.BootID, g.Account, g.InstanceID)
+ if err != nil {
+ return nil, err
+ }
+ return &c, nil
+}
+
+// Match Task 3's fixed/group selection: a visible marker (even a dangling
+// symlink) cannot be disabled by an environment flag. An inaccessible parent
+// on an otherwise fixed box retains the existing fixed behavior.
+func GroupPresent() bool {
+ return groupPresentAt(hostenv.GroupConfigPath, os.Getenv("CARLOS_BOX_REFERENCE"))
+}
+func groupPresentAt(path, reference string) bool {
+ _, err := os.Lstat(path)
+ return err == nil || reference == "group"
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 04fa1c6d7..568b545b9 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -193,6 +193,7 @@ import (
"github.com/carlosframework/platform/internal/groupadmission"
"github.com/carlosframework/platform/internal/hadeparture"
"github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hairpin"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/instancefs"
@@ -3947,6 +3948,12 @@ func imdsLeaf(client *http.Client, token, path string) (string, int) {
// "unknown", never as an error: a box without a discoverable public IP is a
// valid deployment whose DNS checks simply stand down.
func readPublicIP() string {
+ if c, err := hairpin.Load(); c != nil || err != nil {
+ if err != nil {
+ return ""
+ }
+ return c.PublicIPv4
+ }
client := &http.Client{Timeout: 2 * time.Second}
token := imdsToken(client)
if token == "" {
diff --git a/internal/host/awsaddr.go b/internal/host/awsaddr.go
index f63823b2b..fde011c0c 100644
--- a/internal/host/awsaddr.go
+++ b/internal/host/awsaddr.go
@@ -7,6 +7,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/hairpin"
)
// imdsAddresses is the AWS adapter of AddressSource (region HA spec 2
@@ -73,5 +74,22 @@ func (s imdsAddresses) BoxAddresses() (BoxAddresses, bool) {
// publication that host.env does not fully answer; a failed request makes
// that publication unknown, and the pass writes nothing and retries.
func boxAddressSource(getenv func(string) string) AddressSource {
+ if c, err := hairpin.Load(); c != nil || err != nil {
+ return groupAddressSnapshot{config: c, err: err}
+ }
return envAddresses{getenv: getenv, provider: newIMDSAddresses()}
}
+
+// Group addresses remain bound to root's verified boot snapshot until an
+// explicit reseed. This replaces the existing repeated IMDS address adapter.
+type groupAddressSnapshot struct {
+ config *hairpin.Config
+ err error
+}
+
+func (s groupAddressSnapshot) BoxAddresses() (BoxAddresses, bool) {
+ if s.err != nil || s.config == nil {
+ return BoxAddresses{}, false
+ }
+ return BoxAddresses{Private: s.config.PrimaryIPv4, PrivateCIDR: s.config.PrivateCIDR, Public: s.config.PublicIPv4}, true
+}
diff --git a/internal/host/claimstop_run.go b/internal/host/claimstop_run.go
index 415f22200..49563ed6c 100644
--- a/internal/host/claimstop_run.go
+++ b/internal/host/claimstop_run.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/hairpin"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/moves"
@@ -19,6 +20,31 @@ import (
)
func RunInstanceControl(args []string) {
+ if len(args) == 1 && args[0] == "--group-hairpin-verify-identity" {
+ if os.Geteuid() != 0 {
+ log.Fatal(hairpin.ErrConfig)
+ }
+ if err := hairpin.VerifyIdentity(); err != nil {
+ log.Fatal(err)
+ }
+ return
+ }
+ if len(args) == 1 && args[0] == "--group-hairpin-install" {
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ if err := instancectl.InstallDormantGroupHairpin(ctx); err != nil {
+ log.Fatal(err)
+ }
+ return
+ }
+ if len(args) == 1 && args[0] == "--group-hairpin-reset" {
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ if err := instancectl.ClearGroupHairpin(ctx); err != nil {
+ log.Fatal(err)
+ }
+ return
+ }
cfg, err := demo.BoxConfig(os.Getenv)
if err != nil || cfg.BoxMode() && hostwrite.Enabled(os.Getenv) {
log.Fatal("instance-control: demo box configuration refused")
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go
index 6948c9454..149c11192 100644
--- a/internal/host/group_admission.go
+++ b/internal/host/group_admission.go
@@ -23,6 +23,9 @@ import (
var armedFixedAdmission atomic.Pointer[fixedAdmission]
type fixedAdmission struct {
+ hairpin func(bool) error
+ hairpinMu sync.Mutex
+ hairpinReady atomic.Bool
launchFailure string
workMu sync.Mutex
workCtx context.Context
@@ -66,7 +69,7 @@ func (a *fixedAdmission) bind(s *activator.Service, b *activator.ExecBackend) {
if a == nil {
return
}
- s.TenantAdmittedFunc = a.state.Admitted
+ s.TenantAdmittedFunc = a.TenantAdmitted
s.TenantAdmissionStartingFunc = a.TenantAdmissionStarting
s.TenantStartAllowed = a.startAllowed
s.TenantExempt = a.exempt
@@ -108,12 +111,12 @@ func (a *fixedAdmission) applyRole(role boxroles.Role, known bool) error {
func (a *fixedAdmission) startAllowed() bool {
a.mu.Lock()
defer a.mu.Unlock()
- return !a.closed && a.refusal == "" && a.known && a.role == boxroles.Serve && a.state.Admitted()
+ return !a.closed && a.refusal == "" && a.known && a.role == boxroles.Serve && a.TenantAdmitted()
}
func (a *fixedAdmission) EdgesRole() (boxroles.Role, bool, bool) {
a.mu.Lock()
defer a.mu.Unlock()
- if !a.state.Admitted() {
+ if !a.TenantAdmitted() {
return boxroles.Booting, false, false
}
return a.role, true, false
@@ -155,11 +158,25 @@ func (a *fixedAdmission) tick(ctx context.Context) {
a.mu.Unlock()
// No orchestration lock spans the provider call. Close can win immediately.
if err := a.state.Admit(ctx, launch, complete, a.initialHealthy); err == nil {
+ a.hairpinMu.Lock()
a.mu.Lock()
- if !a.closed {
+ closed, change := a.closed, a.hairpin
+ a.mu.Unlock()
+ var hairpinErr error
+ if !closed && change != nil {
+ hairpinErr = change(true)
+ }
+ a.mu.Lock()
+ if !a.closed && hairpinErr == nil {
+ a.hairpinReady.Store(true)
a.openOnce.Do(func() { close(a.opened); log.Print("tenant admission is open. accepting tenant work") })
}
a.mu.Unlock()
+ a.hairpinMu.Unlock()
+ if hairpinErr != nil {
+ log.Printf("group hairpin activation failed: %v", hairpinErr)
+ a.Close()
+ }
} else {
a.mu.Lock()
if a.group && !errors.Is(err, groupadmission.ErrNotReady) {
@@ -195,6 +212,13 @@ func (a *fixedAdmission) Close() {
a.workCancel()
}
a.workMu.Unlock()
+ a.hairpinMu.Lock()
+ if a.hairpin != nil {
+ if err := a.hairpin(false); err != nil {
+ log.Printf("group hairpin closure failed: %v", err)
+ }
+ }
+ a.hairpinMu.Unlock()
a.workWG.Wait()
log.Print("tenant admission is closed for shutdown")
}
@@ -241,7 +265,9 @@ func (a *fixedAdmission) armRoles(ctx context.Context, getenv func(string) strin
a.observe(groupadmission.Facts{EnvLoaded: true})
}
-func (a *fixedAdmission) TenantAdmitted() bool { return a.state.Admitted() }
+func (a *fixedAdmission) TenantAdmitted() bool {
+ return a.state.Admitted() && (a.hairpin == nil || a.hairpinReady.Load())
+}
func (a *fixedAdmission) TenantAdmissionExempt(rt registry.Route) bool { return a.exempt(rt) }
func (a *fixedAdmission) CloseTenantAdmission() { a.Close() }
@@ -280,7 +306,7 @@ func runWorkerBootPassAfterAdmission(ctx context.Context, admission *fixedAdmiss
func (a *fixedAdmission) TenantAdmissionStarting() bool {
a.mu.Lock()
defer a.mu.Unlock()
- return !a.closed && !a.state.Admitted()
+ return !a.closed && !a.TenantAdmitted()
}
func (a *fixedAdmission) logWaitingLocked(now time.Time) {
diff --git a/internal/host/group_boot.go b/internal/host/group_boot.go
index 2e1d5c4ad..2bdf45ec2 100644
--- a/internal/host/group_boot.go
+++ b/internal/host/group_boot.go
@@ -126,6 +126,9 @@ func configureGroupAdmission(ctx context.Context, a *fixedAdmission, c *hostenv.
a.completer = &groupReceiptCompleter{dir: groupReceiptDir, binding: binding, bootID: readBootID(bootIDPath), complete: adapter, now: time.Now, wait: groupLaunchWait, eligible: a.initialHealthy}
a.readerSelf = expect.Box
a.knownReaders = append([]string{}, c.KnownReaders...)
+ if err := configureGroupHairpin(a); err != nil {
+ return err
+ }
a.refusal = ""
return nil
}
diff --git a/internal/host/group_boot_budget_test.go b/internal/host/group_boot_budget_test.go
index f823f2ad9..e02ee3dc9 100644
--- a/internal/host/group_boot_budget_test.go
+++ b/internal/host/group_boot_budget_test.go
@@ -303,9 +303,19 @@ def urlopen(request,timeout):
metadata.append(path)
if path.endswith('/token'): return io.BytesIO(b'token')
if path.endswith('/signature'):return io.BytesIO(b'signature')
+ if path.endswith('/public-ipv4'):return io.BytesIO(b'1.1.1.1')
+ if path.endswith('/local-ipv4'):return io.BytesIO(b'172.31.7.19')
+ if path.endswith('/mac'):return io.BytesIO(b'0e:12:34:56:78:9a')
+ if path.endswith('/vpc-ipv4-cidr-blocks'):return io.BytesIO(b'172.31.0.0/16')
assert path.endswith('/document')
- return io.BytesIO(json.dumps(dict(accountId='123456789012',region='eu-west-1',instanceId='i-0123456789abcdef0',pendingTime=datetime.datetime.now(datetime.timezone.utc).isoformat())).encode())
-urllib.request.urlopen=urlopen
+ return io.BytesIO(json.dumps(dict(accountId='123456789012',region='eu-west-1',instanceId='i-0123456789abcdef0',privateIp='172.31.7.19',pendingTime=datetime.datetime.now(datetime.timezone.utc).isoformat())).encode())
+urllib.request.build_opener=lambda *args:type("Opener",(),{"open":staticmethod(urlopen)})()
+verified_identity=False
+def verify_identity(args,timeout):
+ global verified_identity
+ assert args==['/run/carlos-group-boot/bootstrap','instance-control','--group-hairpin-verify-identity'] and timeout==10
+ verified_identity=True
+subprocess.check_call=verify_identity
realopen=builtins.open
def fakeopen(path,*args,**kwargs):
if path=='/run/carlos-group-boot/bootstrap':return io.BytesIO(b'bootstrap')
@@ -314,13 +324,18 @@ def fakeopen(path,*args,**kwargs):
builtins.open=fakeopen
os.chmod=lambda *args:None
writes=[]
-def write(path,body,mode=0o644):writes.append(path)
+def write(path,body,mode=0o644):
+ if path=='/etc/carlos/group-ingress.json':
+ assert verified_identity, 'snapshot published before signed identity verification'
+ snapshot=json.loads(body)
+ assert snapshot['public_ipv4']=='1.1.1.1' and snapshot['primary_ipv4']=='172.31.7.19' and snapshot['private_cidr']=='172.31.0.0/16'
+ writes.append(path)
tree=ast.parse(source)
tree.body=[n for n in tree.body if not isinstance(n,ast.FunctionDef) or n.name!='write']
exec(compile(tree,'group-init.sh.tftpl','exec'))
-assert len(calls)==3 and decryptions==4 and len(metadata)==3,(calls,decryptions,metadata)
+assert len(calls)==3 and decryptions==4 and len(metadata)==7,(calls,decryptions,metadata)
assert len(writes)==4,writes
-print('boot: 2 SSM calls, 4 decrypted values, 1 versioned S3 GET, 3 IMDS requests')
+print('boot: 2 SSM calls, 4 decrypted values, 1 versioned S3 GET, 7 IMDS requests')
`
source, _ := json.Marshal(string(raw)[start : start+end])
program = strings.Replace(program, "SOURCE", string(source), 1)
diff --git a/internal/host/group_config_linux.go b/internal/host/group_config_linux.go
index 96d957864..b148d24c1 100644
--- a/internal/host/group_config_linux.go
+++ b/internal/host/group_config_linux.go
@@ -4,6 +4,7 @@ package host
import (
"encoding/json"
+ "errors"
"github.com/carlosframework/platform/internal/hostenv"
"golang.org/x/sys/unix"
"os"
@@ -17,6 +18,9 @@ func initializeGroupLaunch(c hostenv.GroupConfig) error {
if c.BootID != readBootID(bootIDPath) || !time.Now().Before(time.Unix(c.Deadline, 0)) {
return errGroupLaunch
}
+ if c, err := groupHairpinSnapshot(); err != nil || c == nil {
+ return errors.Join(err, errGroupLaunch)
+ }
uid, gid, err := bootstrapOwner(serviceUser, serviceUser)
if err != nil {
return err
diff --git a/internal/host/group_hairpin.go b/internal/host/group_hairpin.go
new file mode 100644
index 000000000..5396dc75f
--- /dev/null
+++ b/internal/host/group_hairpin.go
@@ -0,0 +1,57 @@
+package host
+
+import (
+ "context"
+ "os"
+ "time"
+
+ "github.com/carlosframework/platform/internal/controlsock"
+ "github.com/carlosframework/platform/internal/hairpin"
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+func groupHairpinSnapshot() (*hairpin.Config, error) {
+ c, err := hairpin.Load()
+ if err != nil || c == nil {
+ return nil, err
+ }
+ if v := os.Getenv("CARLOS_PUBLIC_IP"); v != "" && v != c.PublicIPv4 {
+ return nil, hairpin.ErrConfig
+ }
+ if v := os.Getenv("CARLOS_PRIVATE_IP"); v != "" && v != c.PrimaryIPv4 {
+ return nil, hairpin.ErrConfig
+ }
+ if v := os.Getenv("CARLOS_PRIVATE_CIDR"); v != "" && v != c.PrivateCIDR {
+ return nil, hairpin.ErrConfig
+ }
+ return c, nil
+}
+
+func configureGroupHairpin(a *fixedAdmission) error {
+ c, err := groupHairpinSnapshot()
+ if err != nil || c == nil {
+ return err
+ }
+ p, err := hairpin.Identity(os.Getpid())
+ if err != nil {
+ return err
+ }
+ client := instancectl.NewClient(controlsock.Path)
+ a.hairpin = func(enable bool) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ return client.GroupHairpin(ctx, enable, p)
+ }
+ return nil
+}
+
+// Task 4 calls this only after consuming its root maintenance permit, before
+// any edge stop or replacement. Staging trees have no live host interfaces.
+func (a *systemApplier) clearGroupHairpin() error {
+ if a.etcDir != "/etc" {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ return instancectl.ClearGroupHairpin(ctx)
+}
diff --git a/internal/host/group_hairpin_rootrunner_linux_test.go b/internal/host/group_hairpin_rootrunner_linux_test.go
new file mode 100644
index 000000000..dcd6d27d0
--- /dev/null
+++ b/internal/host/group_hairpin_rootrunner_linux_test.go
@@ -0,0 +1,926 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/base64"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/controlsock"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/hairpin"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+ "golang.org/x/sys/unix"
+)
+
+func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t) }
+
+// This witness permits IMDSv2 reads and traffic only to its own fixture. The
+// public-shaped EIPs have blackhole fallback routes, so closed-state probes
+// cannot leave the runner. It refuses an existing deployment, and fails rather
+// than skips when root, systemd, nft or cgroup v2 is missing. The agent process
+// uses production edge, admission and authenticated root operations; lifecycle
+// completion and the app backend are local fixtures, with no ASG/S3/SSM calls.
+func hairpinKernelWitness(t *testing.T) {
+ egressRootPrereqs(t)
+ for _, tool := range []string{"nft", "ip", "ss", "systemctl"} {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Fatal(err)
+ }
+ }
+ uid, gid := generationRunnerRegistryUser(t)
+ for _, path := range []string{"/etc/carlos", "/run/carlos", controlsock.Dir, hairpin.RuntimeDir} {
+ if err := os.Mkdir(path, 0755); err != nil {
+ t.Fatalf("fixture must not exist: %s: %v", path, err)
+ }
+ t.Cleanup(func() { os.RemoveAll(path) })
+ }
+ if err := os.Chmod(hairpin.RuntimeDir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chown("/run/carlos", uid, gid); err != nil {
+ t.Fatal(err)
+ }
+ scratch, err := os.MkdirTemp("/var/lib", "carlos-hairpin-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(scratch) })
+ if err := os.Chmod(scratch, 0755); err != nil {
+ t.Fatal(err)
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ payload := filepath.Join(scratch, "witness")
+ image, err := os.ReadFile(exe)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(payload, image, 0755); err != nil {
+ t.Fatal(err)
+ }
+ config := hairpinRunnerSnapshot(t)
+ for _, ip := range config.PublicIPs {
+ if out := hairpinCmd(t, "ip", "route", "show", "exact", ip+"/32"); strings.TrimSpace(out) != "" {
+ t.Fatal("pre-existing EIP route", out)
+ }
+ hairpinCmd(t, "ip", "route", "add", "blackhole", ip+"/32")
+ t.Cleanup(func() { exec.Command("ip", "route", "del", "blackhole", ip+"/32").Run() })
+ }
+ if _, err := net.InterfaceByName(hairpin.Interface); err == nil {
+ t.Fatal("hairpin interface already exists")
+ }
+ t.Cleanup(func() { exec.Command("ip", "link", "del", hairpin.Interface).Run() })
+ for _, table := range []string{hairpin.Table, "carlos_group_imds"} {
+ if exec.Command("nft", "list", "table", "inet", table).Run() == nil {
+ t.Fatal("table exists", table)
+ }
+ t.Cleanup(func() { exec.Command("nft", "delete", "table", "inet", table).Run() })
+ }
+ for _, setting := range []struct{ name, value string }{{"arp_ignore", "1"}, {"arp_announce", "2"}} {
+ path := "/proc/sys/net/ipv4/conf/all/" + setting.name
+ old, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.WriteFile(path, old, 0644) })
+ if err = os.WriteFile(path, []byte(setting.value), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ imds := fmt.Sprintf("table inet carlos_group_imds { chain output { type filter hook output priority -310; policy accept; meta skuid != { 0, %d } ip daddr 169.254.169.254 reject; meta skuid != { 0, %d } ip6 daddr fd00:ec2::254 reject; } chain forward { type filter hook forward priority -310; policy accept; ip daddr 169.254.169.254 reject; ip6 daddr fd00:ec2::254 reject; } }", uid, uid)
+ hairpinNFT(t, imds)
+ imdsBefore := hairpinCmd(t, "nft", "-s", "list", "table", "inet", "carlos_group_imds")
+ parent := instancectl.InstancesSlice
+ if egressShow(t, parent, "LoadState") != "not-found" {
+ t.Fatal("instances slice exists")
+ }
+ hairpinRunnerUnit(t, parent, "[Unit]\nDescription=Hairpin fixture slice\n[Slice]\n")
+ hairpinCmd(t, "systemctl", "start", parent)
+ // Parent set-property drop-ins belong to this fixture too.
+ t.Cleanup(func() {
+ for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} {
+ os.RemoveAll(filepath.Join(root, parent+".d"))
+ }
+ })
+ ctx, cancel := context.WithTimeout(t.Context(), 4*time.Minute)
+ defer cancel()
+ if err := instancectl.InstallDormantGroupHairpin(ctx); err != nil {
+ t.Fatal("dormant install", err)
+ }
+ hairpinAssertEmpty(t)
+ // Give the IPv6 metadata negative probe a real route and source. A missing
+ // IPv6 route must not be mistaken for enforcement of the sandbox policy.
+ if strings.TrimSpace(hairpinCmd(t, "ip", "-6", "route", "show", "exact", "fd00:ec2::254/128")) == "" {
+ const v6 = "carlos-hp-v6"
+ if _, err := net.InterfaceByName(v6); err == nil {
+ t.Fatal("IPv6 fixture interface exists")
+ }
+ hairpinCmd(t, "ip", "link", "add", v6, "type", "dummy")
+ t.Cleanup(func() { exec.Command("ip", "link", "del", v6).Run() })
+ hairpinCmd(t, "ip", "link", "set", v6, "up")
+ hairpinCmd(t, "ip", "-6", "addr", "add", "fd42:ca:5::1/128", "dev", v6, "nodad")
+ hairpinCmd(t, "ip", "-6", "route", "add", "fd00:ec2::254/128", "dev", v6, "src", "fd42:ca:5::1")
+ }
+ ctlLn, err := net.Listen("unix", controlsock.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Chown(controlsock.Path, uid, gid); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Chmod(controlsock.Path, 0600); err != nil {
+ t.Fatal(err)
+ }
+ srv := &instancectl.Server{PeerOK: func(net.Conn) error { return nil }, LocalAddrs: instancectl.LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ }, Logf: t.Logf}
+ serving, cancelServing := context.WithCancel(context.Background())
+ defer cancelServing()
+ ctlDone := make(chan error, 1)
+ go func() { ctlDone <- srv.Serve(serving, ctlLn) }()
+ t.Cleanup(func() { cancelServing(); ctlLn.Close(); <-ctlDone })
+ // An app backend observes what the real edge derived, including through an
+ // upgrade. It never trusts the caller's forwarding headers.
+ backend, err := net.Listen("unix", "/run/carlos/hairpin-app.sock")
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.Chown("/run/carlos/hairpin-app.sock", uid, gid)
+ os.Chmod("/run/carlos/hairpin-app.sock", 0600)
+ app := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
+ conn, rw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ fmt.Fprintf(rw, "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nX-Observed-Client: %s\r\n\r\n", r.Header.Get("X-Forwarded-For"))
+ rw.Flush()
+ io.Copy(conn, rw)
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ json.NewEncoder(w).Encode(map[string]string{"client": r.Header.Get("X-Forwarded-For"), "method": r.Method, "body": string(body), "host": r.Host})
+ })}
+ go app.Serve(backend)
+ t.Cleanup(func() { app.Close(); backend.Close() })
+ cert, key := hairpinRunnerCertificate(t)
+ for name, body := range map[string][]byte{"cert.pem": cert, "key.pem": key} {
+ if err = os.WriteFile(filepath.Join(scratch, name), body, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Start the actual service identity used by the root authenticator. The
+ // fixture replaces cloud startup with ready facts, retaining Close/tick and
+ // ordinary listener handling. No unprivileged caller gets an auth seam.
+ baseUnit, err := unitsFS.ReadFile("units/carlos-edge.service")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var lines []string
+ for _, line := range strings.Split(string(baseUnit), "\n") {
+ if strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") || strings.HasPrefix(line, "Wants=") || strings.HasPrefix(line, "EnvironmentFile=") {
+ continue
+ }
+ if strings.HasPrefix(line, "ExecStart=") {
+ line = "ExecStart=" + payload + " -test.run=^TestHairpinAgentPayload$ -test.v -test.timeout=4m"
+ }
+ if line == "Restart=always" {
+ line = "Restart=no"
+ }
+ if strings.HasPrefix(line, "ReadWritePaths=") {
+ line = "ReadWritePaths=/run/carlos"
+ }
+ lines = append(lines, line)
+ }
+ // Keep the actual service's hardening. Only deployment dependencies and
+ // cloud setup are fixture replacements. The group networking family and
+ // reset hooks are exactly those installed by the group boot template.
+ unit := strings.Join(lines, "\n") + "\n[Service]\nEnvironment=HAIRPIN_FIXTURE=" + scratch + "\nRestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK\nExecStartPre=+/usr/bin/systemctl start carlos-hairpin-reset.service\nExecStop=+/usr/bin/systemctl start carlos-hairpin-reset.service\nExecStopPost=+/usr/bin/systemctl start carlos-hairpin-reset.service\n"
+ hairpinRunnerUnit(t, "carlos-hairpin-reset.service", "[Service]\nType=oneshot\nExecStart="+payload+" instance-control --group-hairpin-reset\nTimeoutStartSec=70\n")
+ hairpinRunnerUnit(t, agentUnit, unit)
+ hairpinCmd(t, "systemctl", "start", agentUnit)
+ control := hairpinAgentClient()
+ hairpinAgentWait(t, control)
+ pid, err := strconv.Atoi(egressShow(t, agentUnit, "MainPID"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ identity, err := hairpin.Identity(pid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := instancectl.NewClient(controlsock.Path).GroupHairpin(ctx, true, identity); err == nil {
+ t.Fatal("root caller impersonated the current agent")
+ }
+ hairpinAssertEmpty(t)
+ // Maintenance can close a booting process before its first enable. Its
+ // delayed successful lifecycle callback must not reopen local ingress.
+ if err := instancectl.ClearGroupHairpin(ctx); err != nil {
+ t.Fatal(err)
+ }
+ hairpinAgentCall(t, control, "/admit-refused")
+ hairpinAssertEmpty(t)
+ hairpinCmd(t, "systemctl", "stop", agentUnit)
+ if err := instancectl.ClearGroupHairpin(ctx); err != nil {
+ t.Fatal(err)
+ }
+ hairpinCmd(t, "systemctl", "start", agentUnit)
+ hairpinAgentWait(t, control)
+ witnessed := map[string]bool{}
+ for cycle := 0; cycle < 2; cycle++ {
+ hairpinAgentCall(t, control, "/admit")
+ ports := hairpinListenerPorts(t)
+ hairpinAgentCall(t, control, "/check?ports="+strings.Join(ports, ","))
+ witnessed["agent"] = true
+ hairpinCallerChecks(t, *config, ports, false)
+ witnessed["root"] = true
+ for _, caller := range []string{"tenant", "sidecar", "rootfs"} {
+ template := "carlos-instance@.service"
+ if caller == "sidecar" {
+ template = "carlos-instance-sidecar@.service"
+ }
+ if caller == "rootfs" {
+ template = "carlos-instance-rootfs@.service"
+ }
+ name := fmt.Sprintf("carlos-hairpin-%s-%d.service", caller, cycle)
+ body := "[Service]\nType=oneshot\nDynamicUser=yes\nNoNewPrivileges=yes\nCapabilityBoundingSet=\nRestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX\nSlice=" + parent + "\nIPAddressDeny=" + egressUnitDeny(t, template) + "\nEnvironment=HAIRPIN_CALLER=" + caller + "\nEnvironment=HAIRPIN_PUBLIC=" + config.PublicIPv4 + "\nEnvironment=HAIRPIN_PRIMARY=" + config.PrimaryIPv4 + "\nEnvironment=HAIRPIN_PORTS=" + strings.Join(ports, ",") + "\nExecStart=" + payload + " -test.run=^TestHairpinCallerPayload$ -test.v -test.timeout=45s\n"
+ if caller == "rootfs" {
+ root := filepath.Join(scratch, fmt.Sprintf("rootfs-%d", cycle))
+ if err = os.Mkdir(root, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(root, "witness"), image, 0755); err != nil {
+ t.Fatal(err)
+ }
+ body = strings.Replace(body, "ExecStart="+payload, "RootDirectory="+root+"\nExecStart=/witness", 1)
+ }
+ hairpinRunnerUnit(t, name, body)
+ hairpinCmd(t, "systemctl", "start", name)
+ witnessed[caller] = true
+ if egressShow(t, name, "ExecMainStatus") != "0" {
+ t.Fatalf("%s failed\n%s", caller, egressJournal(name))
+ }
+ }
+ deniedUnit := fmt.Sprintf("carlos-hairpin-denied-%d.service", cycle)
+ deniedBody := "[Service]\nType=oneshot\nDynamicUser=yes\nCapabilityBoundingSet=\nSlice=" + parent + "\nIPAddressDeny=8.8.8.8/32 9.9.9.9/32\nEnvironment=HAIRPIN_DENIED=1\nExecStart=" + payload + " -test.run=^TestHairpinCallerPayload$ -test.v -test.timeout=10s\n"
+ hairpinRunnerUnit(t, deniedUnit, deniedBody)
+ hairpinCmd(t, "systemctl", "start", deniedUnit)
+ hairpinExternalAndARP(t, payload, *config)
+ // Neither the nft transaction nor closure may disturb metadata protection.
+ if got := hairpinCmd(t, "nft", "-s", "list", "table", "inet", "carlos_group_imds"); got != imdsBefore {
+ t.Fatal("IMDS table changed")
+ }
+ hairpinAgentCall(t, control, "/close")
+ hairpinAssertEmpty(t)
+ deny := egressShow(t, parent, "IPAddressDeny")
+ for _, ip := range config.PublicIPs {
+ if strings.Contains(deny, ip) {
+ t.Fatal("closed EIP incorrectly remains local in #367", deny)
+ }
+ }
+ hairpinAgentCall(t, control, "/admit-refused")
+ if cycle == 0 {
+ hairpinCmd(t, "systemctl", "stop", agentUnit)
+ if err := instancectl.ClearGroupHairpin(ctx); err != nil {
+ t.Fatal(err)
+ }
+ hairpinCmd(t, "systemctl", "start", agentUnit)
+ hairpinAgentWait(t, control)
+ }
+ }
+ for _, caller := range []string{"root", "agent", "tenant", "sidecar", "rootfs"} {
+ if !witnessed[caller] {
+ t.Fatal("missing caller witness", caller)
+ }
+ }
+ // Fail after the kernel has made both EIPs local. The production operation
+ // must remove them, restore plain #367 denial, and retain the IMDS table.
+ l, err := hairpin.Acquire(ctx)
+ if err != nil || l == nil {
+ t.Fatal("rollback lock", err)
+ }
+ plainDeny := func(ctx context.Context, on bool) error {
+ local, err := instancectl.LocalAddresses()
+ if err != nil {
+ return err
+ }
+ var values []string
+ for _, p := range local {
+ if on && p.IsSingleIP() && slices.Contains(config.PublicIPs, p.Addr().String()) {
+ continue
+ }
+ values = append(values, p.String())
+ }
+ slices.Sort(values)
+ _, err = exec.CommandContext(ctx, "systemctl", "set-property", "--runtime", parent, "IPAddressDeny=", "IPAddressDeny="+strings.Join(values, " ")).CombinedOutput()
+ return err
+ }
+ ops := hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, Exempt: plainDeny, Save: func(on bool) error {
+ if on {
+ return errors.New("injected post-assignment save failure")
+ }
+ return l.Save(hairpin.State{Process: l.State.Process, Closed: true})
+ }}
+ rollbackErr := ops.Enable(ctx)
+ l.Close()
+ if rollbackErr == nil {
+ t.Fatal("injected failure accepted")
+ }
+ hairpinAssertEmpty(t)
+ if got := hairpinCmd(t, "nft", "-s", "list", "table", "inet", "carlos_group_imds"); got != imdsBefore {
+ t.Fatal("rollback touched IMDS table")
+ }
+ // Reboot binding: stale snapshots refuse even when the signed identity and
+ // group marker still match this instance. No actual reboot is claimed here.
+ raw, err := os.ReadFile(hairpin.ConfigPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ changed := *config
+ changed.BootID = "00000000-0000-0000-0000-000000000000"
+ hairpinWriteJSON(t, hairpin.ConfigPath, changed)
+ if _, err := hairpin.Load(); err == nil {
+ t.Fatal("stale boot snapshot accepted")
+ }
+ if err = os.WriteFile(hairpin.ConfigPath, raw, 0644); err != nil {
+ t.Fatal(err)
+ }
+ t.Log("PASS: agent, root, tenant, sidecar and rootfs; both EIPs; HTTP/TLS/POST/upgrade; actual listeners fenced; metadata/private/UDP denied for sandbox callers; closure and replacement")
+}
+
+func hairpinCmd(t *testing.T, args ...string) string {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(t.Context(), 70*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v: %v\n%s", args, err, out)
+ }
+ return string(out)
+}
+func hairpinNFT(t *testing.T, body string) {
+ t.Helper()
+ cmd := exec.Command("nft", "-f", "-")
+ cmd.Stdin = strings.NewReader(body)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("nft: %v %s", err, out)
+ }
+}
+func hairpinWriteJSON(t *testing.T, path string, value any) {
+ t.Helper()
+ raw, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(path, raw, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Chmod(path, 0644); err != nil {
+ t.Fatal(err)
+ }
+}
+func hairpinAssertEmpty(t *testing.T) {
+ t.Helper()
+ out := hairpinCmd(t, "ip", "-j", "-4", "addr", "show", "dev", hairpin.Interface)
+ var rows []struct {
+ Addrs []any `json:"addr_info"`
+ }
+ if json.Unmarshal([]byte(out), &rows) != nil || len(rows) != 1 || len(rows[0].Addrs) != 0 {
+ t.Fatal("hairpin still assigned", out)
+ }
+ routes := hairpinCmd(t, "ip", "-j", "-4", "route", "show", "table", "local", "dev", hairpin.Interface)
+ var localRoutes []any
+ if json.Unmarshal([]byte(routes), &localRoutes) != nil || len(localRoutes) != 0 {
+ t.Fatal("local EIP route survived removal", routes)
+ }
+}
+func hairpinRunnerUnit(t *testing.T, name, body string) {
+ t.Helper()
+ path := filepath.Join("/run/systemd/system", name)
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = f.WriteString(body)
+ f.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ exec.Command("systemctl", "stop", name).Run()
+ os.Remove(path)
+ exec.Command("systemctl", "daemon-reload").Run()
+ exec.Command("systemctl", "reset-failed", name).Run()
+ })
+ hairpinCmd(t, "systemctl", "daemon-reload")
+}
+
+func hairpinRunnerSnapshot(t *testing.T) *hairpin.Config {
+ client := &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{Proxy: nil}}
+ record, err := readIdentityRecord(client, imdsBase, "fixture", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := base64.StdEncoding.DecodeString(record.IdentityDocument)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var doc struct {
+ Account string `json:"accountId"`
+ Region string `json:"region"`
+ IID string `json:"instanceId"`
+ Private string `json:"privateIp"`
+ }
+ if json.Unmarshal(raw, &doc) != nil {
+ t.Fatal("identity document")
+ }
+ record.Box = groupReferenceOf(doc.Account, doc.IID)
+ addresses, ok := (imdsAddresses{token: func() string { return imdsToken(client) }, leaf: func(token, path string) (string, int) { return imdsLeaf(client, token, path) }}).BoxAddresses()
+ if !ok || addresses.Private != doc.Private {
+ t.Fatal("metadata address fixture unavailable")
+ }
+ placement := "ie"
+ marker := hostenv.GroupConfig{V: 1, Account: doc.Account, AWSRegion: doc.Region, DeploymentAWSRegion: doc.Region, Region: "ie", Deployment: "dev", Bucket: "fixture-deploy", DataBucket: "fixture-data", Group: "fixture-group", Hook: "carlos-initial-launch", Placement: &placement, Pools: []string{"hapair"}, KnownReaders: []string{}, Release: "v1.2.3", InstanceID: doc.IID, BootID: readBootID(bootIDPath), Deadline: time.Now().Add(time.Hour).Unix(), QueueURL: "https://sqs." + doc.Region + ".amazonaws.com/" + doc.Account + "/fixture"}
+ marker.ConfigDigest = marker.Digest()
+ hairpinWriteJSON(t, hostenv.GroupConfigPath, marker)
+ hairpinWriteJSON(t, groupIdentityPath, record)
+ if err := hairpin.VerifyIdentity(); err != nil {
+ t.Fatal(err)
+ }
+ config := &hairpin.Config{V: 1, Region: "ie", PublicIPs: []string{"8.8.8.8", "9.9.9.9"}, PublicIPv4: addresses.Public, PrimaryIPv4: addresses.Private, PrivateCIDR: addresses.PrivateCIDR, BootID: marker.BootID, Account: doc.Account, InstanceID: doc.IID}
+ if err := config.Validate(); err != nil {
+ t.Fatal("runner requires a public IPv4 from protected IMDS", err)
+ }
+ hairpinWriteJSON(t, hairpin.ConfigPath, config)
+ if _, err := hairpin.Load(); err != nil {
+ t.Fatal(err)
+ }
+ return config
+}
+
+func hairpinRunnerCertificate(t *testing.T) ([]byte, []byte) {
+ t.Helper()
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cert := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "hairpin.test"}, DNSNames: []string{"hairpin.test"}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
+ der, err := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
+}
+
+func hairpinListenerPorts(t *testing.T) []string {
+ t.Helper()
+ seen := map[string]bool{"3333": true}
+ for _, mode := range []string{"-lnt", "-lnu"} {
+ for _, line := range strings.Split(hairpinCmd(t, "ss", "-H", mode), "\n") {
+ f := strings.Fields(line)
+ if len(f) < 4 {
+ continue
+ }
+ _, port, err := net.SplitHostPort(f[3])
+ if err != nil {
+ t.Fatal("listener parse", line)
+ }
+ if port != "80" && port != "443" && port != "*" {
+ seen[port] = true
+ }
+ }
+ }
+ ports := make([]string, 0, len(seen))
+ for port := range seen {
+ ports = append(ports, port)
+ }
+ slices.Sort(ports)
+ t.Logf("actual non-public listener ports: %v", ports)
+ return ports
+}
+
+func hairpinAgentClient() *http.Client {
+ return &http.Client{Timeout: 70 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", "/run/carlos/hairpin-agent.sock")
+ }}}
+}
+func hairpinAgentWait(t *testing.T, c *http.Client) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ resp, err := c.Get("http://fixture/ping")
+ if err == nil {
+ resp.Body.Close()
+ if resp.StatusCode == 200 {
+ return
+ }
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatal("agent not ready", egressJournal(agentUnit))
+}
+func hairpinAgentCall(t *testing.T, c *http.Client, path string) {
+ t.Helper()
+ resp, err := c.Get("http://fixture" + path)
+ if err != nil {
+ t.Fatal(err, egressJournal(agentUnit))
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 200 {
+ t.Fatalf("agent %s: %d %s\n%s", path, resp.StatusCode, body, egressJournal(agentUnit))
+ }
+}
+
+func TestHairpinAgentPayload(t *testing.T) {
+ scratch := os.Getenv("HAIRPIN_FIXTURE")
+ if scratch == "" {
+ t.Fatal("fixture-only payload")
+ }
+ config, err := hairpin.Load()
+ if err != nil || config == nil {
+ t.Fatal(err)
+ }
+ reg, err := registry.Open("/run/carlos/hairpin-registry.db")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err = reg.Upsert(registry.Route{Host: "hairpin.test", Kind: "service", Socket: "/run/carlos/hairpin-app.sock", Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := edge.New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ admission := readyGroupAdmission(t)
+ admission.observe(groupadmission.Facts{TerminationStarted: true})
+ if err = configureGroupHairpin(admission); err != nil {
+ t.Fatal(err)
+ }
+ wireAgentAdmission(admission, nil, nil, nil)(e)
+ for _, port := range []string{"80", "443"} {
+ ln, err := net.Listen("tcp", ":"+port)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: e, ReadHeaderTimeout: 3 * time.Second}
+ ln, err = edge.ConfigureGroupHairpin(srv, ln)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { srv.Close(); ln.Close() })
+ go func() {
+ if port == "443" {
+ srv.ServeTLS(ln, filepath.Join(scratch, "cert.pem"), filepath.Join(scratch, "key.pem"))
+ } else {
+ srv.Serve(ln)
+ }
+ }()
+ }
+ // A real agent-internal listener: the fence must hide it even from root and
+ // the agent when they address an ingress EIP.
+ internal, err := net.Listen("tcp", ":3333")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer internal.Close()
+ go func() {
+ for {
+ c, err := internal.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ os.Remove("/run/carlos/hairpin-agent.sock")
+ ln, err := net.Listen("unix", "/run/carlos/hairpin-agent.sock")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/ping":
+ case "/admit":
+ admission.tick(context.Background())
+ if !admission.startAllowed() {
+ http.Error(w, "not admitted", 503)
+ return
+ }
+ case "/close":
+ admission.Close()
+ case "/admit-refused":
+ admission.tick(context.Background())
+ if admission.startAllowed() {
+ http.Error(w, "reopened", 500)
+ return
+ }
+ case "/check":
+ hairpinCallerChecks(t, *config, strings.Split(r.URL.Query().Get("ports"), ","), false)
+ default:
+ http.NotFound(w, r)
+ return
+ }
+ w.WriteHeader(200)
+ })
+ if err = http.Serve(ln, h); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestHairpinCallerPayload(t *testing.T) {
+ if os.Getenv("HAIRPIN_DENIED") == "1" {
+ for _, ip := range []string{"8.8.8.8", "9.9.9.9"} {
+ for _, port := range []string{"80", "443"} {
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), time.Second)
+ if err == nil {
+ conn.Close()
+ t.Fatal("explicit EIP egress deny was bypassed", ip, port)
+ }
+ }
+ }
+ return
+ }
+
+ if os.Getenv("HAIRPIN_CALLER") == "" {
+ t.Fatal("fixture-only payload")
+ }
+ if os.Getenv("HAIRPIN_CALLER") == "rootfs" {
+ if _, err := os.Stat("/witness"); err != nil {
+ t.Fatal("rootfs namespace was omitted", err)
+ }
+ if _, err := os.Stat(hairpin.ConfigPath); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("rootfs can see the host snapshot", err)
+ }
+ }
+ c := hairpin.Config{PublicIPs: []string{"8.8.8.8", "9.9.9.9"}, PublicIPv4: os.Getenv("HAIRPIN_PUBLIC"), PrimaryIPv4: os.Getenv("HAIRPIN_PRIMARY")}
+ hairpinCallerChecks(t, c, strings.Split(os.Getenv("HAIRPIN_PORTS"), ","), true)
+}
+
+func hairpinCallerChecks(t *testing.T, c hairpin.Config, ports []string, sandbox bool) {
+ t.Helper()
+ for _, ip := range c.PublicIPs {
+ for _, port := range []string{"80", "443"} {
+ scheme := "http"
+ if port == "443" {
+ scheme = "https"
+ }
+ tr := &http.Transport{Proxy: nil, DisableKeepAlives: true, TLSClientConfig: &tls.Config{InsecureSkipVerify: true, ServerName: "hairpin.test"}} // fixture-only self-signed cert
+ client := &http.Client{Transport: tr, Timeout: 3 * time.Second}
+ for _, method := range []string{"GET", "POST"} {
+ req, _ := http.NewRequest(method, scheme+"://"+net.JoinHostPort(ip, port)+"/body", strings.NewReader("payload"))
+ req.Host = "hairpin.test"
+ req.Header.Set("X-Forwarded-For", "127.0.0.1")
+ req.Header.Set("Forwarded", "for=127.0.0.1")
+ req.Header.Set("X-Real-IP", "127.0.0.1")
+ req.Header.Set("X-Carlos-Hairpin", "1")
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s: %v", method, req.URL, err)
+ }
+ var got map[string]string
+ err = json.NewDecoder(resp.Body).Decode(&got)
+ resp.Body.Close()
+ if err != nil || resp.StatusCode != 200 || got["client"] != c.PublicIPv4 || got["method"] != method || got["body"] != "payload" || got["host"] != "hairpin.test" {
+ t.Fatalf("derived identity/body: %d %#v %v", resp.StatusCode, got, err)
+ }
+ }
+ tr.CloseIdleConnections()
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if port == "443" {
+ conn = tls.Client(conn, &tls.Config{InsecureSkipVerify: true, ServerName: "hairpin.test"})
+ }
+ conn.SetDeadline(time.Now().Add(3 * time.Second))
+ fmt.Fprint(conn, "GET /ws HTTP/1.1\r\nHost: hairpin.test\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nX-Forwarded-For: 127.0.0.1\r\n\r\n")
+ reader := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(reader, &http.Request{Method: "GET"})
+ if err != nil || resp.StatusCode != 101 || resp.Header.Get("X-Observed-Client") != c.PublicIPv4 {
+ conn.Close()
+ t.Fatalf("upgrade: %v %#v", err, resp)
+ }
+ // An opaque frame must cross the upgraded stream unchanged.
+ frame := []byte{0x81, 0x82, 1, 2, 3, 4, 'o' ^ 1, 'k' ^ 2}
+ if _, err = conn.Write(frame); err != nil {
+ t.Fatal(err)
+ }
+ got := make([]byte, len(frame))
+ if _, err = io.ReadFull(reader, got); err != nil || !bytes.Equal(got, frame) {
+ t.Fatal("upgrade payload", got, err)
+ }
+ conn.Close()
+ }
+ for _, port := range ports {
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), 200*time.Millisecond)
+ if err == nil {
+ conn.Close()
+ t.Fatalf("local listener exposed at %s:%s", ip, port)
+ }
+ }
+ for _, port := range append(append([]string{}, ports...), "80", "443") {
+ udp, err := net.Dial("udp4", net.JoinHostPort(ip, port))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = udp.Write([]byte("probe"))
+ udp.Close()
+ if !errors.Is(err, unix.EPERM) {
+ t.Fatalf("UDP probe at %s:%s: %v, want EPERM", ip, port, err)
+ }
+ }
+ udp, err := net.Dial("udp4", net.JoinHostPort(ip, "9"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = udp.Write([]byte("probe"))
+ udp.Close()
+ if !errors.Is(err, unix.EPERM) {
+ t.Fatalf("existing UDP denial probe: %v", err)
+ }
+ }
+ if sandbox {
+ // Root and the agent retain their existing metadata authority. The nested
+ // units must still be denied private and both IMDS addresses.
+ for _, addr := range []string{c.PrimaryIPv4, "10.0.0.1", "169.254.169.254", "fd00:ec2::254"} {
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(addr, "80"), 300*time.Millisecond)
+ if err == nil {
+ conn.Close()
+ t.Fatal("private/metadata reachable", addr)
+ }
+ }
+ for _, addr := range []string{"169.254.169.254", "fd00:ec2::254"} {
+ udp, err := net.Dial("udp", net.JoinHostPort(addr, "9"))
+ if err != nil {
+ t.Fatal("metadata route/source unavailable", addr, err)
+ }
+ _, err = udp.Write([]byte("probe"))
+ udp.Close()
+ if !errors.Is(err, unix.EPERM) {
+ t.Fatalf("metadata policy %s: %v, want EPERM", addr, err)
+ }
+ }
+ }
+}
+
+func hairpinExternalAndARP(t *testing.T, payload string, c hairpin.Config) {
+ t.Helper()
+ const ns = "carlos-hairpin-peer"
+ const host = "chp-host"
+ const peer = "chp-peer"
+ if out := hairpinCmd(t, "ip", "netns", "list"); strings.Contains(out, ns) {
+ t.Fatal("peer namespace exists")
+ }
+ hairpinCmd(t, "ip", "netns", "add", ns)
+ defer exec.Command("ip", "netns", "del", ns).Run()
+ hairpinCmd(t, "ip", "link", "add", host, "type", "veth", "peer", "name", peer)
+ defer exec.Command("ip", "link", "del", host).Run()
+ hairpinCmd(t, "ip", "link", "set", peer, "netns", ns)
+ hairpinCmd(t, "ip", "addr", "add", "172.30.0.1/30", "dev", host)
+ hairpinCmd(t, "ip", "link", "set", host, "up")
+ hairpinCmd(t, "ip", "-n", ns, "addr", "add", "172.30.0.2/30", "dev", peer)
+ hairpinCmd(t, "ip", "-n", ns, "link", "set", peer, "up")
+ hairpinCmd(t, "ip", "-n", ns, "link", "set", "lo", "up")
+ hairpinCmd(t, "ip", "-n", ns, "route", "add", "default", "via", "172.30.0.1")
+ cmd := exec.Command("ip", "netns", "exec", ns, payload, "-test.run=^TestHairpinExternalPayload$", "-test.v", "-test.timeout=15s")
+ cmd.Env = append(os.Environ(), "HAIRPIN_EXTERNAL=1", "HAIRPIN_PRIMARY="+c.PrimaryIPv4)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("external/ARP: %v\n%s", err, out)
+ } else {
+ t.Log(string(out))
+ }
+}
+
+func TestHairpinExternalPayload(t *testing.T) {
+ if os.Getenv("HAIRPIN_EXTERNAL") != "1" {
+ t.Fatal("fixture-only payload")
+ }
+ for _, ip := range []string{"8.8.8.8", "9.9.9.9"} {
+ for _, port := range []string{"80", "443"} {
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), time.Second)
+ if err != nil {
+ continue
+ }
+ conn.SetDeadline(time.Now().Add(time.Second))
+ fmt.Fprint(conn, "GET / HTTP/1.1\r\nHost: hairpin.test\r\nX-Carlos-Hairpin: 1\r\n\r\n")
+ _, err = http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "GET"})
+ conn.Close()
+ if err == nil {
+ t.Fatal("EIP-local connection accepted from a non-local peer", ip, port)
+ }
+ }
+ hairpinARPRefused(t, ip)
+ }
+ req, _ := http.NewRequest("GET", "http://"+net.JoinHostPort(os.Getenv("HAIRPIN_PRIMARY"), "80")+"/", nil)
+ req.Host = "hairpin.test"
+ req.Header.Set("X-Carlos-Hairpin", "1")
+ req.Header.Set("X-Forwarded-For", "127.0.0.1")
+ client := &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{Proxy: nil}}
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ var got map[string]string
+ if json.NewDecoder(resp.Body).Decode(&got) != nil || got["client"] != "172.30.0.2" {
+ t.Fatal("ordinary ingress identity changed", got)
+ }
+}
+func hairpinARPRefused(t *testing.T, target string) {
+ t.Helper()
+ iface, err := net.InterfaceByName("chp-peer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW|unix.SOCK_CLOEXEC, int((unix.ETH_P_ARP>>8)|((unix.ETH_P_ARP&0xff)<<8)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer unix.Close(fd)
+ if err = unix.Bind(fd, &unix.SockaddrLinklayer{Ifindex: iface.Index, Protocol: uint16((unix.ETH_P_ARP >> 8) | ((unix.ETH_P_ARP & 0xff) << 8))}); err != nil {
+ t.Fatal(err)
+ }
+ packet := make([]byte, 42)
+ for i := 0; i < 6; i++ {
+ packet[i] = 255
+ }
+ copy(packet[6:12], iface.HardwareAddr)
+ packet[12] = 8
+ packet[13] = 6
+ packet[15] = 1
+ packet[16] = 8
+ packet[18] = 6
+ packet[19] = 4
+ packet[21] = 1
+ copy(packet[22:28], iface.HardwareAddr)
+ copy(packet[28:32], net.ParseIP("172.30.0.2").To4())
+ copy(packet[38:42], net.ParseIP(target).To4())
+ dest := &unix.SockaddrLinklayer{Ifindex: iface.Index, Halen: 6}
+ for i := 0; i < 6; i++ {
+ dest.Addr[i] = 255
+ }
+ if err = unix.Sendto(fd, packet, 0, dest); err != nil {
+ t.Fatal(err)
+ }
+ until := time.Now().Add(350 * time.Millisecond)
+ for time.Now().Before(until) {
+ fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ if _, err = unix.Poll(fds, 50); err != nil {
+ t.Fatal(err)
+ }
+ if fds[0].Revents == 0 {
+ continue
+ }
+ b := make([]byte, 1500)
+ n, _, err := unix.Recvfrom(fd, b, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n >= 42 && b[20] == 0 && b[21] == 2 && net.IP(b[28:32]).String() == target {
+ t.Fatal("EIP announced by ARP", target)
+ }
+ }
+}
+
+// The installed reset unit executes this binary through the same bounded root
+// entry point as production, independently of the test's in-process server.
+func init() {
+ if len(os.Args) == 3 && os.Args[1] == "instance-control" && os.Args[2] == "--group-hairpin-reset" {
+ RunInstanceControl(os.Args[2:])
+ os.Exit(0)
+ }
+}
diff --git a/internal/host/group_hairpin_test.go b/internal/host/group_hairpin_test.go
new file mode 100644
index 000000000..c52c088f1
--- /dev/null
+++ b/internal/host/group_hairpin_test.go
@@ -0,0 +1,92 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestHairpinAdmissionSynchronization(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ entered, release := make(chan struct{}), make(chan struct{})
+ var disables atomic.Int32
+ a.hairpin = func(on bool) error {
+ if on {
+ close(entered)
+ <-release
+ } else {
+ disables.Add(1)
+ }
+ return nil
+ }
+ done := make(chan struct{})
+ go func() { defer close(done); a.tick(context.Background()) }()
+ select {
+ case <-entered:
+ case <-time.After(time.Second):
+ t.Fatal("no activation")
+ }
+ if a.startAllowed() || a.TenantAdmitted() {
+ close(release)
+ <-done
+ a.Close()
+ t.Fatal("tenant gate opened before root enabled hairpin")
+ }
+ closed := make(chan struct{})
+ go func() { a.Close(); close(closed) }()
+ // Closure must publish its gate before it waits for an in-flight root call.
+ deadline := time.After(time.Second)
+ for a.state.Admitted() {
+ select {
+ case <-deadline:
+ close(release)
+ <-done
+ <-closed
+ t.Fatal("closure waits behind root enable before closing the gate")
+ default:
+ time.Sleep(time.Millisecond)
+ }
+ }
+ close(release)
+ <-done
+ <-closed
+ if a.startAllowed() || disables.Load() != 1 {
+ t.Fatalf("reopened: disables=%d", disables.Load())
+ }
+}
+
+func TestHairpinCloseCancelsWorkBeforeRoot(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ entered, release := make(chan struct{}), make(chan struct{})
+ a.hairpin = func(on bool) error {
+ if !on {
+ close(entered)
+ <-release
+ }
+ return nil
+ }
+ a.tick(context.Background())
+ work, finish, ok := a.beginDepartureWork(context.Background())
+ if !ok {
+ t.Fatal("not admitted")
+ }
+ closed := make(chan struct{})
+ go func() { a.Close(); close(closed) }()
+ <-entered
+ cancelled := false
+ select {
+ case <-work.Done():
+ cancelled = true
+ case <-time.After(time.Second):
+ }
+ close(release)
+ finish()
+ <-closed
+ if !cancelled {
+ t.Fatal("departure work remained live while root removal blocked")
+ }
+}
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go
index 21079bfbb..51fb2bda8 100644
--- a/internal/host/group_maintenance.go
+++ b/internal/host/group_maintenance.go
@@ -131,7 +131,7 @@ func (a *systemApplier) requireGroupMaintenance(action string) error {
return nil
}
if g.used[action] {
- return nil
+ return a.clearGroupHairpin()
}
if err := consumeGroupAction(g.dir, "used-"+p.Transaction+"-"+action, g.owner); err != nil {
return errors.Join(errGroupMaintenance, err)
@@ -141,7 +141,7 @@ func (a *systemApplier) requireGroupMaintenance(action string) error {
}
g.used[action] = true
g.permit = &p
- return nil
+ return a.clearGroupHairpin()
}
func (a *systemApplier) groupTarget(path string, rollback bool) error {
if !groupMarkerPresent(a.etcDir) {
diff --git a/internal/host/group_metrics.go b/internal/host/group_metrics.go
index fbc3f2e26..ff5ce9e30 100644
--- a/internal/host/group_metrics.go
+++ b/internal/host/group_metrics.go
@@ -16,6 +16,7 @@ import (
)
type admissionMetrics struct {
+ admitted func() bool
deployment, region string
group string
state *groupadmission.State
@@ -31,7 +32,7 @@ func admissionMetricsFromEnv(getenv func(string) string, a *fixedAdmission, read
if deployment == "" || err != nil {
return nil
}
- m := &admissionMetrics{deployment: deployment, region: region.RegionCode, state: &a.state, clock: clock}
+ m := &admissionMetrics{deployment: deployment, region: region.RegionCode, state: &a.state, admitted: a.TenantAdmitted, clock: clock}
if a.group {
// The launch binding was verified against the root marker. The boot
// shell's CARLOS_GROUP_NAME is not part of the service environment.
@@ -49,6 +50,9 @@ func admissionMetricsFromEnv(getenv func(string) string, a *fixedAdmission, read
func (m *admissionMetrics) observe(ctx context.Context, now time.Time) (groupadmission.Observation, error) {
o := groupadmission.Observation{At: now, Deployment: m.deployment, Region: m.region, Admitted: m.state.Admitted()}
+ if m.admitted != nil {
+ o.Admitted = m.admitted()
+ }
offset, err := m.clock(ctx)
if err == nil {
o.ClockOffset = &offset
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go
new file mode 100644
index 000000000..f6c75b425
--- /dev/null
+++ b/internal/instancectl/hairpin.go
@@ -0,0 +1,266 @@
+package instancectl
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/netip"
+ "os"
+ "os/exec"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hairpin"
+)
+
+type hairpinLeaseKey struct{}
+type hairpinRequest struct {
+ Enable *bool `json:"enable"`
+ Process hairpin.Process `json:"process"`
+}
+
+// All group operations, the ordinary deny refresh and the entire binary/rootfs
+// probe share this root lock. No second per-box polling loop is introduced.
+func hairpinLocked(ctx context.Context) (context.Context, func(), error) {
+ if _, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease); ok {
+ return ctx, func() {}, nil
+ }
+ bounded, cancel := context.WithTimeout(ctx, 60*time.Second)
+ l, err := hairpin.Acquire(bounded)
+ if err != nil {
+ cancel()
+ return ctx, func() {}, err
+ }
+ if l == nil {
+ cancel()
+ return ctx, func() {}, nil
+ }
+ return context.WithValue(bounded, hairpinLeaseKey{}, l), func() { l.Close(); cancel() }, nil
+}
+func (s *Server) hairpinDeny(ctx context.Context, local []netip.Prefix) ([]netip.Prefix, error) {
+ l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
+ if !ok || !l.State.Active {
+ return local, nil
+ }
+ if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil {
+ // A failed readback revokes both pieces of authority immediately. Even if
+ // address removal fails, the caller still applies the complete local deny.
+ l.State.Active = false
+ l.State.Closed = true
+ saved := l.Save(l.State)
+ removed := l.Addresses(ctx, false)
+ current, readErr := s.localPrefixes()
+ if readErr == nil && len(current) > 0 {
+ local = current
+ }
+ return local, errors.Join(err, saved, removed, readErr)
+ }
+ out := make([]netip.Prefix, 0, len(local))
+ for _, p := range local {
+ if p.IsSingleIP() && slices.Contains(l.Config.PublicIPs, p.Addr().String()) {
+ continue
+ }
+ out = append(out, p)
+ }
+ return out, nil
+}
+func (s *Server) hairpinOperations(ctx context.Context, l *hairpin.Lease, p hairpin.Process) hairpin.Operations {
+ return hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses,
+ Exempt: func(ctx context.Context, on bool) error { l.State.Active = on; return s.denyLocalAddrs(ctx) },
+ Save: func(on bool) error { return l.Save(hairpin.State{Process: p, Active: on, Closed: !on}) },
+ }
+}
+func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
+ defer cancel()
+ conn := RequestConn(r.Context())
+ if conn == nil || conn.SetReadDeadline(time.Now().Add(5*time.Second)) != nil || conn.SetWriteDeadline(time.Now().Add(75*time.Second)) != nil {
+ http.Error(w, "group_hairpin_peer", 403)
+ return
+ }
+ var req hairpinRequest
+ d := json.NewDecoder(io.LimitReader(r.Body, 1025))
+ d.DisallowUnknownFields()
+ if d.Decode(&req) != nil || d.Decode(new(any)) != io.EOF || req.Enable == nil {
+ http.Error(w, "group_hairpin_request", 400)
+ return
+ }
+ // Revalidate the exact kernel peer and live MainPID after taking the lock;
+ // a delayed connection from an earlier process cannot alter its successor.
+ ctx, unlock, err := hairpinLocked(ctx)
+ if err != nil {
+ http.Error(w, "group_hairpin_unavailable", 503)
+ return
+ }
+ defer unlock()
+ l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
+ if !ok || hairpin.Authenticate(ctx, conn, req.Process) != nil {
+ http.Error(w, "group_hairpin_peer", 403)
+ return
+ }
+ op := s.hairpinOperations(ctx, l, req.Process)
+ if *req.Enable {
+ if l.State.Process == req.Process && l.State.Closed {
+ http.Error(w, "group_hairpin_closed", 409)
+ return
+ }
+ if l.State.Active && l.State.Process == req.Process {
+ if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil {
+ _ = op.Disable(ctx)
+ http.Error(w, "group_hairpin_unavailable", 503)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ if l.State.Active {
+ if err := op.Disable(ctx); err != nil {
+ http.Error(w, "group_hairpin_unavailable", 503)
+ return
+ }
+ }
+ // Open the descriptor before making the first EIP local. The callback also
+ // checks the saved identity, so an old exit cannot close a new process.
+ stop, watchErr := hairpin.WatchExit(req.Process, func() { s.hairpinExited(req.Process) })
+ if watchErr != nil {
+ http.Error(w, "group_hairpin_peer", 403)
+ return
+ }
+ err = op.Enable(ctx)
+ if err != nil {
+ stop()
+ }
+ } else {
+ err = op.Disable(ctx)
+ }
+ if err != nil {
+ http.Error(w, "group_hairpin_unavailable", 503)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+func (s *Server) hairpinExited(p hairpin.Process) {
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ ctx, unlock, err := hairpinLocked(ctx)
+ if err != nil {
+ s.logf("group hairpin exit cleanup failed: %v", err)
+ return
+ }
+ defer unlock()
+ l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
+ if !ok || l.State.Process != p {
+ return
+ }
+ if err = s.hairpinOperations(ctx, l, p).Disable(ctx); err != nil {
+ s.logf("group hairpin exit cleanup failed: %v", err)
+ }
+}
+
+// ClearGroupHairpin is a root-only pre-start/pre-maintenance operation. The
+// state remains closed for the old process. Only a different current MainPID
+// may subsequently enable. The group-only reset unit also runs after a crash.
+func ClearGroupHairpin(ctx context.Context) error {
+ if os.Geteuid() != 0 {
+ return hairpin.ErrConfig
+ }
+ s := &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ }}
+ ctx, unlock, err := hairpinLocked(ctx)
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
+ if !ok {
+ return nil
+ }
+ // Tombstone the current process even if it has never enabled hairpin.
+ // A booting agent must not race a maintenance stop by enabling afterward.
+ process, lookupErr := hairpin.MainProcess(ctx)
+ if process.PID == 0 {
+ process = l.State.Process
+ }
+ if err := errors.Join(s.hairpinOperations(ctx, l, process).Disable(ctx), lookupErr); err != nil {
+ return err
+ }
+ return l.Prepare(ctx)
+}
+func groupHairpinMarker() bool { return hairpin.GroupPresent() }
+
+func (c *Client) GroupHairpin(ctx context.Context, enable bool, p hairpin.Process) error {
+ body, err := json.Marshal(hairpinRequest{Enable: &enable, Process: p})
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", "http://control/group-hairpin", bytes.NewReader(body))
+ if err != nil {
+ return err
+ }
+ resp, err := c.httpClient().Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusNoContent {
+ return errors.New("group_hairpin_unavailable")
+ }
+ return nil
+}
+
+// The control service may restart while the agent remains admitted. Reattach
+// the kernel exit watch from root's state; interrupted inactive operations are
+// rolled back before this service answers requests or refreshes an exemption.
+func (s *Server) resumeGroupHairpin(ctx context.Context) error {
+ ctx, unlock, err := hairpinLocked(ctx)
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
+ if !ok {
+ return nil
+ }
+ p := l.State.Process
+ if !l.State.Active || hairpin.Current(ctx, p) != nil || l.Verify(ctx) != nil || l.CheckAddresses(ctx, true) != nil {
+ return s.hairpinOperations(ctx, l, p).Disable(ctx)
+ }
+ _, err = hairpin.WatchExit(p, func() { s.hairpinExited(p) })
+ return err
+}
+
+// InstallDormantGroupHairpin is the initial root boot stage, before bootstrap
+// has installed instance units. It cannot grant an exemption or assign an EIP.
+// A saved state requires reset/maintenance, never another initial install.
+func InstallDormantGroupHairpin(ctx context.Context) error {
+ if os.Geteuid() != 0 {
+ return hairpin.ErrConfig
+ }
+ ctx, unlock, err := hairpinLocked(ctx)
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
+ if !ok {
+ return hairpin.ErrConfig
+ }
+ if l.State != (hairpin.State{}) {
+ return hairpin.ErrConfig
+ }
+ if current, err := hairpin.MainProcess(ctx); err != nil || current.PID != 0 {
+ return hairpin.ErrConfig
+ }
+ if err := l.Prepare(ctx); err != nil {
+ return err
+ }
+ if err := l.CheckAddresses(ctx, false); err != nil {
+ return err
+ }
+ return l.Save(hairpin.State{Closed: true})
+}
diff --git a/internal/instancectl/hardening.go b/internal/instancectl/hardening.go
index 17b18668d..95498102a 100644
--- a/internal/instancectl/hardening.go
+++ b/internal/instancectl/hardening.go
@@ -290,12 +290,18 @@ func (s *Server) allowResolvers(ctx context.Context) (refused []string, err erro
// remembered in lastDeny, for denyLoop. denyMu runs one call at a time, so
// an older read can never be applied over a newer one.
func (s *Server) denyLocalAddrs(ctx context.Context) error {
+ ctx, unlock, lockErr := hairpinLocked(ctx)
+ if lockErr != nil {
+ return lockErr
+ }
+ defer unlock()
s.denyMu.Lock()
defer s.denyMu.Unlock()
local, err := s.localPrefixes()
if err != nil {
return fmt.Errorf("this box's addresses: %v; the last deny stands", err)
}
+ local, hairpinErr := s.hairpinDeny(ctx, local)
deny := denySet(local)
if len(deny) == 0 {
return errors.New("this box's addresses: none read; the last deny stands")
@@ -311,7 +317,7 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error {
s.mu.Lock()
s.lastDeny = deny
s.mu.Unlock()
- return nil
+ return hairpinErr
}
// denySet is local sorted by its string form, each prefix once: the deny
@@ -371,16 +377,20 @@ func (s *Server) denyLoopWith(ctx context.Context, ticks <-chan time.Time, done
logErr(err)
if err == nil {
s.mu.Lock()
- unchanged := slices.Equal(denySet(local), s.lastDeny)
+ previous := slices.Clone(s.lastDeny)
+ unchanged := slices.Equal(denySet(local), previous)
s.mu.Unlock()
- if !unchanged {
+ if !unchanged || groupHairpinMarker() {
err := s.denyLocalAddrs(ctx)
logErr(err)
if err == nil {
s.mu.Lock()
n := len(s.lastDeny)
+ changed := !slices.Equal(previous, s.lastDeny)
s.mu.Unlock()
- s.logf("instance-control: box addresses changed: %d prefixes", n)
+ if changed {
+ s.logf("instance-control: box addresses changed: %d prefixes", n)
+ }
}
// #328: s.Egress.Sweep(ctx) here (nil-safe)
}
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index f454d0237..3e8592848 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -332,6 +332,9 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
+ if err := s.resumeGroupHairpin(ctx); err != nil {
+ log.Fatal(err)
+ }
s.InspectMountpoints(ctx)
firstProbe := make(chan struct{})
builder, err := demobuild.NewWorker(os.Getenv, func(ctx context.Context) error {
@@ -486,6 +489,9 @@ func (s *Server) Handler() http.Handler {
// flags on (item 6); off, the route is absent as on main.
mux.Handle("POST /claim/held-release", s.ClaimHeldRelease)
}
+ if groupHairpinMarker() {
+ mux.HandleFunc("POST /group-hairpin", s.handleHairpin)
+ }
mux.HandleFunc("POST /start", s.claimAwareLegacy(s.handleStart))
mux.HandleFunc("POST /seed", s.claimAwareLegacy(s.handleSeed))
mux.HandleFunc("POST /stop", s.claimAwareLegacy(s.handleStop))
@@ -1345,11 +1351,17 @@ func (s *Server) probeLoop(ctx context.Context, firstProbe chan<- struct{}) {
// could not be read all leave the box not ready, with the reason on a
// verdict line; readiness is never the default.
func (s *Server) RunProbe(ctx context.Context) {
+ ctx, unlock, lockErr := hairpinLocked(ctx)
+ defer unlock()
set := func(r ProbeReport) {
s.mu.Lock()
s.report, s.probed = r, true
s.mu.Unlock()
}
+ if lockErr != nil {
+ set(ProbeReport{Lines: []VerdictLine{{Check: "group-hairpin", Verdict: "fail", Detail: lockErr.Error()}}})
+ return
+ }
if err := s.FixtureOK(); err != nil {
set(ProbeReport{Lines: []VerdictLine{{Check: "fixture", Verdict: "fail", Detail: err.Error()}}})
return