From d2ff069e6463a68a50408b0e9910f8796ea609fa Mon Sep 17 00:00:00 2001 From: MengMengCode <227010654+MengMengCode@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:02:32 +0800 Subject: [PATCH] FIX #70 --- backend/internal/kvm/kvm.go | 5 +- backend/internal/lxc/lxc_test.go | 16 +- backend/internal/lxc/portmap.go | 387 +++++------------- backend/internal/lxc/portmap_ipv6.go | 103 ++--- backend/internal/lxc/portmap_ipv6_test.go | 6 +- backend/internal/lxc/portmap_reconcile.go | 330 +++++++++++++++ .../internal/lxc/portmap_reconcile_test.go | 313 ++++++++++++++ 7 files changed, 808 insertions(+), 352 deletions(-) create mode 100644 backend/internal/lxc/portmap_reconcile.go create mode 100644 backend/internal/lxc/portmap_reconcile_test.go diff --git a/backend/internal/kvm/kvm.go b/backend/internal/kvm/kvm.go index 2d365be..edede0c 100644 --- a/backend/internal/kvm/kvm.go +++ b/backend/internal/kvm/kvm.go @@ -1837,7 +1837,10 @@ func (m *Manager) RefreshNetwork(id int) (string, error) { config.SaveConfig() } if c.Status == "running" && shouldApplyPortMappings(id, changed) { - if err := lxc.NewManager().ApplyPortMappings(id); err != nil { + if err := lxc.NewManager().EnsurePortMappings(id); err != nil { + portMapApplyMu.Lock() + delete(lastPortMapApply, id) + portMapApplyMu.Unlock() return ip, err } } diff --git a/backend/internal/lxc/lxc_test.go b/backend/internal/lxc/lxc_test.go index f1eb900..b2e2e72 100644 --- a/backend/internal/lxc/lxc_test.go +++ b/backend/internal/lxc/lxc_test.go @@ -186,18 +186,14 @@ func TestIsIPTablesRuleNotFoundError(t *testing.T) { } func TestPortMappingConntrackDeleteArgs(t *testing.T) { - got := portMappingConntrackDeleteArgs(config.PortMapping{ - HostIP: "203.0.113.10", - HostPort: 32022, - Protocol: "TCP", - }) - want := []string{"-D", "-p", "tcp", "--dport", "32022", "--dst", "203.0.113.10"} + c := &config.Container{ID: 12, IP: "10.0.3.5", PortMappings: []config.PortMapping{{HostIP: "203.0.113.10", HostPort: 32022, ContainerPort: 22, Protocol: "tcp"}}} + got := mappingRuleConntrackArgs("iptables", ipv4MappingRules(c, "lxcbr0", "10.0.3.0/24", "eth0")[0]) + want := []string{"-D", "-f", "ipv4", "--dst-nat", "--reply-src", "10.0.3.5", "-p", "tcp", "--dport", "32022", "--dst", "203.0.113.10", "--reply-port-src", "22"} if !reflect.DeepEqual(got, want) { - t.Fatalf("portMappingConntrackDeleteArgs() = %v, want %v", got, want) + t.Fatalf("cleanup = %v, want %v", got, want) } - - if got := portMappingConntrackDeleteArgs(config.PortMapping{HostPort: 32022, Protocol: "icmp"}); got != nil { - t.Fatalf("unsupported protocol returned args: %v", got) + if got := mappingRuleConntrackArgs("iptables", mappingRule{table: "filter", args: []string{"-j", "ACCEPT"}}); got != nil { + t.Fatalf("non-NAT rule caused invalidation: %v", got) } } diff --git a/backend/internal/lxc/portmap.go b/backend/internal/lxc/portmap.go index a297b72..7d4ae83 100644 --- a/backend/internal/lxc/portmap.go +++ b/backend/internal/lxc/portmap.go @@ -25,11 +25,20 @@ var ( queuedCreateNATMirrorsIPv6 = map[string]bool{} ) -// ApplyPortMappings applies iptables DNAT rules for a container's port mappings +// ApplyPortMappings reconciles network rules and reapplies the configured firewall. func (m *Manager) ApplyPortMappings(id int) error { + return m.reconcilePortMappings(id) +} + +// EnsurePortMappings repairs missing/stale network rules without disturbing +// healthy connections or replaying the firewall on every background poll. +func (m *Manager) EnsurePortMappings(id int) error { + return m.reconcilePortMappings(id) +} + +func (m *Manager) reconcilePortMappings(id int) error { iptablesMu.Lock() defer iptablesMu.Unlock() - c := config.FindContainer(id) if c == nil { return fmt.Errorf("container not found: %d", id) @@ -39,124 +48,31 @@ func (m *Manager) ApplyPortMappings(id int) error { if err := validateIPv6MappingInventory(c); err != nil { return err } - if c.IP == "" { - if _, _, _, enabled := nat6PortEndpoint(c); enabled { - if err := cleanIPv6PortMappingsLocked(id); err != nil { - return err - } - if err := applyIPv6PortMappingsLocked(c); err != nil { - return err - } - return applyFirewallRulesLocked(id) + if c.IP != "" { + EnsureAssignedPublicIPv4s(c.PublicIPv4s) + bridge, subnet := "lxcbr0", config.LXCNATNetwork().Subnet + if c.IsKVM() { + bridge, subnet = "virbr0", config.KVMNATNetwork().Subnet } + EnsureForwardRules(bridge) + var err error + _, err = reconcileMappingRules("iptables", "clicd-"+clicdTag(id)+"-", + []mappingRule{{table: "nat", chain: "PREROUTING"}, {table: "nat", chain: "POSTROUTING"}, {table: "filter", chain: "FORWARD"}}, + ipv4MappingRules(c, bridge, subnet, DetectPublicIPv4().Interface), runPortMappingCommand) + if err != nil { + return err + } + deleteBridgeMasquerade(subnet) + } else if _, _, _, enabled := nat6PortEndpoint(c); !enabled { return fmt.Errorf("container has no IP") } - EnsureAssignedPublicIPv4s(c.PublicIPv4s) - tag := clicdTag(id) - bridge := "lxcbr0" - subnet := config.LXCNATNetwork().Subnet - if c.IsKVM() { - bridge = "virbr0" - subnet = config.KVMNATNetwork().Subnet - } - - EnsureForwardRules(bridge) - if err := m.cleanPortMappingsLocked(id); err != nil { - return fmt.Errorf("clean existing port mappings for container %d: %w", id, err) - } - deleteBridgeMasquerade(subnet) - - for _, pm := range c.PortMappings { - for _, hostIP := range expandPortMappingHostIPs(c, pm) { - args := []string{ - "-t", "nat", - "-I", "PREROUTING", "1", - "-p", pm.Protocol, - } - if hostIP != "" { - args = append(args, "-d", hostIP) - } - args = append(args, - "--dport", fmt.Sprintf("%d", pm.HostPort), - "-j", "DNAT", - "--to-destination", fmt.Sprintf("%s:%d", c.IP, pm.ContainerPort), - "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-%s-%d", tag, natRuleIPTag(hostIP), pm.HostPort), - ) - cmd := exec.Command("iptables", args...) - output, err := cmd.CombinedOutput() - if err != nil { - fmt.Printf("Warning: failed to apply port mapping %s:%d->%s:%d: %v, output: %s\n", - displayHostIP(hostIP), pm.HostPort, c.IP, pm.ContainerPort, err, string(output)) - continue - } - fmt.Printf("Port mapping: %s:%d -> %s:%d\n", displayHostIP(hostIP), pm.HostPort, c.IP, pm.ContainerPort) + if c.IPv6NATAddress != "" { + _, err := reconcileIPv6PortMappingsLocked(c) + if err != nil { + return err } } - - // When container has public IPv4, apply full port passthrough DNAT so the - // container owns all ports on its public IP (no NAT management needed). - if len(c.PublicIPv4s) > 0 { - ensureIndependentIPv4Ingress(c, tag) - } - - applyIPv4EgressPolicy(c, bridge, subnet, tag) - if err := applyIPv6PortMappingsLocked(c); err != nil { - return err - } - - if err := applyFirewallRulesLocked(id); err != nil { - return err - } - - return nil -} - -func ensureIndependentIPv4Ingress(c *config.Container, tag string) { - if c == nil || c.IP == "" || len(c.PublicIPv4s) == 0 { - return - } - - for _, assignment := range c.PublicIPv4s { - hostIP := strings.TrimSpace(assignment.Address) - if hostIP == "" { - continue - } - // Full port passthrough: DNAT all TCP+UDP traffic on this public IP to the container. - for _, proto := range []string{"tcp", "udp"} { - args := []string{ - "-t", "nat", - "-I", "PREROUTING", "1", - "-d", hostIP, - "-p", proto, - "-j", "DNAT", - "--to-destination", c.IP, - "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-%s-all-%s", tag, natRuleIPTag(hostIP), proto), - } - cmd := exec.Command("iptables", args...) - output, err := cmd.CombinedOutput() - if err != nil { - fmt.Printf("Warning: failed to apply %s passthrough %s->%s: %v, output: %s\n", - proto, hostIP, c.IP, err, string(output)) - continue - } - fmt.Printf("IPv4 passthrough (%s): %s -> %s (all ports)\n", proto, hostIP, c.IP) - } - } -} - -func applyIPv4EgressPolicy(c *config.Container, bridge, subnet, tag string) { - if c == nil || strings.TrimSpace(c.IP) == "" { - return - } - if containerAllowsPublicIPv4Egress(c) { - if _, ok := primaryPublicIPv4Assignment(c); ok { - applyPublicIPv4SNAT(c, tag) - return - } - ensureContainerMasquerade(c, tag) - return - } - ensureIPv4EgressBlocked(c, bridge, subnet, tag) + return applyFirewallRulesLocked(id) } func containerAllowsPublicIPv4Egress(c *config.Container) bool { @@ -169,94 +85,11 @@ func containerAllowsPublicIPv4Egress(c *config.Container) bool { return c.PortMappingLimit > 0 || len(c.PortMappings) > 0 } -func ensureContainerMasquerade(c *config.Container, tag string) { - args := []string{ - "-s", c.IP + "/32", - "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-masq", tag), - "-j", "MASQUERADE", - } - if host := DetectPublicIPv4(); strings.TrimSpace(host.Interface) != "" { - args = append([]string{"-o", strings.TrimSpace(host.Interface)}, args...) - } else { - args = append([]string{"-o", "eth+"}, args...) - } - ensureNATRule("POSTROUTING", args) -} - -func ensureIPv4EgressBlocked(c *config.Container, bridge, subnet, tag string) { - args := []string{ - "-i", bridge, - "-s", c.IP + "/32", - "!", "-d", subnet, - "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-v4-egress-block", tag), - "-j", "REJECT", - } - ensureFilterRule("FORWARD", args) -} - -func ensureNATRule(chain string, args []string) { - check := append([]string{"-t", "nat", "-C", chain}, args...) - if exec.Command("iptables", check...).Run() == nil { - return - } - add := append([]string{"-t", "nat", "-I", chain, "1"}, args...) - exec.Command("iptables", add...).Run() -} - -func ensureFilterRule(chain string, args []string) { - check := append([]string{"-C", chain}, args...) - if exec.Command("iptables", check...).Run() == nil { - return - } - add := append([]string{"-I", chain, "1"}, args...) - exec.Command("iptables", add...).Run() -} - func deleteBridgeMasquerade(subnet string) { for exec.Command("iptables", "-t", "nat", "-D", "POSTROUTING", "-s", subnet, "-o", "eth+", "-j", "MASQUERADE").Run() == nil { } } -func applyPublicIPv4SNAT(c *config.Container, tag string) { - if c == nil || strings.TrimSpace(c.IP) == "" { - return - } - assignment, ok := primaryPublicIPv4Assignment(c) - if !ok { - return - } - hostIP := strings.TrimSpace(assignment.Address) - if hostIP == "" { - return - } - iface := strings.TrimSpace(assignment.Interface) - if iface == "" { - if info, ok := publicIPv4InfoByAddress(hostIP); ok { - iface = strings.TrimSpace(info.Interface) - } - } - if iface == "" { - if host := DetectPublicIPv4(); host.Interface != "" { - iface = host.Interface - } - } - args := []string{ - "-t", "nat", - "-I", "POSTROUTING", "1", - "-s", c.IP + "/32", - } - if iface != "" { - args = append(args, "-o", iface) - } - args = append(args, - "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-snat-%s", tag, natRuleIPTag(hostIP)), - "-j", "SNAT", "--to-source", hostIP, - ) - if output, err := exec.Command("iptables", args...).CombinedOutput(); err != nil { - fmt.Printf("Warning: failed to apply public IPv4 SNAT %s -> %s: %v, output: %s\n", c.IP, hostIP, err, string(output)) - } -} - func primaryPublicIPv4Assignment(c *config.Container) (config.PublicIPv4Assignment, bool) { if c == nil { return config.PublicIPv4Assignment{}, false @@ -349,14 +182,7 @@ func EnsureForwardRules(bridge string) { {"-i", bridge, "-j", "ACCEPT"}, } for _, args := range inputRules { - for { - deleteArgs := append([]string{"-D", "INPUT"}, args...) - if exec.Command("iptables", deleteArgs...).Run() != nil { - break - } - } - insertArgs := append([]string{"-I", "INPUT", "1"}, args...) - exec.Command("iptables", insertArgs...).Run() + ensureBridgeAcceptRule("INPUT", args) } forwardRules := [][]string{ @@ -365,14 +191,7 @@ func EnsureForwardRules(bridge string) { {"-i", bridge, "-o", bridge, "-j", "ACCEPT"}, } for _, args := range forwardRules { - for { - deleteArgs := append([]string{"-D", "FORWARD"}, args...) - if exec.Command("iptables", deleteArgs...).Run() != nil { - break - } - } - insertArgs := append([]string{"-I", "FORWARD", "1"}, args...) - exec.Command("iptables", insertArgs...).Run() + ensureBridgeAcceptRule("FORWARD", args) } } @@ -410,14 +229,7 @@ func ensureLibvirtForwardRules(bridge string) { if exec.Command("iptables", "-L", rule.chain, "-n").Run() != nil { continue } - for { - deleteArgs := append([]string{"-D", rule.chain}, rule.args...) - if exec.Command("iptables", deleteArgs...).Run() != nil { - break - } - } - insertArgs := append([]string{"-I", rule.chain, "1"}, rule.args...) - exec.Command("iptables", insertArgs...).Run() + ensureBridgeAcceptRule(rule.chain, rule.args) } } @@ -451,8 +263,8 @@ func (m *Manager) cleanPortMappingsLocked(id int) error { cleanupErrors = append(cleanupErrors, err) } } - for _, mapping := range c.PortMappings { - clearPortMappingConntrack(mapping) + for _, rule := range ipv4MappingRules(c, "", "", "") { + clearMappingRuleConntrack("iptables", rule, runPortMappingCommand) } } return errors.Join(cleanupErrors...) @@ -486,6 +298,8 @@ func deleteTaggedIPTablesRules(table, chain, marker string) error { "delete iptables %s/%s rule [%s]: %w: %s", tableName(table), chain, strings.Join(spec, " "), err, outStr, )) + } else { + clearMappingRuleConntrack("iptables", mappingRule{table, chain, spec[2:]}, runPortMappingCommand) } } return errors.Join(deleteErrors...) @@ -521,11 +335,11 @@ func taggedRuleSpecifications(output []byte, marker string) [][]string { var specs [][]string for _, line := range strings.Split(string(output), "\n") { trimmed := strings.TrimSpace(line) - if trimmed == "" || !strings.Contains(trimmed, marker) { + if trimmed == "" { continue } fields := parseIPTablesRuleFields(trimmed) - if len(fields) >= 2 && fields[0] == "-A" { + if len(fields) >= 2 && fields[0] == "-A" && strings.HasPrefix(ruleOption(fields[2:], "--comment"), marker) { fields[0] = "-D" specs = append(specs, fields) } @@ -566,34 +380,6 @@ func tableName(table string) string { return table } -func clearPortMappingConntrack(mapping config.PortMapping) { - args := portMappingConntrackDeleteArgs(mapping) - if len(args) == 0 { - return - } - // conntrack exits non-zero when no matching flow exists; that is already clean. - _ = exec.Command("conntrack", args...).Run() -} - -func portMappingConntrackDeleteArgs(mapping config.PortMapping) []string { - protocol := strings.ToLower(strings.TrimSpace(mapping.Protocol)) - if protocol != "tcp" && protocol != "udp" { - return nil - } - if mapping.HostPort < 1 || mapping.HostPort > 65535 { - return nil - } - args := []string{ - "-D", - "-p", protocol, - "--dport", strconv.Itoa(mapping.HostPort), - } - if hostIP := strings.TrimSpace(mapping.HostIP); hostIP != "" { - args = append(args, "--dst", hostIP) - } - return args -} - // SetupDefaultPortMappings creates default port mappings func SetupDefaultPortMappings(sshPort int) []config.PortMapping { return []config.PortMapping{ @@ -630,6 +416,7 @@ func (m *Manager) AddPortMapping(id int, pm config.PortMapping) ([]config.PortMa if err != nil { return nil, err } + previous := *c candidate := *c candidate.PortMappings = append(append([]config.PortMapping(nil), c.PortMappings...), normalized) if err := validateIPv6MappingInventory(&candidate); err != nil { @@ -639,6 +426,8 @@ func (m *Manager) AddPortMapping(id int, pm config.PortMapping) ([]config.PortMa if err := persistAndReloadMappings(m, c); err != nil { return nil, err } + clearChangedIPv4Mappings(&previous, c) + clearChangedIPv6Mappings(&previous, c) return c.PortMappings, nil } @@ -661,6 +450,7 @@ func (m *Manager) UpdatePortMapping(id int, index int, pm config.PortMapping) ([ if strings.EqualFold(existing.Description, "SSH") { normalized.Description = "SSH" } + previous := *c candidate := *c candidate.PortMappings = append([]config.PortMapping(nil), c.PortMappings...) candidate.PortMappings[index] = normalized @@ -671,8 +461,8 @@ func (m *Manager) UpdatePortMapping(id int, index int, pm config.PortMapping) ([ if err := persistAndReloadMappings(m, c); err != nil { return nil, err } - clearPortMappingConntrack(existing) - clearSynchronizedIPv6Conntrack(c, existing) + clearChangedIPv4Mappings(&previous, c) + clearChangedIPv6Mappings(&previous, c) return c.PortMappings, nil } @@ -691,12 +481,13 @@ func (m *Manager) DeletePortMapping(id int, index int) ([]config.PortMapping, er if strings.EqualFold(removed.Description, "SSH") { return nil, fmt.Errorf("SSH default mapping cannot be deleted") } - c.PortMappings = append(c.PortMappings[:index], c.PortMappings[index+1:]...) + previous := *c + c.PortMappings = append(append([]config.PortMapping(nil), c.PortMappings[:index]...), c.PortMappings[index+1:]...) if err := persistAndReloadMappings(m, c); err != nil { return nil, err } - clearPortMappingConntrack(removed) - clearSynchronizedIPv6Conntrack(c, removed) + clearChangedIPv4Mappings(&previous, c) + clearChangedIPv6Mappings(&previous, c) return c.PortMappings, nil } @@ -1351,9 +1142,39 @@ func applyFirewallRulesLocked(id int) error { snapshot := *c c = &snapshot - // Always clean existing firewall rules first + rules, err := plannedFirewallRules(c) + if err != nil { + return err + } + healthy, err := firewallRulesPresent(c, rules) + if err != nil || healthy { + return err + } cleanFirewallRulesLocked(id) + for _, rule := range rules { + if output, err := runPortMappingCommand(rule.command, rule.args...); err != nil { + return fmt.Errorf("apply firewall: %w: %s", err, output) + } + } + return nil +} +type firewallCommand struct { + command string + args []string +} + +func plannedFirewallRules(c *config.Container) ([]firewallCommand, error) { + var rules []firewallCommand + emit := func(command string, args []string) error { + rules = append(rules, firewallCommand{command, append([]string(nil), args...)}) + return nil + } + err := walkFirewallRules(c, emit) + return rules, err +} + +func walkFirewallRules(c *config.Container, emit func(string, []string) error) error { // If firewall is disabled or no rules, nothing to apply if !c.FirewallEnabled { return nil @@ -1368,16 +1189,16 @@ func applyFirewallRulesLocked(id int) error { if containerIP == "" && len(containerIPv6s) == 0 { return nil } - tag := clicdTag(id) + tag := clicdTag(c.ID) defaultAction := normalizeFirewallDefaultAction(c.FirewallDefaultAction) if defaultAction == "DROP" { if containerIP != "" { - if err := applyDefaultFirewallPolicy(tag, bridge, containerIP); err != nil { + if err := applyDefaultFirewallPolicy(tag, bridge, containerIP, emit); err != nil { return err } } - if err := applyDefaultFirewallIPv6Policy(tag, bridge, containerIPv6s); err != nil { + if err := applyDefaultFirewallIPv6Policy(tag, bridge, containerIPv6s, emit); err != nil { return err } } @@ -1388,13 +1209,13 @@ func applyFirewallRulesLocked(id int) error { continue } if containerIP != "" && firewallRuleAppliesToFamily(rule, true) { - if err := applyOneFirewallRule(tag, bridge, containerIP, rule); err != nil { - return fmt.Errorf("failed to apply firewall rule %s for container %d: %w", rule.ID, id, err) + if err := applyOneFirewallRule(tag, bridge, containerIP, rule, emit); err != nil { + return fmt.Errorf("failed to apply firewall rule %s for container %d: %w", rule.ID, c.ID, err) } } if len(containerIPv6s) > 0 && firewallRuleAppliesToFamily(rule, false) { - if err := applyOneFirewallIPv6Rule(tag, bridge, containerIPv6s, rule); err != nil { - return fmt.Errorf("failed to apply IPv6 firewall rule %s for container %d: %w", rule.ID, id, err) + if err := applyOneFirewallIPv6Rule(tag, bridge, containerIPv6s, rule, emit); err != nil { + return fmt.Errorf("failed to apply IPv6 firewall rule %s for container %d: %w", rule.ID, c.ID, err) } } } @@ -1487,7 +1308,7 @@ func firewallIPv6Addresses(c *config.Container) []string { return result } -func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallRule) error { +func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallRule, emit func(string, []string) error) error { commentTag := fmt.Sprintf("clicd-%s-fw-%s", tag, rule.ID) // Build base iptables args @@ -1543,15 +1364,13 @@ func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallR // Comment tag for cleanup args = append(args, "-m", "comment", "--comment", commentTag) - cmd := exec.Command("iptables", args...) - output, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("iptables error: %s", string(output)) + if err := emit("iptables", args); err != nil { + return err } return nil } -func applyOneFirewallIPv6Rule(tag, bridge string, containerIPs []string, rule config.FirewallRule) error { +func applyOneFirewallIPv6Rule(tag, bridge string, containerIPs []string, rule config.FirewallRule, emit func(string, []string) error) error { for _, containerIP := range containerIPs { commentTag := fmt.Sprintf("clicd-%s-fw-%s-v6-%s", tag, rule.ID, firewallCommentIPTag(containerIP)) args := []string{"-I", "FORWARD", "1"} @@ -1595,10 +1414,8 @@ func applyOneFirewallIPv6Rule(tag, bridge string, containerIPs []string, rule co args = append(args, "-j", action) args = append(args, "-m", "comment", "--comment", commentTag) - cmd := exec.Command("ip6tables", args...) - output, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("ip6tables error: %s", string(output)) + if err := emit("ip6tables", args); err != nil { + return err } } return nil @@ -1633,7 +1450,7 @@ func normalizePortSpec(port string) string { return strings.Join(parts, ",") } -func applyDefaultFirewallPolicy(tag, bridge, containerIP string) error { +func applyDefaultFirewallPolicy(tag, bridge, containerIP string, emit func(string, []string) error) error { defaults := [][]string{ { "-I", "FORWARD", "1", @@ -1651,16 +1468,14 @@ func applyDefaultFirewallPolicy(tag, bridge, containerIP string) error { }, } for _, args := range defaults { - cmd := exec.Command("iptables", args...) - output, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("iptables default firewall error: %s", string(output)) + if err := emit("iptables", args); err != nil { + return err } } return nil } -func applyDefaultFirewallIPv6Policy(tag, bridge string, containerIPs []string) error { +func applyDefaultFirewallIPv6Policy(tag, bridge string, containerIPs []string, emit func(string, []string) error) error { for _, containerIP := range containerIPs { defaults := [][]string{ { @@ -1679,10 +1494,8 @@ func applyDefaultFirewallIPv6Policy(tag, bridge string, containerIPs []string) e }, } for _, args := range defaults { - cmd := exec.Command("ip6tables", args...) - output, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("ip6tables default firewall error: %s", string(output)) + if err := emit("ip6tables", args); err != nil { + return err } } } diff --git a/backend/internal/lxc/portmap_ipv6.go b/backend/internal/lxc/portmap_ipv6.go index 947ae57..080045a 100644 --- a/backend/internal/lxc/portmap_ipv6.go +++ b/backend/internal/lxc/portmap_ipv6.go @@ -391,11 +391,7 @@ func persistIPv6MappingChange(m *Manager, current *config.Container, candidate c return fmt.Errorf("IPv6 mapping configuration saved, but applying it failed: %w", err) } } - _, host, _, _ := nat6PortEndpoint(&previous) - oldMappings, _ := effectiveIPv6Mappings(&previous, host) - for _, mapping := range oldMappings { - clearIPv6PortMappingConntrack(mapping) - } + clearChangedIPv6Mappings(&previous, &candidate) return nil } @@ -436,10 +432,7 @@ func (m *Manager) ApplyIPv6PortMappings(id int) error { if err := validateIPv6MappingInventory(c); err != nil { return err } - if err := cleanIPv6PortMappingsLocked(id); err != nil { - return err - } - if err := applyIPv6PortMappingsLocked(c); err != nil { + if _, err := reconcileIPv6PortMappingsLocked(c); err != nil { return err } return applyFirewallRulesLocked(id) @@ -453,25 +446,63 @@ func applyIPv6PortMappingsLocked(c *config.Container) error { if c.Status != "running" { return nil } + _, err := reconcileIPv6PortMappingsLocked(c) + return err +} + +func ipv6MappingRules(c *config.Container) ([]mappingRule, error) { guest, host, _, enabled := nat6PortEndpoint(c) - if !enabled { - return nil + if !enabled || c.Status != "running" { + return nil, nil } if err := validateIPv6MappingInventory(c); err != nil { - return err + return nil, err } mappings, err := effectiveIPv6Mappings(c, host) if err != nil { - return err + return nil, err } + var rules []mappingRule for _, mapping := range mappings { for _, args := range ipv6PortMappingRuleArgs(c.ID, guest, host, mapping) { - if out, err := runIPv6PortMappingCommand("ip6tables", args...); err != nil { - return errors.Join(fmt.Errorf("apply IPv6 NAT port %d/%s: %w: %s", mapping.HostPort, mapping.Protocol, err, strings.TrimSpace(string(out))), cleanIPv6PortMappingsLocked(c.ID)) + table, start := "filter", 2 + if args[start] == "-t" { + table = args[start+1] + start += 2 } + rules = append(rules, mappingRule{table, args[start+1], args[start+3:]}) + } + } + return rules, nil +} + +func reconcileIPv6PortMappingsLocked(c *config.Container) (bool, error) { + rules, err := ipv6MappingRules(c) + if err != nil { + return false, err + } + return reconcileMappingRules("ip6tables", "clicd-"+clicdTag(c.ID)+"-nat6-port-", + []mappingRule{{table: "nat", chain: "PREROUTING"}, {table: "nat", chain: "OUTPUT"}, {table: "filter", chain: "FORWARD"}}, rules, runIPv6PortMappingCommand) +} + +func clearChangedIPv6Mappings(previous, current *config.Container) { + old, err := ipv6MappingRules(previous) + if err != nil { + return + } + next, err := ipv6MappingRules(current) + if err != nil { + return + } + wanted := map[string]bool{} + for _, rule := range next { + wanted[mappingRuleKey(rule)] = true + } + for _, rule := range old { + if !wanted[mappingRuleKey(rule)] { + clearMappingRuleConntrack("ip6tables", rule, runIPv6PortMappingCommand) } } - return nil } func ipv6PortMappingRuleArgs(id int, guest, host string, mapping config.PortMapping) [][]string { @@ -511,48 +542,18 @@ func cleanIPv6PortMappingsLocked(id int) error { for _, args := range taggedRuleSpecifications(out, marker) { if output, err := runIPv6PortMappingCommand("ip6tables", append([]string{"-w", "5", "-t", target.table}, args...)...); err != nil && !isIPTablesRuleNotFoundError(string(output)) { cleanupErrors = append(cleanupErrors, fmt.Errorf("remove IPv6 NAT rule: %w: %s", err, strings.TrimSpace(string(output)))) + } else { + clearMappingRuleConntrack("ip6tables", mappingRule{target.table, target.chain, args[2:]}, runIPv6PortMappingCommand) } } } if c := config.FindContainer(id); c != nil { snapshot := *c c = &snapshot - _, host, _, _ := nat6PortEndpoint(c) - mappings, _ := effectiveIPv6Mappings(c, host) - for _, mapping := range mappings { - clearIPv6PortMappingConntrack(mapping) + rules, _ := ipv6MappingRules(c) + for _, rule := range rules { + clearMappingRuleConntrack("ip6tables", rule, runIPv6PortMappingCommand) } } return errors.Join(cleanupErrors...) } - -func ipv6PortMappingConntrackDeleteArgs(mapping config.PortMapping) []string { - if mapping.HostPort < 1 || mapping.HostPort > 65535 || (mapping.Protocol != "tcp" && mapping.Protocol != "udp") { - return nil - } - args := []string{"-D", "-f", "ipv6", "-p", mapping.Protocol, "--dport", strconv.Itoa(mapping.HostPort)} - if mapping.HostIP != "" { - args = append(args, "--dst", mapping.HostIP) - } - return args -} - -func clearIPv6PortMappingConntrack(mapping config.PortMapping) { - // An unavailable uplink must not turn an exact cleanup into a global - // deletion of unrelated IPv6 services using the same port. - if mapping.HostIP == "" { - return - } - if args := ipv6PortMappingConntrackDeleteArgs(mapping); len(args) > 0 { - _, _ = runIPv6PortMappingCommand("conntrack", args...) - } -} - -func clearSynchronizedIPv6Conntrack(c *config.Container, mapping config.PortMapping) { - if !ipv6MappingsSyncIPv4(c) || c.IPv6NATAddress == "" { - return - } - _, host, _, _ := nat6PortEndpoint(c) - mapping.HostIP = host - clearIPv6PortMappingConntrack(mapping) -} diff --git a/backend/internal/lxc/portmap_ipv6_test.go b/backend/internal/lxc/portmap_ipv6_test.go index a08041c..73144bc 100644 --- a/backend/internal/lxc/portmap_ipv6_test.go +++ b/backend/internal/lxc/portmap_ipv6_test.go @@ -125,8 +125,8 @@ func TestIPv6NATRuleAndConntrackFamilies(t *testing.T) { if forward := strings.Join(rules[2], " "); !strings.Contains(forward, "--ctstate DNAT") || !strings.Contains(forward, "--dport 8080") || !strings.Contains(forward, "-d fd00::2/128") { t.Fatalf("translated ingress was not restricted to the actual guest service: %s", forward) } - want := []string{"-D", "-f", "ipv6", "-p", "tcp", "--dport", "30080", "--dst", "2001:db8::10"} - if got := ipv6PortMappingConntrackDeleteArgs(mapping); !reflect.DeepEqual(got, want) { + want := []string{"-D", "-f", "ipv6", "--dst-nat", "--reply-src", "fd00::2", "-p", "tcp", "--dport", "30080", "--dst", "2001:db8::10/128", "--reply-port-src", "8080"} + if got := mappingRuleConntrackArgs("ip6tables", mappingRule{"nat", "PREROUTING", rules[0][7:]}); !reflect.DeepEqual(got, want) { t.Fatalf("IPv6 cleanup could target another family: %v", got) } c := &config.Container{IPv6NATAddress: "fd00::2"} @@ -260,7 +260,7 @@ func TestIPv6StoppedMappingsAndUnavailableConntrackHaveNoSideEffects(t *testing. if err := applyIPv6PortMappingsLocked(c); err != nil { t.Fatal(err) } - clearIPv6PortMappingConntrack(config.PortMapping{HostPort: 30080, Protocol: "tcp"}) + clearMappingRuleConntrack("ip6tables", mappingRule{"nat", "PREROUTING", []string{"-j", "DNAT", "--to-destination", ""}}, runIPv6PortMappingCommand) if calls != 0 { t.Fatal("stopped guest installed DNAT or unavailable host triggered global conntrack deletion") } diff --git a/backend/internal/lxc/portmap_reconcile.go b/backend/internal/lxc/portmap_reconcile.go new file mode 100644 index 0000000..8554aeb --- /dev/null +++ b/backend/internal/lxc/portmap_reconcile.go @@ -0,0 +1,330 @@ +package lxc + +import ( + "errors" + "fmt" + "net" + "net/netip" + "os/exec" + "slices" + "sort" + "strconv" + "strings" + + "clicd/internal/config" +) + +var runPortMappingCommand = func(command string, args ...string) ([]byte, error) { + return exec.Command(command, args...).CombinedOutput() +} + +type mappingRule struct { + table, chain string + args []string +} + +// Compare ordered firewall rules against the kernel, including their precedence +// over broad bridge accepts. This keeps firewall self-healing after an external +// flush without deleting/reinserting healthy rules during routine NAT polling. +func firewallRulesPresent(c *config.Container, rules []firewallCommand) (bool, error) { + marker := "clicd-" + clicdTag(c.ID) + "-fw-" + bridge := "lxcbr0" + if c.IsKVM() { + bridge = "virbr0" + } + for _, command := range []string{"iptables", "ip6tables"} { + var wanted []string + for _, rule := range rules { + if rule.command == command { + wanted = append(wanted, mappingRuleKey(mappingRule{"filter", "FORWARD", rule.args[3:]})) + } + } + slices.Reverse(wanted) // Each original command inserts at position 1. + output, err := runPortMappingCommand(command, "-w", "5", "-S", "FORWARD") + if err != nil { + if command == "ip6tables" && len(wanted) == 0 && len(firewallIPv6Addresses(c)) == 0 { + continue // Hosts with the IPv6 module disabled need no IPv6 policy. + } + return false, fmt.Errorf("inspect %s firewall: %w: %s", command, err, output) + } + var found []string + broadAccept := false + for _, line := range strings.Split(string(output), "\n") { + fields := parseIPTablesRuleFields(line) + if len(fields) < 3 || fields[0] != "-A" || fields[1] != "FORWARD" { + continue + } + args := fields[2:] + if strings.HasPrefix(ruleOption(args, "--comment"), marker) { + if broadAccept { + return false, nil + } + found = append(found, mappingRuleKey(mappingRule{"filter", "FORWARD", args})) + } else if ruleOption(args, "-j") == "ACCEPT" && ruleOption(args, "-s") == "" && ruleOption(args, "-d") == "" && + (ruleOption(args, "-i") == bridge || ruleOption(args, "-o") == bridge) { + broadAccept = true + } + } + if !slices.Equal(found, wanted) { + return false, nil + } + } + return true, nil +} + +func ensureBridgeAcceptRule(chain string, args []string) { + if _, err := runPortMappingCommand("iptables", append([]string{"-w", "5", "-C", chain}, args...)...); err == nil { + return + } + output, err := runPortMappingCommand("iptables", "-w", "5", "-S", chain) + if err != nil { + return + } + position, count := 1, 0 + for _, line := range strings.Split(string(output), "\n") { + fields := parseIPTablesRuleFields(line) + if len(fields) < 3 || fields[0] != "-A" || fields[1] != chain { + continue + } + count++ + if strings.HasPrefix(ruleOption(fields[2:], "--comment"), "clicd-") { + position = count + 1 + } + } + _, _ = runPortMappingCommand("iptables", append([]string{"-w", "5", "-I", chain, strconv.Itoa(position)}, args...)...) +} + +func ruleOption(args []string, option string) string { + for i := 0; i+1 < len(args); i++ { + if args[i] == option { + return args[i+1] + } + } + return "" +} + +// iptables -S canonicalizes addresses, moves match modules, and adds implicit +// tcp/udp matches. Compare these representations without depending on ordering. +func mappingRuleKey(rule mappingRule) string { + parts := []string{rule.table, rule.chain} + negated := false + for i := 0; i < len(rule.args); i++ { + key := rule.args[i] + if key == "!" { + negated = true + continue + } + value := "" + if i+1 < len(rule.args) && !strings.HasPrefix(rule.args[i+1], "-") && rule.args[i+1] != "!" { + i++ + value = rule.args[i] + } + if !negated && ((key == "-m" && (value == "tcp" || value == "udp")) || + (key == "--reject-with" && value == "icmp-port-unreachable")) { + continue + } + if key == "-s" || key == "-d" { + if prefix, err := netip.ParsePrefix(value); err == nil { + value = prefix.Masked().String() + } else if address, err := netip.ParseAddr(value); err == nil { + value = netip.PrefixFrom(address, address.BitLen()).String() + } + } + if key == "--ctstate" { + states := strings.Split(value, ",") + sort.Strings(states) + value = strings.Join(states, ",") + } + if negated { + key = "!" + key + negated = false + } + parts = append(parts, key+"="+value) + } + sort.Strings(parts[2:]) + return strings.Join(parts, "\x00") +} + +// Reconcile only this owner's network rules; firewall rules have their own +// ordering and lifecycle. Read every chain before changing anything. Existing +// matching rules (and their counters/conntrack entries) are left in place. +func reconcileMappingRules(command, marker string, targets, desired []mappingRule, run func(string, ...string) ([]byte, error)) (bool, error) { + wanted := make(map[string]bool, len(desired)) + priority := make(map[string]int, len(desired)) + for i, rule := range desired { + wanted[mappingRuleKey(rule)] = true + priority[mappingRuleKey(rule)] = i + } + present := map[string]bool{} + liveRules := map[string][]mappingRule{} + filterPosition := map[string]int{} + var stale []mappingRule + for _, target := range targets { + output, err := run(command, "-w", "5", "-t", target.table, "-S", target.chain) + if err != nil { + return false, fmt.Errorf("list %s %s/%s: %w: %s", command, target.table, target.chain, err, output) + } + position := 0 + for _, line := range strings.Split(string(output), "\n") { + fields := parseIPTablesRuleFields(line) + if len(fields) < 3 || fields[0] != "-A" || fields[1] != target.chain { + continue + } + position++ + liveRules[target.table+"/"+target.chain] = append(liveRules[target.table+"/"+target.chain], mappingRule{target.table, target.chain, fields[2:]}) + comment := ruleOption(fields[2:], "--comment") + if target.table == "filter" && strings.HasPrefix(comment, "clicd-") && strings.Contains(comment, "-fw-") { + filterPosition[target.chain] = position + 1 + } + if !strings.HasPrefix(comment, marker) || strings.HasPrefix(comment, marker+"fw-") { + continue + } + rule := mappingRule{target.table, target.chain, fields[2:]} + key := mappingRuleKey(rule) + if !wanted[key] || present[key] { + stale = append(stale, rule) + } else { + present[key] = true + } + } + } + changed := false + for _, rule := range desired { + key := mappingRuleKey(rule) + if present[key] { + continue + } + position := 1 + if rule.table == "filter" && filterPosition[rule.chain] > 0 { + position = filterPosition[rule.chain] + } + chainKey := rule.table + "/" + rule.chain + // Retain the ordering produced by the original insert-at-head plan, + // notably independent-public-IP passthrough ahead of explicit mappings. + for i, existing := range liveRules[chainKey] { + if rank, ok := priority[mappingRuleKey(existing)]; ok && rank > priority[key] && i+2 > position { + position = i + 2 + } + } + args := append([]string{"-w", "5", "-t", rule.table, "-I", rule.chain, strconv.Itoa(position)}, rule.args...) + if output, err := run(command, args...); err != nil { + // Keep the old working mapping if installing its replacement fails. + return changed, fmt.Errorf("install %s mapping: %w: %s", command, err, output) + } + present[key], changed = true, true + liveRules[chainKey] = slices.Insert(liveRules[chainKey], position-1, rule) + } + var failures []error + for _, rule := range stale { + args := append([]string{"-w", "5", "-t", rule.table, "-D", rule.chain}, rule.args...) + if output, err := run(command, args...); err != nil { + failures = append(failures, fmt.Errorf("remove obsolete %s mapping: %w: %s", command, err, output)) + continue + } + changed = true + if !wanted[mappingRuleKey(rule)] { + clearMappingRuleConntrack(command, rule, run) + } + } + return changed, errors.Join(failures...) +} + +// Match both the original endpoint and the translated endpoint. A wildcard +// host binding must never delete unrelated outbound flows to the same port. +func mappingRuleConntrackArgs(command string, rule mappingRule) []string { + if rule.table != "nat" || ruleOption(rule.args, "-j") != "DNAT" { + return nil + } + family := "ipv4" + if command == "ip6tables" { + family = "ipv6" + } + target := ruleOption(rule.args, "--to-destination") + guest, port, err := net.SplitHostPort(target) + if err != nil { + guest, port = target, "" + } + if _, err := netip.ParseAddr(guest); err != nil { + return nil + } + args := []string{"-D", "-f", family, "--dst-nat", "--reply-src", guest} + if protocol := ruleOption(rule.args, "-p"); protocol != "" { + args = append(args, "-p", protocol) + } + if hostPort := ruleOption(rule.args, "--dport"); hostPort != "" { + args = append(args, "--dport", hostPort) + } + if host := ruleOption(rule.args, "-d"); host != "" { + args = append(args, "--dst", host) + } + if port != "" { + args = append(args, "--reply-port-src", port) + } + return args +} + +func clearMappingRuleConntrack(command string, rule mappingRule, run func(string, ...string) ([]byte, error)) { + if args := mappingRuleConntrackArgs(command, rule); len(args) > 0 { + // conntrack returns nonzero when no matching flow remains. + _, _ = run("conntrack", args...) + } +} + +func ipv4MappingRules(c *config.Container, bridge, subnet, iface string) []mappingRule { + tag := clicdTag(c.ID) + var rules []mappingRule + for _, pm := range c.PortMappings { + for _, hostIP := range expandPortMappingHostIPs(c, pm) { + args := []string{"-p", pm.Protocol} + if hostIP != "" { + args = append(args, "-d", hostIP) + } + args = append(args, "--dport", strconv.Itoa(pm.HostPort), "-j", "DNAT", "--to-destination", net.JoinHostPort(c.IP, strconv.Itoa(pm.ContainerPort)), + "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-%s-%d", tag, natRuleIPTag(hostIP), pm.HostPort)) + rules = append(rules, mappingRule{"nat", "PREROUTING", args}) + } + } + for _, assignment := range c.PublicIPv4s { + if host := strings.TrimSpace(assignment.Address); host != "" { + for _, protocol := range []string{"tcp", "udp"} { + rules = append(rules, mappingRule{"nat", "PREROUTING", []string{"-d", host, "-p", protocol, "-j", "DNAT", "--to-destination", c.IP, + "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-%s-all-%s", tag, natRuleIPTag(host), protocol)}}) + } + } + } + if !containerAllowsPublicIPv4Egress(c) { + return append(rules, mappingRule{"filter", "FORWARD", []string{"-i", bridge, "-s", c.IP + "/32", "!", "-d", subnet, + "-m", "comment", "--comment", "clicd-" + tag + "-v4-egress-block", "-j", "REJECT"}}) + } + args := []string{"-s", c.IP + "/32"} + if assignment, ok := primaryPublicIPv4Assignment(c); ok { + if assignment.Interface != "" { + iface = assignment.Interface + } else if info, ok := publicIPv4InfoByAddress(assignment.Address); ok && info.Interface != "" { + iface = info.Interface + } + if iface != "" { + args = append(args, "-o", iface) + } + args = append(args, "-m", "comment", "--comment", "clicd-"+tag+"-snat-"+natRuleIPTag(assignment.Address), "-j", "SNAT", "--to-source", assignment.Address) + } else { + if iface == "" { + iface = "eth+" + } + args = append(args, "-o", iface, "-m", "comment", "--comment", "clicd-"+tag+"-masq", "-j", "MASQUERADE") + } + return append(rules, mappingRule{"nat", "POSTROUTING", args}) +} + +func clearChangedIPv4Mappings(previous, current *config.Container) { + old := ipv4MappingRules(previous, "", "", "") + next := map[string]bool{} + for _, rule := range ipv4MappingRules(current, "", "", "") { + next[mappingRuleKey(rule)] = true + } + for _, rule := range old { + if !next[mappingRuleKey(rule)] { + clearMappingRuleConntrack("iptables", rule, runPortMappingCommand) + } + } +} diff --git a/backend/internal/lxc/portmap_reconcile_test.go b/backend/internal/lxc/portmap_reconcile_test.go new file mode 100644 index 0000000..ab1527d --- /dev/null +++ b/backend/internal/lxc/portmap_reconcile_test.go @@ -0,0 +1,313 @@ +package lxc + +import ( + "errors" + "reflect" + "strings" + "testing" + + "clicd/internal/config" +) + +type mappingKernel struct { + rules []mappingRule + writes, invalidated [][]string + failList, failInsert bool +} + +func (k *mappingKernel) run(command string, args ...string) ([]byte, error) { + if command == "conntrack" { + k.invalidated = append(k.invalidated, append([]string(nil), args...)) + return nil, nil + } + table := ruleOption(args, "-t") + if table == "" { + table = "filter" + } + for i, arg := range args { + switch arg { + case "-S": + if k.failList { + return nil, errors.New("permission denied") + } + var lines []string + for _, rule := range k.rules { + if rule.table == table && rule.chain == args[i+1] { + lines = append(lines, "-A "+rule.chain+" "+strings.Join(rule.args, " ")) + } + } + return []byte(strings.Join(lines, "\n")), nil + case "-I": + if k.failInsert { + return nil, errors.New("xtables busy") + } + k.writes = append(k.writes, append([]string(nil), args...)) + rule := mappingRule{table, args[i+1], append([]string(nil), args[i+3:]...)} + k.rules = append([]mappingRule{rule}, k.rules...) + return nil, nil + case "-D": + k.writes = append(k.writes, append([]string(nil), args...)) + key := mappingRuleKey(mappingRule{table, args[i+1], args[i+2:]}) + for j, rule := range k.rules { + if mappingRuleKey(rule) == key { + k.rules = append(k.rules[:j], k.rules[j+1:]...) + return nil, nil + } + } + return nil, errors.New("missing rule") + } + } + return nil, errors.New("unexpected command: " + strings.Join(args, " ")) +} + +func testMappingContainer() *config.Container { + return &config.Container{ID: 12, Status: "running", IP: "192.168.122.20", PortMappingLimit: 3, + PortMappings: []config.PortMapping{{HostPort: 32022, ContainerPort: 22, Protocol: "tcp"}, {HostPort: 32080, ContainerPort: 80, Protocol: "tcp"}}} +} + +func testIPv4Rules(c *config.Container) []mappingRule { + return ipv4MappingRules(c, "virbr0", "192.168.122.0/24", "eth0") +} +func testReconcile(k *mappingKernel, rules []mappingRule) (bool, error) { + return reconcileMappingRules("iptables", "clicd-c12-", []mappingRule{{table: "nat", chain: "PREROUTING"}, {table: "nat", chain: "POSTROUTING"}, {table: "filter", chain: "FORWARD"}}, rules, k.run) +} + +func TestMappingReconcilePreservesEstablishedFlowsAcrossPollsAndRestarts(t *testing.T) { + c := testMappingContainer() + desired := testIPv4Rules(c) + k := &mappingKernel{rules: append([]mappingRule(nil), desired...)} + // Simulate iptables' canonical output (implicit match, /32, different order). + k.rules[0].args = []string{"-m", "comment", "--comment", "clicd-c12-any-32022", "-p", "tcp", "-m", "tcp", "--dport", "32022", "-j", "DNAT", "--to-destination", "192.168.122.20:22"} + for poll := 0; poll < 20; poll++ { + changed, err := testReconcile(k, testIPv4Rules(c)) + if err != nil || changed || len(k.writes) != 0 || len(k.invalidated) != 0 { + t.Fatalf("poll %d changed healthy state: %v %v %+v", poll, changed, err, k) + } + } +} + +func TestMappingReconcileRepairsMissingRuleWithoutClearingFlows(t *testing.T) { + desired := testIPv4Rules(testMappingContainer()) + k := &mappingKernel{rules: append([]mappingRule(nil), desired[1:]...)} + changed, err := testReconcile(k, desired) + if err != nil || !changed || len(k.writes) != 1 || len(k.invalidated) != 0 { + t.Fatalf("repair: %v %v %+v", changed, err, k) + } + k.writes = nil + if changed, err = testReconcile(k, desired); err != nil || changed || len(k.writes) != 0 { + t.Fatalf("repair not idempotent: %v %v", changed, err) + } +} + +func TestMappingChangeInvalidatesOnlyOldTranslatedEndpoint(t *testing.T) { + c := testMappingContainer() + k := &mappingKernel{rules: testIPv4Rules(c)} + c.PortMappings[1].ContainerPort = 8080 + changed, err := testReconcile(k, testIPv4Rules(c)) + if err != nil || !changed || len(k.writes) != 2 || len(k.invalidated) != 1 { + t.Fatalf("update: %v %v %+v", changed, err, k) + } + args := k.invalidated[0] + if ruleOption(args, "--dport") != "32080" || ruleOption(args, "--reply-src") != c.IP || ruleOption(args, "--reply-port-src") != "80" || !strings.Contains(strings.Join(args, " "), "--dst-nat") { + t.Fatalf("overbroad invalidation: %v", args) + } + if k.writes[0][4] != "-I" || k.writes[1][4] != "-D" { + t.Fatal("removed old mapping before installing replacement") + } +} + +func TestMappingAddDeleteAndDescriptionChangesPreserveOtherPorts(t *testing.T) { + c := testMappingContainer() + k := &mappingKernel{rules: testIPv4Rules(c)} + c.PortMappings = append(c.PortMappings, config.PortMapping{HostPort: 32053, ContainerPort: 53, Protocol: "udp"}) + if _, err := testReconcile(k, testIPv4Rules(c)); err != nil || len(k.invalidated) != 0 { + t.Fatalf("add interrupted existing flows: %v", err) + } + c.PortMappings[0].Description = "renamed" + k.writes = nil + if changed, err := testReconcile(k, testIPv4Rules(c)); err != nil || changed { + t.Fatalf("description changed kernel state: %v", err) + } + c.PortMappings = c.PortMappings[:2] + if _, err := testReconcile(k, testIPv4Rules(c)); err != nil || len(k.invalidated) != 1 || ruleOption(k.invalidated[0], "-p") != "udp" { + t.Fatalf("delete invalidation: %v %v", err, k.invalidated) + } +} + +func TestMappingReconcilePreservesForeignAndFirewallRules(t *testing.T) { + desired := testIPv4Rules(testMappingContainer()) + k := &mappingKernel{rules: append([]mappingRule(nil), desired...)} + foreign := []mappingRule{ + {"filter", "FORWARD", []string{"-j", "DROP", "-m", "comment", "--comment", "clicd-c12-fw-default-in"}}, + {"nat", "PREROUTING", []string{"-j", "ACCEPT", "-m", "comment", "--comment", "clicd-c123-any-32022"}}, + {"nat", "PREROUTING", []string{"-j", "ACCEPT", "-m", "comment", "--comment", "other-clicd-c12-note"}}, + } + k.rules = append(k.rules, foreign...) + if changed, err := testReconcile(k, desired); err != nil || changed || len(k.writes) != 0 { + t.Fatalf("touched foreign rules: %v %v", changed, err) + } +} + +func TestMappingDuplicateCleanupPreservesConntrack(t *testing.T) { + desired := testIPv4Rules(testMappingContainer()) + k := &mappingKernel{rules: append(append([]mappingRule(nil), desired...), desired[0])} + if _, err := testReconcile(k, desired); err != nil || len(k.writes) != 1 || len(k.invalidated) != 0 { + t.Fatalf("duplicate cleanup: %v %+v", err, k) + } +} + +func TestMappingFailuresKeepWorkingRuleAndRetry(t *testing.T) { + for _, kind := range []string{"list", "insert"} { + t.Run(kind, func(t *testing.T) { + c := testMappingContainer() + old := testIPv4Rules(c) + k := &mappingKernel{rules: append([]mappingRule(nil), old...), failList: kind == "list", failInsert: kind == "insert"} + c.IP = "192.168.122.21" + if _, err := testReconcile(k, testIPv4Rules(c)); err == nil || len(k.writes) != 0 || len(k.invalidated) != 0 || !reflect.DeepEqual(k.rules, old) { + t.Fatalf("failure damaged old rules: %v %+v", err, k) + } + k.failList, k.failInsert = false, false + if _, err := testReconcile(k, testIPv4Rules(c)); err != nil || len(k.invalidated) != 2 { + t.Fatalf("retry: %v %+v", err, k) + } + for _, args := range k.invalidated { + if ruleOption(args, "--reply-src") != "192.168.122.20" { + t.Fatalf("wrong old IP: %v", args) + } + } + }) + } +} + +func TestMappingRuleKeyCanonicalizesOnlyEquivalentRules(t *testing.T) { + a := mappingRule{"filter", "FORWARD", []string{"-s", "10.0.3.2", "!", "-d", "10.0.3.0/24", "-j", "REJECT"}} + b := mappingRule{"filter", "FORWARD", []string{"-j", "REJECT", "--reject-with", "icmp-port-unreachable", "!", "-d", "10.0.3.0/24", "-s", "10.0.3.2/32"}} + if mappingRuleKey(a) != mappingRuleKey(b) { + t.Fatal("equivalent canonical representations differ") + } + b.args = []string{"-s", "10.0.3.2/32", "-d", "10.0.3.0/24", "-j", "REJECT"} + if mappingRuleKey(a) == mappingRuleKey(b) { + t.Fatal("lost negation") + } +} + +func TestIPv6MappingReconcilePreservesUnchangedConnections(t *testing.T) { + setupIPv6PortMappingTest(t, false) + c := testMappingContainer() + c.IPv6NATAddress = "fd00::2" + desired, err := ipv6MappingRules(c) + if err != nil { + t.Fatal(err) + } + k := &mappingKernel{rules: append([]mappingRule(nil), desired...)} + runIPv6PortMappingCommand = k.run + if changed, err := reconcileIPv6PortMappingsLocked(c); err != nil || changed || len(k.writes) != 0 || len(k.invalidated) != 0 { + t.Fatalf("IPv6 healthy: %v %v", changed, err) + } + c.PortMappings[1].ContainerPort = 8080 + if _, err := reconcileIPv6PortMappingsLocked(c); err != nil || len(k.invalidated) != 2 { + t.Fatalf("IPv6 change: %v %v", err, k.invalidated) + } + for _, args := range k.invalidated { + if ruleOption(args, "--dport") != "32080" || ruleOption(args, "--reply-src") != "fd00::2" || ruleOption(args, "-f") != "ipv6" { + t.Fatalf("IPv6 scope: %v", args) + } + } +} + +func TestFirewallHealthCheckDetectsLossOrderAndBroadAccepts(t *testing.T) { + c := testMappingContainer() + c.Virtualization = "kvm" + c.FirewallEnabled, c.FirewallDefaultAction = true, "DROP" + c.FirewallRules = []config.FirewallRule{{ID: "ssh", Enabled: true, Direction: "in", Protocol: "tcp", Port: "22", Action: "ACCEPT"}} + plan, err := plannedFirewallRules(c) + if err != nil { + t.Fatal(err) + } + var healthy []mappingRule + for i := len(plan) - 1; i >= 0; i-- { + if plan[i].command == "iptables" { + healthy = append(healthy, mappingRule{"filter", "FORWARD", plan[i].args[3:]}) + } + } + broad := mappingRule{"filter", "FORWARD", []string{"-o", "virbr0", "-j", "ACCEPT"}} + old := runPortMappingCommand + t.Cleanup(func() { runPortMappingCommand = old }) + for _, tc := range []struct { + name string + rules []mappingRule + want bool + }{ + {"healthy", append(append([]mappingRule(nil), healthy...), broad), true}, + {"missing_allow", healthy[1:], false}, + {"missing_all", nil, false}, + {"broad_accept_before_policy", append([]mappingRule{broad}, healthy...), false}, + {"reordered_policy", []mappingRule{healthy[1], healthy[0], healthy[2]}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + k := &mappingKernel{rules: tc.rules} + runPortMappingCommand = func(command string, args ...string) ([]byte, error) { + if command == "ip6tables" { + return nil, nil + } + return k.run(command, args...) + } + got, err := firewallRulesPresent(c, plan) + if err != nil || got != tc.want || len(k.writes) != 0 { + t.Fatalf("health=%v want=%v err=%v writes=%v", got, tc.want, err, k.writes) + } + }) + } +} + +func TestMappingRepairNeverPlacesAcceptAheadOfExistingFirewall(t *testing.T) { + k := &mappingKernel{rules: []mappingRule{{"filter", "FORWARD", []string{"-d", "fd00::2/128", "-j", "DROP", "-m", "comment", "--comment", "clicd-c12-fw-default-in"}}}} + desired := []mappingRule{{"filter", "FORWARD", []string{"-d", "fd00::2/128", "-j", "ACCEPT", "-m", "comment", "--comment", "clicd-c12-nat6-port-tcp-30080"}}} + _, err := reconcileMappingRules("ip6tables", "clicd-c12-nat6-port-", []mappingRule{{table: "filter", chain: "FORWARD"}}, desired, k.run) + if err != nil || len(k.writes) != 1 || k.writes[0][6] != "2" { + t.Fatalf("repair bypasses firewall: %v %v", err, k.writes) + } +} + +func TestBridgeRepairLeavesExistingRulesAndRespectsPolicyOrder(t *testing.T) { + old := runPortMappingCommand + t.Cleanup(func() { runPortMappingCommand = old }) + writes := 0 + runPortMappingCommand = func(_ string, args ...string) ([]byte, error) { + if ruleOption(args, "-C") != "" { + return nil, nil + } + writes++ + return nil, nil + } + ensureBridgeAcceptRule("FORWARD", []string{"-o", "virbr0", "-j", "ACCEPT"}) + if writes != 0 { + t.Fatal("healthy bridge rules were rewritten") + } + runPortMappingCommand = func(_ string, args ...string) ([]byte, error) { + if ruleOption(args, "-C") != "" { + return nil, errors.New("missing") + } + if ruleOption(args, "-S") != "" { + return []byte("-A FORWARD -d 192.168.122.20/32 -m comment --comment clicd-c12-fw-default-in -j DROP"), nil + } + writes++ + if args[4] != "2" { + t.Fatalf("bridge accept before firewall: %v", args) + } + return nil, nil + } + ensureBridgeAcceptRule("FORWARD", []string{"-o", "virbr0", "-j", "ACCEPT"}) + if writes != 1 { + t.Fatalf("repair writes=%d", writes) + } +} + +func TestAddingMappingPreservesIndependentPublicIPPassthroughPrecedence(t *testing.T) { + specific := mappingRule{"nat", "PREROUTING", []string{"-p", "tcp", "-d", "203.0.113.10", "--dport", "32080", "-j", "DNAT", "--to-destination", "10.0.3.2:80", "-m", "comment", "--comment", "clicd-c12-203_0_113_10-32080"}} + passthrough := mappingRule{"nat", "PREROUTING", []string{"-p", "tcp", "-d", "203.0.113.10", "-j", "DNAT", "--to-destination", "10.0.3.2", "-m", "comment", "--comment", "clicd-c12-203_0_113_10-all-tcp"}} + k := &mappingKernel{rules: []mappingRule{passthrough}} + if _, err := testReconcile(k, []mappingRule{specific, passthrough}); err != nil || len(k.writes) != 1 || k.writes[0][6] != "2" || len(k.invalidated) != 0 { + t.Fatalf("new mapping overrode full passthrough: %v %v", err, k.writes) + } +}