|
| 1 | +package nft |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "os/exec" |
| 7 | + |
| 8 | + _ "embed" |
| 9 | + |
| 10 | + "github.com/containernetworking/plugins/pkg/ns" |
| 11 | + "github.com/pkg/errors" |
| 12 | + "github.com/rs/zerolog/log" |
| 13 | + "github.com/threefoldtech/zosbase/pkg/netlight/namespace" |
| 14 | + "github.com/vishvananda/netlink" |
| 15 | +) |
| 16 | + |
| 17 | +//go:embed lansecurity.tmpl |
| 18 | +var lanSecurityTmpl string |
| 19 | + |
| 20 | +// Apply applies the ntf configuration contained in the reader r |
| 21 | +// if ns is specified, the nft command is execute in the network namespace names ns |
| 22 | +func Apply(r io.Reader, ns string) error { |
| 23 | + var cmd *exec.Cmd |
| 24 | + |
| 25 | + if ns != "" { |
| 26 | + cmd = exec.Command("ip", "netns", "exec", ns, "nft", "-f", "-") |
| 27 | + } else { |
| 28 | + cmd = exec.Command("nft", "-f", "-") |
| 29 | + } |
| 30 | + |
| 31 | + cmd.Stdin = r |
| 32 | + |
| 33 | + out, err := cmd.CombinedOutput() |
| 34 | + if err != nil { |
| 35 | + log.Error().Err(err).Str("output", string(out)).Msg("error during nft") |
| 36 | + if eerr, ok := err.(*exec.ExitError); ok { |
| 37 | + return errors.Wrapf(err, "failed to execute nft: %v", string(eerr.Stderr)) |
| 38 | + } |
| 39 | + return errors.Wrap(err, "failed to execute nft") |
| 40 | + } |
| 41 | + return nil |
| 42 | +} |
| 43 | + |
| 44 | +// DropTrafficToLAN drops all the outgoing traffic to any peers on |
| 45 | +// the same lan network, but allow dicovery port for ygg/myc by accepting |
| 46 | +// traffic to/from dest/src ports. |
| 47 | +func DropTrafficToLAN(netns string) error { |
| 48 | + var dgw netlink.Neigh |
| 49 | + |
| 50 | + toRun := func(_ ns.NetNS) error { |
| 51 | + var err error |
| 52 | + dgw, err = getDefaultGW() |
| 53 | + return err |
| 54 | + } |
| 55 | + |
| 56 | + if netns != "" { |
| 57 | + nss, err := namespace.GetByName(netns) |
| 58 | + if err != nil { |
| 59 | + return fmt.Errorf("failed to get namespace %q", netns) |
| 60 | + } |
| 61 | + defer nss.Close() |
| 62 | + |
| 63 | + if err := nss.Do(toRun); err != nil { |
| 64 | + return fmt.Errorf("failed to execute in namespace %q: %w", netns, err) |
| 65 | + } |
| 66 | + } else { |
| 67 | + if err := toRun(nil); err != nil { |
| 68 | + return fmt.Errorf("failed to get default gateway: %w", err) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if !dgw.IP.IsPrivate() { |
| 73 | + log.Warn().Msg("skip LAN security. default gateway is public") |
| 74 | + return nil |
| 75 | + } |
| 76 | + |
| 77 | + rules, err := renderRulesTemplate(lanSecurityTmpl, dgw) |
| 78 | + if err != nil { |
| 79 | + return fmt.Errorf("failed to render nft rules template: %w", err) |
| 80 | + } |
| 81 | + |
| 82 | + return Apply(rules, netns) |
| 83 | +} |
0 commit comments