|
| 1 | +//go:build linux |
| 2 | + |
| 3 | +package host |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "os/exec" |
| 9 | + |
| 10 | + "golang.org/x/sync/semaphore" |
| 11 | +) |
| 12 | + |
| 13 | +// pinMMDSSem serializes self-heal calls so concurrent /init retries don't |
| 14 | +// run iptables in parallel against the same nat table. |
| 15 | +var pinMMDSSem = semaphore.NewWeighted(1) |
| 16 | + |
| 17 | +// PinMMDSRoute pins a RETURN rule for MMDS traffic (169.254.169.254:80) at |
| 18 | +// position 1 of nat PREROUTING and OUTPUT. Idempotent: each run deletes any |
| 19 | +// existing copy of the rule first, then re-inserts at position 1, so user |
| 20 | +// rules added above ours get pushed down. |
| 21 | +// |
| 22 | +// Intended for the self-heal path: only called when a real MMDS lookup |
| 23 | +// fails. Concurrent callers are coalesced via a semaphore — only one runs |
| 24 | +// at a time, the rest return nil immediately. Returns the first -I failure |
| 25 | +// (if any); -D failures are expected (rule absent on first run) and |
| 26 | +// silently swallowed. |
| 27 | +func PinMMDSRoute(ctx context.Context) error { |
| 28 | + if !pinMMDSSem.TryAcquire(1) { |
| 29 | + return nil |
| 30 | + } |
| 31 | + defer pinMMDSSem.Release(1) |
| 32 | + |
| 33 | + rule := []string{"-d", "169.254.169.254", "-p", "tcp", "--dport", "80", "-j", "RETURN"} |
| 34 | + for _, chain := range []string{"PREROUTING", "OUTPUT"} { |
| 35 | + // -D fails when the rule is absent (exit 1, expected on first run); |
| 36 | + // nothing actionable to log. |
| 37 | + _ = iptables(ctx, append([]string{"-D", chain}, rule...)...) |
| 38 | + if err := iptables(ctx, append([]string{"-I", chain, "1"}, rule...)...); err != nil { |
| 39 | + return fmt.Errorf("iptables -I nat %s: %w", chain, err) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +// iptables runs `iptables -w 5 -t nat ...`. -w waits up to 5s for the |
| 47 | +// xtables lock (a user iptables process may race us). |
| 48 | +func iptables(ctx context.Context, args ...string) error { |
| 49 | + full := append([]string{"-w", "5", "-t", "nat"}, args...) |
| 50 | + out, err := exec.CommandContext(ctx, "iptables", full...).CombinedOutput() |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("%w: %s", err, out) |
| 53 | + } |
| 54 | + |
| 55 | + return nil |
| 56 | +} |
0 commit comments