nat_chain_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package firewall
  2. import (
  3. "strings"
  4. "testing"
  5. )
  6. func TestChainPlacement(t *testing.T) {
  7. cases := []struct {
  8. kind string
  9. rule any
  10. valid bool
  11. }{
  12. {"nat", NATRule{Chain: "dstnat", Action: "dst-nat"}, true},
  13. {"nat", NATRule{Chain: "prerouting", Action: "dst-nat"}, true},
  14. {"nat", NATRule{Chain: "output", Action: "dst-nat"}, true},
  15. {"nat", NATRule{Chain: "custom", Action: "dst-nat"}, true},
  16. {"nat", NATRule{Chain: "srcnat", Action: "dst-nat"}, false},
  17. {"nat", NATRule{Chain: "forward", Action: "accept"}, false},
  18. {"nat", NATRule{Chain: "srcnat", Action: "masquerade", OutInterface: "eth0"}, true},
  19. {"nat", NATRule{Chain: "input", Action: "masquerade"}, false},
  20. {"nat", NATRule{Chain: "prerouting", Action: "accept", OutInterface: "eth0"}, false},
  21. {"filter", FilterRule{Chain: "prerouting", Action: "accept"}, false},
  22. {"filter", FilterRule{Chain: "input", Action: "accept", OutInterface: "eth0"}, false},
  23. {"mangle", MangleRule{Chain: "output", Action: "accept", InInterface: "eth0"}, false},
  24. {"mangle", MangleRule{Chain: "forward", Action: "accept", InInterface: "eth0", OutInterface: "eth1"}, true},
  25. }
  26. for _, c := range cases {
  27. err := validateChainPlacement(c.kind, c.rule)
  28. if (err == nil) != c.valid {
  29. t.Errorf("%s %#v: %v", c.kind, c.rule, err)
  30. }
  31. }
  32. }
  33. func TestNATChainHooks(t *testing.T) {
  34. rules := []NATRule{{ID: "incoming", Chain: "dstnat", Action: "dst-nat", ToAddresses: "192.0.2.1"}, {ID: "local", Chain: "output", Action: "dst-nat", ToAddresses: "192.0.2.2"}, {ID: "outgoing", Chain: "srcnat", Action: "masquerade"}}
  35. payload := ownedPayload(BuildIPTablesRestore(nil, rules, nil), "")
  36. for _, want := range []string{"-A DT_nat_PREROUTING ", "-A DT_nat_OUTPUT ", "-A DT_nat_POSTROUTING ", "-I PREROUTING 1 -m comment --comment debtik:hook -j DT_nat_PREROUTING", "-I OUTPUT 1 -m comment --comment debtik:hook -j DT_nat_OUTPUT", "-I POSTROUTING 1 -m comment --comment debtik:hook -j DT_nat_POSTROUTING"} {
  37. if !strings.Contains(payload, want) {
  38. t.Errorf("missing %s", want)
  39. }
  40. }
  41. }