|
| 1 | +package nftables |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/lxc/incus/v6/shared/subprocess" |
| 8 | + |
| 9 | + "github.com/lxc/incus-os/incus-osd/api" |
| 10 | +) |
| 11 | + |
| 12 | +// SetupChains creates the initial system-wide chains. |
| 13 | +func SetupChains(ctx context.Context) error { |
| 14 | + // Ensure we have a bridge table. |
| 15 | + _, err := subprocess.RunCommandContext(ctx, "nft", "add", "table", "bridge", "incus-osd") |
| 16 | + if err != nil { |
| 17 | + return err |
| 18 | + } |
| 19 | + |
| 20 | + // Ensure we have a MAC filtering chain. |
| 21 | + _, err = subprocess.RunCommandContext(ctx, "nft", "add", "chain", "bridge", "incus-osd", "mac-filters", "{ type filter hook output priority 0 ; policy accept ; }") |
| 22 | + if err != nil { |
| 23 | + return err |
| 24 | + } |
| 25 | + |
| 26 | + return nil |
| 27 | +} |
| 28 | + |
| 29 | +// ApplyHwaddrFilters ensures that all interfaces with the StrictHwaddr flag set get a suitable MAC filter in place. |
| 30 | +func ApplyHwaddrFilters(ctx context.Context, networkCfg *api.SystemNetworkConfig) error { |
| 31 | + // Make sure we have the expected chains. |
| 32 | + err := SetupChains(ctx) |
| 33 | + if err != nil { |
| 34 | + return err |
| 35 | + } |
| 36 | + |
| 37 | + // Empty the chain. |
| 38 | + _, err = subprocess.RunCommandContext(ctx, "nft", "flush", "chain", "bridge", "incus-osd", "mac-filters") |
| 39 | + if err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + |
| 43 | + // Apply the filters. |
| 44 | + for _, iface := range networkCfg.Interfaces { |
| 45 | + if !iface.StrictHwaddr { |
| 46 | + continue |
| 47 | + } |
| 48 | + |
| 49 | + underlyingDevice := "_p" + strings.ToLower(strings.ReplaceAll(iface.Hwaddr, ":", "")) |
| 50 | + |
| 51 | + _, err = subprocess.RunCommandContext(ctx, "nft", "add", "rule", "bridge", "incus-osd", "mac-filters", "oif", underlyingDevice, "ether", "saddr", "!=", iface.Hwaddr, "drop") |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return nil |
| 58 | +} |
0 commit comments