mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 13:36:57 +01:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04e80f0dcf | ||
|
|
ed8ae57fee | ||
|
|
e99e48cca7 | ||
|
|
027c728702 | ||
|
|
1cfed59214 | ||
|
|
c4b9df20ac | ||
|
|
92bad7460b | ||
|
|
cac7586c0b | ||
|
|
9aab46c1ad |
No files matched your search
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Firewall rules are held as a flat list with a bitset of rule ids per port, instead of a tree of maps copied
|
||||||
|
into every port of a range. A rule like `port: 1024-65535` now costs kilobytes rather than tens of megabytes,
|
||||||
|
and matching is faster on every path.
|
||||||
|
- A firewall rule's `proto` can be `udplite`, `dccp`, `sctp`, `icmpv6`, or any IP protocol number. A rule with
|
||||||
|
a port or port range on a protocol that has no ports, such as `proto: 47`, is rejected rather than silently
|
||||||
|
never matching. `port: any` and `port: fragment` apply to every protocol.
|
||||||
|
- An ICMP non-first fragment is matched against `port: fragment` rules like a fragment of any other protocol.
|
||||||
|
It was only matched against `port: any` rules before.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- A firewall rule with `group: []`, `groups:` with no value, or a `groups` entry that isn't a string, such as
|
||||||
|
`groups: [1, 2]`, no longer crashes Nebula on startup or reload. An empty `group` array is rejected, a null
|
||||||
|
`groups` means no groups, and non-string entries are read as strings.
|
||||||
|
|
||||||
## [1.11.1] - 2026-08-21
|
## [1.11.1] - 2026-08-21
|
||||||
|
|
||||||
See the [v1.11.1](https://github.com/slackhq/nebula/milestone/30?closed=1) milestone for a complete list of changes.
|
See the [v1.11.1](https://github.com/slackhq/nebula/milestone/30?closed=1) milestone for a complete list of changes.
|
||||||
|
|||||||
+11
-20
@@ -75,23 +75,8 @@ func addRulesFromConfig(l *slog.Logger, inbound bool, c *config.C, ra ruleAdder)
|
|||||||
sPort = r.Port
|
sPort = r.Port
|
||||||
}
|
}
|
||||||
|
|
||||||
var proto uint8
|
proto, ok := protoByName(r.Proto)
|
||||||
switch r.Proto {
|
if !ok {
|
||||||
case "any":
|
|
||||||
proto = ProtoAny
|
|
||||||
case "tcp":
|
|
||||||
proto = iputil.IPProtocolTCP
|
|
||||||
case "udp":
|
|
||||||
proto = iputil.IPProtocolUDP
|
|
||||||
case "udplite":
|
|
||||||
proto = iputil.IPProtocolUDPLite
|
|
||||||
case "dccp":
|
|
||||||
proto = iputil.IPProtocolDCCP
|
|
||||||
case "sctp":
|
|
||||||
proto = iputil.IPProtocolSCTP
|
|
||||||
case "icmp":
|
|
||||||
proto = iputil.IPProtocolICMP
|
|
||||||
default:
|
|
||||||
// Any other protocol by number. 0 is reserved for `any`.
|
// Any other protocol by number. 0 is reserved for `any`.
|
||||||
n, perr := strconv.ParseUint(r.Proto, 10, 8)
|
n, perr := strconv.ParseUint(r.Proto, 10, 8)
|
||||||
if perr != nil || n == 0 {
|
if perr != nil || n == 0 {
|
||||||
@@ -99,9 +84,10 @@ func addRulesFromConfig(l *slog.Logger, inbound bool, c *config.C, ra ruleAdder)
|
|||||||
}
|
}
|
||||||
proto = uint8(n)
|
proto = uint8(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
var startPort, endPort int32
|
var startPort, endPort int32
|
||||||
if proto == iputil.IPProtocolICMP || proto == iputil.IPProtocolICMPv6 {
|
if proto == iputil.IPProtocolICMP || proto == iputil.IPProtocolICMPv6 {
|
||||||
|
// RulesBuilder.AddRule coerces ICMP ports to `any` as well. This copy stays so that an ICMP rule's
|
||||||
|
// port is warned about rather than parsed, whatever it holds.
|
||||||
startPort = PortAny
|
startPort = PortAny
|
||||||
endPort = PortAny
|
endPort = PortAny
|
||||||
if sPort != "" {
|
if sPort != "" {
|
||||||
@@ -173,6 +159,9 @@ func yamlToConfigRule(l *slog.Logger, p any, table string, i int) (configRule, e
|
|||||||
if len(v) > 1 {
|
if len(v) > 1 {
|
||||||
return r, errors.New("group should contain a single value, an array with more than one entry was provided")
|
return r, errors.New("group should contain a single value, an array with more than one entry was provided")
|
||||||
}
|
}
|
||||||
|
if len(v) == 0 {
|
||||||
|
return r, errors.New("group should contain a single value, an empty array was provided")
|
||||||
|
}
|
||||||
|
|
||||||
l.Warn("group was an array with a single value, converting to simple value",
|
l.Warn("group was an array with a single value, converting to simple value",
|
||||||
"table", table,
|
"table", table,
|
||||||
@@ -183,13 +172,15 @@ func yamlToConfigRule(l *slog.Logger, p any, table string, i int) (configRule, e
|
|||||||
|
|
||||||
singleGroup := toString("group", m)
|
singleGroup := toString("group", m)
|
||||||
|
|
||||||
if rg, ok := m["groups"]; ok {
|
// A null value, `groups:` with nothing after it, is the same as no groups
|
||||||
|
if rg, ok := m["groups"]; ok && rg != nil {
|
||||||
switch reflect.TypeOf(rg).Kind() {
|
switch reflect.TypeOf(rg).Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
|
// Every entry is read as a string, as the other fields are, so `groups: [1, 2]` is the groups "1" and "2"
|
||||||
v := reflect.ValueOf(rg)
|
v := reflect.ValueOf(rg)
|
||||||
r.Groups = make([]string, v.Len())
|
r.Groups = make([]string, v.Len())
|
||||||
for i := 0; i < v.Len(); i++ {
|
for i := 0; i < v.Len(); i++ {
|
||||||
r.Groups[i] = v.Index(i).Interface().(string)
|
r.Groups[i] = fmt.Sprintf("%v", v.Index(i).Interface())
|
||||||
}
|
}
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
r.Groups = []string{rg.(string)}
|
r.Groups = []string{rg.(string)}
|
||||||
|
|||||||
+57
-18
@@ -170,13 +170,21 @@ func TestAddRulesFromConfig(t *testing.T) {
|
|||||||
assert.Equal(t, addRuleCall{incoming: false, proto: 47, startPort: PortAny, endPort: PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall, proto)
|
assert.Equal(t, addRuleCall{incoming: false, proto: 47, startPort: PortAny, endPort: PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall, proto)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test ICMP and ICMPv6 by number still ignore ports
|
// Test ICMP and ICMPv6, by name and by number, still ignore ports
|
||||||
for _, proto := range []uint8{iputil.IPProtocolICMP, iputil.IPProtocolICMPv6} {
|
for _, tc := range []struct {
|
||||||
|
given any
|
||||||
|
want uint8
|
||||||
|
}{
|
||||||
|
{"icmp", iputil.IPProtocolICMP},
|
||||||
|
{"icmpv6", iputil.IPProtocolICMPv6},
|
||||||
|
{iputil.IPProtocolICMP, iputil.IPProtocolICMP},
|
||||||
|
{iputil.IPProtocolICMPv6, iputil.IPProtocolICMPv6},
|
||||||
|
} {
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
mf = &mockFirewall{}
|
mf = &mockFirewall{}
|
||||||
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": proto, "host": "a"}}}
|
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": tc.given, "host": "a"}}}
|
||||||
require.NoError(t, addRulesFromConfig(l, false, conf, mf), proto)
|
require.NoError(t, addRulesFromConfig(l, false, conf, mf), tc.given)
|
||||||
assert.Equal(t, addRuleCall{incoming: false, proto: proto, startPort: PortAny, endPort: PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall, proto)
|
assert.Equal(t, addRuleCall{incoming: false, proto: tc.want, startPort: PortAny, endPort: PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall, tc.given)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test protocols that aren't a known name or a number from 1 to 255
|
// Test protocols that aren't a known name or a number from 1 to 255
|
||||||
@@ -283,6 +291,26 @@ func TestAddRulesFromConfig(t *testing.T) {
|
|||||||
require.NoError(t, addRulesFromConfig(l, true, conf, mf))
|
require.NoError(t, addRulesFromConfig(l, true, conf, mf))
|
||||||
assert.Equal(t, addRuleCall{incoming: true, proto: ProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: true, proto: ProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: "", localIp: ""}, mf.lastCall)
|
||||||
|
|
||||||
|
// Test group and groups values that used to crash: an empty group array is rejected, groups entries that
|
||||||
|
// aren't strings are read as strings, and a null groups is no groups
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": []any{}}}}
|
||||||
|
require.EqualError(t, addRulesFromConfig(l, true, conf, mf), "firewall.inbound rule #0; group should contain a single value, an empty array was provided")
|
||||||
|
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": []any{1, 2}}}}
|
||||||
|
require.NoError(t, addRulesFromConfig(l, true, conf, mf))
|
||||||
|
assert.Equal(t, []string{"1", "2"}, mf.lastCall.groups)
|
||||||
|
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": nil, "host": "a"}}}
|
||||||
|
require.NoError(t, addRulesFromConfig(l, true, conf, mf))
|
||||||
|
assert.Empty(t, mf.lastCall.groups)
|
||||||
|
assert.Equal(t, "a", mf.lastCall.host)
|
||||||
|
|
||||||
// Test Add error
|
// Test Add error
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
mf = &mockFirewall{}
|
mf = &mockFirewall{}
|
||||||
@@ -299,8 +327,17 @@ func TestRulesFromConfig_defaultLocalCIDR(t *testing.T) {
|
|||||||
vpnAddr := netip.MustParseAddr("10.1.9.9")
|
vpnAddr := netip.MustParseAddr("10.1.9.9")
|
||||||
unsafeAddr := netip.MustParseAddr("192.168.0.3")
|
unsafeAddr := netip.MustParseAddr("192.168.0.3")
|
||||||
|
|
||||||
allows := func(lr *localRules, addr netip.Addr) bool {
|
// ruleOnPort returns the rule on proto whose port clause is exactly port, chosen from the rules that a packet
|
||||||
return lr.match(&Packet{LocalAddr: addr}, nil)
|
// on port is checked against.
|
||||||
|
ruleOnPort := func(t *testing.T, table *Table, proto uint8, port int32) *rule {
|
||||||
|
t.Helper()
|
||||||
|
for _, r := range table.rulesAt(proto, port) {
|
||||||
|
if r.startPort == port {
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.Failf(t, "no rule found", "proto %d port %d", proto, port)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
@@ -327,22 +364,24 @@ func TestRulesFromConfig_defaultLocalCIDR(t *testing.T) {
|
|||||||
rules, err := RulesFromConfig(test.NewLogger(), conf, vpnNetworks, tc.unsafeNetworks)
|
rules, err := RulesFromConfig(test.NewLogger(), conf, vpnNetworks, tc.unsafeNetworks)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// The proto `any` rule, copied into a protocol with rules of its own and shared by one without
|
// The proto `any` rule, as indexed by a protocol with rules of its own and as shared by one without.
|
||||||
for _, proto := range []uint8{iputil.IPProtocolTCP, 47} {
|
for _, proto := range []uint8{iputil.IPProtocolTCP, 47} {
|
||||||
lr := rules.In.protos[proto][PortAny].Any.Any
|
r := ruleOnPort(t, rules.In, proto, PortAny)
|
||||||
assert.True(t, allows(lr, vpnAddr), "proto %d", proto)
|
assert.True(t, r.matchLocal(vpnAddr), "proto %d", proto)
|
||||||
assert.Equal(t, tc.wantUnsafe, allows(lr, unsafeAddr), "proto %d", proto)
|
assert.Equal(t, tc.wantUnsafe, r.matchLocal(unsafeAddr), "proto %d", proto)
|
||||||
}
|
}
|
||||||
|
|
||||||
tcp := rules.In.protos[iputil.IPProtocolTCP]
|
r := ruleOnPort(t, rules.In, iputil.IPProtocolTCP, 22)
|
||||||
assert.True(t, allows(tcp[22].Any.Any, vpnAddr))
|
assert.True(t, r.matchLocal(vpnAddr))
|
||||||
assert.Equal(t, tc.wantUnsafe, allows(tcp[22].Any.Any, unsafeAddr))
|
assert.Equal(t, tc.wantUnsafe, r.matchLocal(unsafeAddr))
|
||||||
|
|
||||||
assert.False(t, allows(tcp[80].Any.Any, vpnAddr))
|
r = ruleOnPort(t, rules.In, iputil.IPProtocolTCP, 80)
|
||||||
assert.True(t, allows(tcp[80].Any.Any, unsafeAddr))
|
assert.False(t, r.matchLocal(vpnAddr))
|
||||||
|
assert.True(t, r.matchLocal(unsafeAddr))
|
||||||
|
|
||||||
assert.True(t, allows(tcp[443].Any.Any, vpnAddr))
|
r = ruleOnPort(t, rules.In, iputil.IPProtocolTCP, 443)
|
||||||
assert.True(t, allows(tcp[443].Any.Any, unsafeAddr))
|
assert.True(t, r.matchLocal(vpnAddr))
|
||||||
|
assert.True(t, r.matchLocal(unsafeAddr))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+40
-20
@@ -40,35 +40,55 @@ func (fp *Packet) Copy() *Packet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (fp Packet) MarshalJSON() ([]byte, error) {
|
func (fp Packet) MarshalJSON() ([]byte, error) {
|
||||||
var proto string
|
|
||||||
switch fp.Protocol {
|
|
||||||
case iputil.IPProtocolTCP:
|
|
||||||
proto = "tcp"
|
|
||||||
case iputil.IPProtocolICMP:
|
|
||||||
proto = "icmp"
|
|
||||||
case iputil.IPProtocolICMPv6:
|
|
||||||
proto = "icmpv6"
|
|
||||||
case iputil.IPProtocolUDP:
|
|
||||||
proto = "udp"
|
|
||||||
case iputil.IPProtocolUDPLite:
|
|
||||||
proto = "udplite"
|
|
||||||
case iputil.IPProtocolDCCP:
|
|
||||||
proto = "dccp"
|
|
||||||
case iputil.IPProtocolSCTP:
|
|
||||||
proto = "sctp"
|
|
||||||
default:
|
|
||||||
proto = fmt.Sprintf("unknown %v", fp.Protocol)
|
|
||||||
}
|
|
||||||
return json.Marshal(m{
|
return json.Marshal(m{
|
||||||
"LocalAddr": fp.LocalAddr.String(),
|
"LocalAddr": fp.LocalAddr.String(),
|
||||||
"RemoteAddr": fp.RemoteAddr.String(),
|
"RemoteAddr": fp.RemoteAddr.String(),
|
||||||
"LocalPort": fp.LocalPort,
|
"LocalPort": fp.LocalPort,
|
||||||
"RemotePort": fp.RemotePort,
|
"RemotePort": fp.RemotePort,
|
||||||
"Protocol": proto,
|
"Protocol": protoName(fp.Protocol),
|
||||||
"Fragment": fp.Fragment,
|
"Fragment": fp.Fragment,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// protoNames are the protocol names that rules accept and packets report, and their numbers. Any other protocol
|
||||||
|
// is given by number.
|
||||||
|
var protoNames = []struct {
|
||||||
|
name string
|
||||||
|
proto uint8
|
||||||
|
}{
|
||||||
|
{"any", ProtoAny},
|
||||||
|
{"tcp", iputil.IPProtocolTCP},
|
||||||
|
{"udp", iputil.IPProtocolUDP},
|
||||||
|
{"udplite", iputil.IPProtocolUDPLite},
|
||||||
|
{"dccp", iputil.IPProtocolDCCP},
|
||||||
|
{"sctp", iputil.IPProtocolSCTP},
|
||||||
|
{"icmp", iputil.IPProtocolICMP},
|
||||||
|
{"icmpv6", iputil.IPProtocolICMPv6},
|
||||||
|
}
|
||||||
|
|
||||||
|
// protoByName returns the number of a protocol named in protoNames.
|
||||||
|
func protoByName(name string) (uint8, bool) {
|
||||||
|
for _, p := range protoNames {
|
||||||
|
if p.name == name {
|
||||||
|
return p.proto, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// protoName returns the name in protoNames of a packet's protocol, or "unknown" and its number. `any` is only
|
||||||
|
// a rule's protocol, so a packet's protocol 0 is unknown.
|
||||||
|
func protoName(proto uint8) string {
|
||||||
|
if proto != ProtoAny {
|
||||||
|
for _, p := range protoNames {
|
||||||
|
if p.proto == proto {
|
||||||
|
return p.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("unknown %v", proto)
|
||||||
|
}
|
||||||
|
|
||||||
// ParsedPacket is a Packet plus the parse byproducts the RX path reuses
|
// ParsedPacket is a Packet plus the parse byproducts the RX path reuses
|
||||||
type ParsedPacket struct {
|
type ParsedPacket struct {
|
||||||
Packet
|
Packet
|
||||||
|
|||||||
+124
-196
@@ -4,68 +4,43 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash"
|
|
||||||
"hash/fnv"
|
"hash/fnv"
|
||||||
"io"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"math"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"slices"
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
|
||||||
"github.com/slackhq/nebula/iputil"
|
"github.com/slackhq/nebula/iputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RulesBuilder collects the inbound and outbound rules, Build turns them into a Table for each direction
|
// RulesBuilder collects the inbound and outbound rules, Build turns them into a Table for each direction
|
||||||
type RulesBuilder struct {
|
type RulesBuilder struct {
|
||||||
in, out tableRules
|
// in and out are each direction's rules in the order they were added
|
||||||
|
in, out []rule
|
||||||
|
|
||||||
// defaultLocalCIDRAny makes rules without a local cidr allow any local address, even with unsafe networks
|
// defaultLocalCIDRAny makes rules without a local cidr allow any local address, even with unsafe networks
|
||||||
defaultLocalCIDRAny bool
|
defaultLocalCIDRAny bool
|
||||||
|
|
||||||
// ruleSHA and ruleFNV hash every rule as it's added, see Rules
|
// ruleText describes every rule as it is added, one line each. Build hashes it; see Rules.
|
||||||
ruleSHA hash.Hash
|
ruleText strings.Builder
|
||||||
ruleFNV hash.Hash32
|
|
||||||
|
|
||||||
l *slog.Logger
|
l *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
// tableRules are one direction's rules, waiting to be built into a Table
|
|
||||||
type tableRules struct {
|
|
||||||
anyRules []rule
|
|
||||||
// protoRules holds the rules for each protocol besides proto `any`, ICMPv6 rules are kept with ICMP
|
|
||||||
protoRules [256][]rule
|
|
||||||
}
|
|
||||||
|
|
||||||
// rule is a parsed rule, so adding it to a Table can't fail
|
|
||||||
type rule struct {
|
|
||||||
startPort, endPort int32
|
|
||||||
groups []string
|
|
||||||
host string
|
|
||||||
caName, caSha string
|
|
||||||
|
|
||||||
// cidr is the remote cidr, not valid when the rule doesn't have one
|
|
||||||
cidr netip.Prefix
|
|
||||||
anyCIDR bool
|
|
||||||
|
|
||||||
// localCIDR is the local addresses the rule allows, anyLocalCIDR allows all of them.
|
|
||||||
// Neither is set for a rule without a local cidr until the Table is built and it gets the default.
|
|
||||||
// localCIDR is shared by every localRules the rule is added to, so it's never changed, see localRules.add
|
|
||||||
localCIDR *bart.Lite
|
|
||||||
anyLocalCIDR bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRulesBuilder(l *slog.Logger) *RulesBuilder {
|
func NewRulesBuilder(l *slog.Logger) *RulesBuilder {
|
||||||
return &RulesBuilder{
|
return &RulesBuilder{l: l}
|
||||||
ruleSHA: sha256.New(),
|
|
||||||
ruleFNV: fnv.New32a(),
|
|
||||||
l: l,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddRule adds a rule for incoming or outgoing traffic, on proto or on every protocol when proto is ProtoAny.
|
// AddRule adds a rule for incoming or outgoing traffic, on proto or on every protocol when proto is ProtoAny.
|
||||||
// The rule is parsed now, so a bad rule is reported when it's added rather than when the Tables are built.
|
// The rule is parsed now, so a bad rule is reported when it's added rather than when the Tables are built.
|
||||||
func (b *RulesBuilder) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
|
func (b *RulesBuilder) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
|
||||||
if proto == iputil.IPProtocolICMP || proto == iputil.IPProtocolICMPv6 {
|
// ICMPv6 rules are ICMP rules, and a packet of either protocol is checked against both
|
||||||
|
if proto == iputil.IPProtocolICMPv6 {
|
||||||
|
proto = iputil.IPProtocolICMP
|
||||||
|
}
|
||||||
|
|
||||||
|
if proto == iputil.IPProtocolICMP {
|
||||||
//ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
|
//ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
|
||||||
if startPort != PortAny {
|
if startPort != PortAny {
|
||||||
b.l.Warn("ignoring port specification for ICMP firewall rule", "startPort", startPort)
|
b.l.Warn("ignoring port specification for ICMP firewall rule", "startPort", startPort)
|
||||||
@@ -74,19 +49,19 @@ func (b *RulesBuilder) AddRule(incoming bool, proto uint8, startPort int32, endP
|
|||||||
endPort = PortAny
|
endPort = PortAny
|
||||||
}
|
}
|
||||||
|
|
||||||
r, err := parseRule(startPort, endPort, groups, host, cidr, localCidr, caName, caSha)
|
r, err := parseRule(proto, startPort, endPort, groups, host, cidr, localCidr, caName, caSha)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if incoming {
|
if incoming {
|
||||||
b.in.add(proto, r)
|
b.in = append(b.in, r)
|
||||||
} else {
|
} else {
|
||||||
b.out.add(proto, r)
|
b.out = append(b.out, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The rule hashes are of these lines, changing them changes every hash
|
// The rule hashes are of these lines, changing them changes every hash
|
||||||
fmt.Fprintf(io.MultiWriter(b.ruleSHA, b.ruleFNV),
|
fmt.Fprintf(&b.ruleText,
|
||||||
"incoming: %v, proto: %v, startPort: %v, endPort: %v, groups: %v, host: %v, ip: %v, localIp: %v, caName: %v, caSha: %s\n",
|
"incoming: %v, proto: %v, startPort: %v, endPort: %v, groups: %v, host: %v, ip: %v, localIp: %v, caName: %v, caSha: %s\n",
|
||||||
incoming, proto, startPort, endPort, groups, host, cidr, localCidr, caName, caSha,
|
incoming, proto, startPort, endPort, groups, host, cidr, localCidr, caName, caSha,
|
||||||
)
|
)
|
||||||
@@ -105,28 +80,44 @@ func (b *RulesBuilder) AddRule(incoming bool, proto uint8, startPort int32, endP
|
|||||||
// Build turns the rules into a Table for each direction, and hashes them. Rules without a local cidr allow
|
// Build turns the rules into a Table for each direction, and hashes them. Rules without a local cidr allow
|
||||||
// vpnNetworks when there are unsafe networks, otherwise any local address.
|
// vpnNetworks when there are unsafe networks, otherwise any local address.
|
||||||
func (b *RulesBuilder) Build(vpnNetworks, unsafeNetworks []netip.Prefix) Rules {
|
func (b *RulesBuilder) Build(vpnNetworks, unsafeNetworks []netip.Prefix) Rules {
|
||||||
var defaultLocal *bart.Lite
|
var defaultLocal []netip.Prefix
|
||||||
if len(unsafeNetworks) > 0 && !b.defaultLocalCIDRAny {
|
if len(unsafeNetworks) > 0 && !b.defaultLocalCIDRAny {
|
||||||
defaultLocal = new(bart.Lite)
|
// Never nil, even when there are no vpn networks, so that the rules allow nothing rather than everything.
|
||||||
for _, network := range vpnNetworks {
|
defaultLocal = append([]netip.Prefix{}, vpnNetworks...)
|
||||||
defaultLocal.Insert(network)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
text := []byte(b.ruleText.String())
|
||||||
|
sha := sha256.Sum256(text)
|
||||||
|
h := fnv.New32a()
|
||||||
|
h.Write(text)
|
||||||
|
|
||||||
return Rules{
|
return Rules{
|
||||||
In: b.in.build(defaultLocal),
|
In: buildTable(b.in, defaultLocal),
|
||||||
Out: b.out.build(defaultLocal),
|
Out: buildTable(b.out, defaultLocal),
|
||||||
Hash: hex.EncodeToString(b.ruleSHA.Sum(nil)),
|
Hash: hex.EncodeToString(sha[:]),
|
||||||
HashFNV: b.ruleFNV.Sum32(),
|
HashFNV: h.Sum32(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRule(startPort, endPort int32, groups []string, host, cidr, localCidr, caName, caSha string) (rule, error) {
|
func parseRule(proto uint8, startPort, endPort int32, groups []string, host, cidr, localCidr, caName, caSha string) (rule, error) {
|
||||||
if startPort > endPort {
|
if startPort > endPort {
|
||||||
return rule{}, fmt.Errorf("start port was lower than end port")
|
return rule{}, fmt.Errorf("start port was lower than end port")
|
||||||
}
|
}
|
||||||
|
if startPort < PortFragment || endPort > math.MaxUint16 {
|
||||||
|
return rule{}, fmt.Errorf("port range %d-%d is outside of %d-%d", startPort, endPort, PortFragment, math.MaxUint16)
|
||||||
|
}
|
||||||
|
// A range that includes port 0 is port `any`.
|
||||||
|
if startPort <= PortAny && PortAny <= endPort {
|
||||||
|
startPort, endPort = PortAny, PortAny
|
||||||
|
}
|
||||||
|
// A port rule on a protocol without ports could never match. ICMP rules were coerced to `any` by AddRule,
|
||||||
|
// and a proto `any` rule with a port applies to the protocols that have them.
|
||||||
|
if startPort > PortAny && proto != ProtoAny && !iputil.HasPorts(proto) {
|
||||||
|
return rule{}, fmt.Errorf("protocol %d has no ports, port must be any or fragment", proto)
|
||||||
|
}
|
||||||
|
|
||||||
r := rule{
|
r := rule{
|
||||||
|
proto: proto,
|
||||||
startPort: startPort,
|
startPort: startPort,
|
||||||
endPort: endPort,
|
endPort: endPort,
|
||||||
groups: groups,
|
groups: groups,
|
||||||
@@ -135,73 +126,112 @@ func parseRule(startPort, endPort int32, groups []string, host, cidr, localCidr,
|
|||||||
caSha: caSha,
|
caSha: caSha,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var anyCIDR bool
|
||||||
var err error
|
var err error
|
||||||
r.cidr, r.anyCIDR, err = parseCIDR(cidr)
|
r.cidr, anyCIDR, err = parseCIDR(cidr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return rule{}, fmt.Errorf("cidr did not parse; %w", err)
|
return rule{}, fmt.Errorf("cidr did not parse; %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A rule with no group, host, or cidr allows any host, as does a rule with `any` for one of them.
|
||||||
|
r.remoteAny = anyCIDR || host == "any" || slices.Contains(groups, "any") ||
|
||||||
|
(len(groups) == 0 && host == "" && !r.cidr.IsValid())
|
||||||
|
|
||||||
var localCIDR netip.Prefix
|
var localCIDR netip.Prefix
|
||||||
localCIDR, r.anyLocalCIDR, err = parseCIDR(localCidr)
|
localCIDR, r.localAny, err = parseCIDR(localCidr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return rule{}, fmt.Errorf("local_cidr did not parse; %w", err)
|
return rule{}, fmt.Errorf("local_cidr did not parse; %w", err)
|
||||||
}
|
}
|
||||||
if localCIDR.IsValid() {
|
if localCIDR.IsValid() {
|
||||||
r.localCIDR = new(bart.Lite)
|
r.local = []netip.Prefix{localCIDR}
|
||||||
r.localCIDR.Insert(localCIDR)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return r, nil
|
return r, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// add keeps r for proto, or for every protocol when proto is ProtoAny
|
// buildTable turns one direction's rules into a Table. Rules without a local cidr allow defaultLocal,
|
||||||
func (tr *tableRules) add(proto uint8, r rule) {
|
|
||||||
switch proto {
|
|
||||||
case ProtoAny:
|
|
||||||
tr.anyRules = append(tr.anyRules, r)
|
|
||||||
case iputil.IPProtocolICMPv6:
|
|
||||||
tr.protoRules[iputil.IPProtocolICMP] = append(tr.protoRules[iputil.IPProtocolICMP], r)
|
|
||||||
default:
|
|
||||||
tr.protoRules[proto] = append(tr.protoRules[proto], r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// build turns the rules into a Table. Rules without a local cidr allow defaultLocal,
|
|
||||||
// or any local address when defaultLocal is nil.
|
// or any local address when defaultLocal is nil.
|
||||||
func (tr *tableRules) build(defaultLocal *bart.Lite) *Table {
|
func buildTable(rules []rule, defaultLocal []netip.Prefix) *Table {
|
||||||
t := &Table{}
|
t := &Table{rules: make([]rule, len(rules))}
|
||||||
|
var hasOwn [256]bool
|
||||||
|
for id, r := range rules {
|
||||||
|
t.rules[id] = r.withDefaultLocal(defaultLocal)
|
||||||
|
if r.proto != ProtoAny {
|
||||||
|
hasOwn[r.proto] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Every protocol starts out sharing the proto `any` rules, including protos[ProtoAny]
|
// A protocol with rules of its own gets an index of those rules plus the proto `any` rules, so a packet
|
||||||
anyProto := newPortRules(defaultLocal, tr.anyRules)
|
// checks a single index. The other protocols share an index of the proto `any` rules, one for protocols with
|
||||||
|
// ports and one for protocols without.
|
||||||
|
anyPorts := newProtoIndex(true, t.rules, ProtoAny)
|
||||||
|
anyNoPorts := newProtoIndex(false, t.rules, ProtoAny)
|
||||||
for proto := range t.protos {
|
for proto := range t.protos {
|
||||||
t.protos[proto] = anyProto
|
switch {
|
||||||
}
|
case hasOwn[proto]:
|
||||||
|
t.protos[proto] = newProtoIndex(iputil.HasPorts(uint8(proto)), t.rules, uint8(proto))
|
||||||
// Protocols with rules of their own get a copy of the proto `any` rules too, so a packet only checks one set
|
case iputil.HasPorts(uint8(proto)):
|
||||||
for proto, rules := range tr.protoRules {
|
t.protos[proto] = anyPorts
|
||||||
if len(rules) > 0 {
|
default:
|
||||||
t.protos[proto] = newPortRules(defaultLocal, tr.anyRules, rules)
|
t.protos[proto] = anyNoPorts
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ICMP and ICMPv6 share one set of rules, add keeps them together under ICMP
|
// ICMPv6 rules are ICMP rules, see AddRule, so ICMPv6 packets are checked against the ICMP index
|
||||||
t.protos[iputil.IPProtocolICMPv6] = t.protos[iputil.IPProtocolICMP]
|
t.protos[iputil.IPProtocolICMPv6] = t.protos[iputil.IPProtocolICMP]
|
||||||
|
|
||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
// newPortRules builds portRules from each set of rules, or returns nil when there are none
|
// newProtoIndex builds an index of the proto `any` rules and proto's own rules, for a protocol with or without
|
||||||
func newPortRules(defaultLocal *bart.Lite, ruleSets ...[]rule) portRules {
|
// ports, or returns nil when there are none. With ProtoAny, it indexes only the proto `any` rules.
|
||||||
var pr portRules
|
func newProtoIndex(hasPorts bool, rules []rule, proto uint8) *protoIndex {
|
||||||
for _, rules := range ruleSets {
|
var pi *protoIndex
|
||||||
for _, r := range rules {
|
for id := range rules {
|
||||||
if pr == nil {
|
r := &rules[id]
|
||||||
pr = portRules{}
|
if r.proto != ProtoAny && r.proto != proto {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
pr.add(r.withDefaultLocal(defaultLocal))
|
|
||||||
|
if pi == nil {
|
||||||
|
pi = &protoIndex{hasPorts: hasPorts, fragment: newRuleSet(len(rules))}
|
||||||
|
if hasPorts {
|
||||||
|
pi.byPort = newRuleSets(math.MaxUint16+1, len(rules))
|
||||||
|
} else {
|
||||||
|
pi.packet = newRuleSet(len(rules))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return pr
|
pi.add(r, id)
|
||||||
|
}
|
||||||
|
return pi
|
||||||
|
}
|
||||||
|
|
||||||
|
// add puts id in every set that r's port clause covers.
|
||||||
|
func (pi *protoIndex) add(r *rule, id int) {
|
||||||
|
switch r.startPort {
|
||||||
|
case PortAny:
|
||||||
|
pi.fragment.add(id)
|
||||||
|
if pi.hasPorts {
|
||||||
|
pi.addPorts(0, math.MaxUint16, id)
|
||||||
|
} else {
|
||||||
|
pi.packet.add(id)
|
||||||
|
}
|
||||||
|
case PortFragment:
|
||||||
|
pi.fragment.add(id)
|
||||||
|
default:
|
||||||
|
// A proto `any` rule with a port is indexed for the protocols that have ports, parseRule rejects a port on
|
||||||
|
// a protocol without them.
|
||||||
|
if pi.hasPorts {
|
||||||
|
pi.addPorts(int(r.startPort), int(r.endPort), id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// addPorts puts id in the set of every port from lo through hi.
|
||||||
|
func (pi *protoIndex) addPorts(lo, hi, id int) {
|
||||||
|
for port := lo; port <= hi; port++ {
|
||||||
|
pi.byPort.at(port).add(id)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseCIDR parses a rule's cidr, which is empty, `any`, or a prefix
|
// parseCIDR parses a rule's cidr, which is empty, `any`, or a prefix
|
||||||
@@ -217,114 +247,12 @@ func parseCIDR(s string) (prefix netip.Prefix, isAny bool, err error) {
|
|||||||
return prefix, false, err
|
return prefix, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// isAny reports whether r matches any host, making its groups, host, and cidr irrelevant
|
|
||||||
func (r rule) isAny() bool {
|
|
||||||
if len(r.groups) == 0 && r.host == "" && !r.cidr.IsValid() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return slices.Contains(r.groups, "any") || r.host == "any" || r.anyCIDR
|
|
||||||
}
|
|
||||||
|
|
||||||
// withDefaultLocal returns r allowing defaultLocal, or any local address when defaultLocal is nil,
|
// withDefaultLocal returns r allowing defaultLocal, or any local address when defaultLocal is nil,
|
||||||
// unless r has a local cidr of its own
|
// unless r has a local cidr of its own
|
||||||
func (r rule) withDefaultLocal(defaultLocal *bart.Lite) rule {
|
func (r rule) withDefaultLocal(defaultLocal []netip.Prefix) rule {
|
||||||
if !r.anyLocalCIDR && r.localCIDR == nil {
|
if !r.localAny && r.local == nil {
|
||||||
r.anyLocalCIDR = defaultLocal == nil
|
r.localAny = defaultLocal == nil
|
||||||
r.localCIDR = defaultLocal
|
r.local = defaultLocal
|
||||||
}
|
}
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pr portRules) add(r rule) {
|
|
||||||
for i := r.startPort; i <= r.endPort; i++ {
|
|
||||||
cr := pr[i]
|
|
||||||
if cr == nil {
|
|
||||||
cr = &caRules{}
|
|
||||||
pr[i] = cr
|
|
||||||
}
|
|
||||||
cr.add(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cr *caRules) add(r rule) {
|
|
||||||
if r.caSha == "" && r.caName == "" {
|
|
||||||
if cr.Any == nil {
|
|
||||||
cr.Any = &remoteRules{}
|
|
||||||
}
|
|
||||||
cr.Any.add(r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.caSha != "" {
|
|
||||||
getOrNew(&cr.CAShas, r.caSha).add(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.caName != "" {
|
|
||||||
getOrNew(&cr.CANames, r.caName).add(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rr *remoteRules) add(r rule) {
|
|
||||||
if r.isAny() {
|
|
||||||
if rr.Any == nil {
|
|
||||||
rr.Any = &localRules{}
|
|
||||||
}
|
|
||||||
rr.Any.add(r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(r.groups) > 0 {
|
|
||||||
lr := &localRules{}
|
|
||||||
lr.add(r)
|
|
||||||
rr.Groups = append(rr.Groups, &groupsRule{
|
|
||||||
Groups: r.groups,
|
|
||||||
LocalCIDR: lr,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.host != "" {
|
|
||||||
getOrNew(&rr.Hosts, r.host).add(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.cidr.IsValid() {
|
|
||||||
if rr.CIDR == nil {
|
|
||||||
rr.CIDR = new(bart.Table[*localRules])
|
|
||||||
}
|
|
||||||
lr, ok := rr.CIDR.Get(r.cidr)
|
|
||||||
if !ok {
|
|
||||||
lr = &localRules{}
|
|
||||||
rr.CIDR.Insert(r.cidr, lr)
|
|
||||||
}
|
|
||||||
lr.add(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lr *localRules) add(r rule) {
|
|
||||||
if r.anyLocalCIDR {
|
|
||||||
lr.Any = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Share the rule's local cidrs until another rule's need adding, then copy them instead of changing them
|
|
||||||
if lr.LocalCIDR == nil {
|
|
||||||
lr.LocalCIDR = r.localCIDR
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for prefix := range r.localCIDR.All() {
|
|
||||||
lr.LocalCIDR = lr.LocalCIDR.InsertPersist(prefix)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// getOrNew returns m[k], adding a new value for k first when there isn't one. m is made if it's nil.
|
|
||||||
func getOrNew[M ~map[K]*V, K comparable, V any](m *M, k K) *V {
|
|
||||||
if *m == nil {
|
|
||||||
*m = make(M)
|
|
||||||
}
|
|
||||||
v := (*m)[k]
|
|
||||||
if v == nil {
|
|
||||||
v = new(V)
|
|
||||||
(*m)[k] = v
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
+204
-76
@@ -1,160 +1,198 @@
|
|||||||
package firewall
|
package firewall
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/cert"
|
||||||
|
"github.com/slackhq/nebula/cert_test"
|
||||||
"github.com/slackhq/nebula/iputil"
|
"github.com/slackhq/nebula/iputil"
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// rulesAt returns the rules that a packet on proto with the given port is checked against, in id order.
|
||||||
|
// port may also be PortAny or PortFragment.
|
||||||
|
func (t *Table) rulesAt(proto uint8, port int32) []*rule {
|
||||||
|
pi := t.protos[proto]
|
||||||
|
if pi == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p := &Packet{Protocol: proto, Fragment: port == PortFragment}
|
||||||
|
if port > 0 {
|
||||||
|
p.LocalPort = uint16(port)
|
||||||
|
}
|
||||||
|
|
||||||
|
var rules []*rule
|
||||||
|
for id := range pi.whichMatch(p, true).all() {
|
||||||
|
rules = append(rules, &t.rules[id])
|
||||||
|
}
|
||||||
|
return rules
|
||||||
|
}
|
||||||
|
|
||||||
|
// oneRuleAt returns the single rule that rulesAt finds, and fails the test when there is not exactly one.
|
||||||
|
func oneRuleAt(t *testing.T, table *Table, proto uint8, key int32) *rule {
|
||||||
|
t.Helper()
|
||||||
|
rules := table.rulesAt(proto, key)
|
||||||
|
require.Len(t, rules, 1)
|
||||||
|
return rules[0]
|
||||||
|
}
|
||||||
|
|
||||||
func TestRulesBuilder_AddRule(t *testing.T) {
|
func TestRulesBuilder_AddRule(t *testing.T) {
|
||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
|
|
||||||
ti, err := netip.ParsePrefix("1.2.3.4/32")
|
ti := netip.MustParsePrefix("1.2.3.4/32")
|
||||||
require.NoError(t, err)
|
ti6 := netip.MustParsePrefix("fd12::34/128")
|
||||||
|
|
||||||
ti6, err := netip.ParsePrefix("fd12::34/128")
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
rb := NewRulesBuilder(l)
|
rb := NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 1, 1, []string{}, "", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 1, 1, []string{}, "", "", "", "", ""))
|
||||||
rules := rb.Build(nil, nil)
|
rules := rb.Build(nil, nil)
|
||||||
// An empty rule is any
|
// An empty rule is any
|
||||||
assert.True(t, rules.In.protos[iputil.IPProtocolTCP][1].Any.Any.Any)
|
r := oneRuleAt(t, rules.In, iputil.IPProtocolTCP, 1)
|
||||||
assert.Empty(t, rules.In.protos[iputil.IPProtocolTCP][1].Any.Groups)
|
assert.True(t, r.remoteAny)
|
||||||
assert.Empty(t, rules.In.protos[iputil.IPProtocolTCP][1].Any.Hosts)
|
assert.Empty(t, r.groups)
|
||||||
|
assert.Empty(t, r.host)
|
||||||
|
// It applies only to its own port.
|
||||||
|
assert.Empty(t, rules.In.rulesAt(iputil.IPProtocolTCP, 2))
|
||||||
|
assert.Empty(t, rules.In.rulesAt(iputil.IPProtocolTCP, PortAny))
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Nil(t, rules.In.protos[iputil.IPProtocolUDP][1].Any.Any)
|
r = oneRuleAt(t, rules.In, iputil.IPProtocolUDP, 1)
|
||||||
assert.Contains(t, rules.In.protos[iputil.IPProtocolUDP][1].Any.Groups[0].Groups, "g1")
|
assert.False(t, r.remoteAny)
|
||||||
assert.Empty(t, rules.In.protos[iputil.IPProtocolUDP][1].Any.Hosts)
|
assert.Equal(t, []string{"g1"}, r.groups)
|
||||||
|
assert.Empty(t, r.host)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMP, 1, 1, []string{}, "h1", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMP, 1, 1, []string{}, "h1", "", "", "", ""))
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMPv6, 1, 1, []string{}, "h2", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMPv6, 1, 1, []string{}, "h2", "", "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
//no matter what port is given for icmp, it should end up as "any"
|
// An ICMP rule is port `any` regardless of the port given, and ICMP and ICMPv6 share one set of rules.
|
||||||
assert.Nil(t, rules.In.protos[iputil.IPProtocolICMP][PortAny].Any.Any)
|
for _, proto := range []uint8{iputil.IPProtocolICMP, iputil.IPProtocolICMPv6} {
|
||||||
assert.Empty(t, rules.In.protos[iputil.IPProtocolICMP][PortAny].Any.Groups)
|
rs := rules.In.rulesAt(proto, PortAny)
|
||||||
assert.Contains(t, rules.In.protos[iputil.IPProtocolICMP][PortAny].Any.Hosts, "h1")
|
require.Len(t, rs, 2, "proto %d", proto)
|
||||||
|
assert.False(t, rs[0].remoteAny)
|
||||||
// ICMP and ICMPv6 share one set of rules
|
assert.Equal(t, "h1", rs[0].host)
|
||||||
assert.Contains(t, rules.In.protos[iputil.IPProtocolICMP][PortAny].Any.Hosts, "h2")
|
assert.Equal(t, "h2", rs[1].host)
|
||||||
assert.Contains(t, rules.In.protos[iputil.IPProtocolICMPv6][PortAny].Any.Hosts, "h1")
|
}
|
||||||
|
assert.Same(t, rules.In.protos[iputil.IPProtocolICMP], rules.In.protos[iputil.IPProtocolICMPv6])
|
||||||
|
|
||||||
// Any other protocol number gets its own rules
|
// Any other protocol number gets its own rules
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, 47, 0, 0, []string{"g1"}, "", "", "", "", "")) // GRE
|
require.NoError(t, rb.AddRule(true, 47, 0, 0, []string{"g1"}, "", "", "", "", "")) // GRE
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Contains(t, rules.In.protos[47][PortAny].Any.Groups[0].Groups, "g1")
|
assert.Equal(t, []string{"g1"}, oneRuleAt(t, rules.In, 47, PortAny).groups)
|
||||||
assert.Nil(t, rules.In.protos[iputil.IPProtocolTCP])
|
assert.Nil(t, rules.In.protos[iputil.IPProtocolTCP])
|
||||||
|
|
||||||
|
// A proto `any` rule with a port applies to every protocol with ports, and ProtoAny itself has none.
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", ti.String(), "", "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", ti.String(), "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Nil(t, rules.Out.protos[ProtoAny][1].Any.Any)
|
assert.Empty(t, rules.Out.rulesAt(ProtoAny, 1))
|
||||||
_, ok := rules.Out.protos[ProtoAny][1].Any.CIDR.Get(ti)
|
r = oneRuleAt(t, rules.Out, iputil.IPProtocolTCP, 1)
|
||||||
assert.True(t, ok)
|
assert.False(t, r.remoteAny)
|
||||||
|
assert.Equal(t, ti, r.cidr)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", ti6.String(), "", "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", ti6.String(), "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Nil(t, rules.Out.protos[ProtoAny][1].Any.Any)
|
r = oneRuleAt(t, rules.Out, iputil.IPProtocolTCP, 1)
|
||||||
_, ok = rules.Out.protos[ProtoAny][1].Any.CIDR.Get(ti6)
|
assert.False(t, r.remoteAny)
|
||||||
assert.True(t, ok)
|
assert.Equal(t, ti6, r.cidr)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", "", ti.String(), "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", "", ti.String(), "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.NotNil(t, rules.Out.protos[ProtoAny][1].Any.Any)
|
r = oneRuleAt(t, rules.Out, iputil.IPProtocolTCP, 1)
|
||||||
ok = rules.Out.protos[ProtoAny][1].Any.Any.LocalCIDR.Get(ti)
|
assert.True(t, r.remoteAny)
|
||||||
assert.True(t, ok)
|
assert.False(t, r.localAny)
|
||||||
|
assert.Equal(t, []netip.Prefix{ti}, r.local)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", "", ti6.String(), "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 1, 1, []string{}, "", "", ti6.String(), "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.NotNil(t, rules.Out.protos[ProtoAny][1].Any.Any)
|
r = oneRuleAt(t, rules.Out, iputil.IPProtocolTCP, 1)
|
||||||
ok = rules.Out.protos[ProtoAny][1].Any.Any.LocalCIDR.Get(ti6)
|
assert.True(t, r.remoteAny)
|
||||||
assert.True(t, ok)
|
assert.False(t, r.localAny)
|
||||||
|
assert.Equal(t, []netip.Prefix{ti6}, r.local)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "ca-name", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "ca-name", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Contains(t, rules.In.protos[iputil.IPProtocolUDP][1].CANames, "ca-name")
|
assert.Equal(t, "ca-name", oneRuleAt(t, rules.In, iputil.IPProtocolUDP, 1).caName)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", "ca-sha"))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", "ca-sha"))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Contains(t, rules.In.protos[iputil.IPProtocolUDP][1].CAShas, "ca-sha")
|
assert.Equal(t, "ca-sha", oneRuleAt(t, rules.In, iputil.IPProtocolUDP, 1).caSha)
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "any", "", "", "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "any", "", "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.True(t, rules.Out.protos[ProtoAny][0].Any.Any.Any)
|
assert.True(t, oneRuleAt(t, rules.Out, ProtoAny, 0).remoteAny)
|
||||||
|
|
||||||
|
// 0.0.0.0/0 allows any IPv4 address, but no IPv6 address.
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
anyIp, err := netip.ParsePrefix("0.0.0.0/0")
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "0.0.0.0/0", "", "", ""))
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", anyIp.String(), "", "", ""))
|
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Nil(t, rules.Out.protos[ProtoAny][0].Any.Any)
|
r = oneRuleAt(t, rules.Out, ProtoAny, 0)
|
||||||
table, ok := rules.Out.protos[ProtoAny][0].Any.CIDR.Lookup(netip.MustParseAddr("1.1.1.1"))
|
assert.False(t, r.remoteAny)
|
||||||
assert.True(t, table.Any)
|
assert.True(t, r.matchRemote(netip.MustParseAddr("1.1.1.1"), nil))
|
||||||
table, ok = rules.Out.protos[ProtoAny][0].Any.CIDR.Lookup(netip.MustParseAddr("9::9"))
|
assert.False(t, r.matchRemote(netip.MustParseAddr("9::9"), nil))
|
||||||
assert.False(t, ok)
|
|
||||||
|
|
||||||
|
// ::/0 allows any IPv6 address, but no IPv4 address.
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
anyIp6, err := netip.ParsePrefix("::/0")
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "::/0", "", "", ""))
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", anyIp6.String(), "", "", ""))
|
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Nil(t, rules.Out.protos[ProtoAny][0].Any.Any)
|
r = oneRuleAt(t, rules.Out, ProtoAny, 0)
|
||||||
table, ok = rules.Out.protos[ProtoAny][0].Any.CIDR.Lookup(netip.MustParseAddr("9::9"))
|
assert.False(t, r.remoteAny)
|
||||||
assert.True(t, table.Any)
|
assert.True(t, r.matchRemote(netip.MustParseAddr("9::9"), nil))
|
||||||
table, ok = rules.Out.protos[ProtoAny][0].Any.CIDR.Lookup(netip.MustParseAddr("1.1.1.1"))
|
assert.False(t, r.matchRemote(netip.MustParseAddr("1.1.1.1"), nil))
|
||||||
assert.False(t, ok)
|
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "any", "", "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "any", "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.True(t, rules.Out.protos[ProtoAny][0].Any.Any.Any)
|
assert.True(t, oneRuleAt(t, rules.Out, ProtoAny, 0).remoteAny)
|
||||||
|
|
||||||
|
// A local cidr is likewise limited to its own address family.
|
||||||
|
rb = NewRulesBuilder(l)
|
||||||
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "", "0.0.0.0/0", "", ""))
|
||||||
|
rules = rb.Build(nil, nil)
|
||||||
|
r = oneRuleAt(t, rules.Out, ProtoAny, 0)
|
||||||
|
assert.False(t, r.localAny)
|
||||||
|
assert.True(t, r.matchLocal(netip.MustParseAddr("1.1.1.1")))
|
||||||
|
assert.False(t, r.matchLocal(netip.MustParseAddr("9::9")))
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "", anyIp.String(), "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "", "::/0", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.False(t, rules.Out.protos[ProtoAny][0].Any.Any.Any)
|
r = oneRuleAt(t, rules.Out, ProtoAny, 0)
|
||||||
assert.True(t, rules.Out.protos[ProtoAny][0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("1.1.1.1")))
|
assert.False(t, r.localAny)
|
||||||
assert.False(t, rules.Out.protos[ProtoAny][0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("9::9")))
|
assert.True(t, r.matchLocal(netip.MustParseAddr("9::9")))
|
||||||
|
assert.False(t, r.matchLocal(netip.MustParseAddr("1.1.1.1")))
|
||||||
rb = NewRulesBuilder(l)
|
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "", anyIp6.String(), "", ""))
|
|
||||||
rules = rb.Build(nil, nil)
|
|
||||||
assert.False(t, rules.Out.protos[ProtoAny][0].Any.Any.Any)
|
|
||||||
assert.True(t, rules.Out.protos[ProtoAny][0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("9::9")))
|
|
||||||
assert.False(t, rules.Out.protos[ProtoAny][0].Any.Any.LocalCIDR.Lookup(netip.MustParseAddr("1.1.1.1")))
|
|
||||||
|
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "", "any", "", ""))
|
require.NoError(t, rb.AddRule(false, ProtoAny, 0, 0, []string{}, "", "", "any", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.True(t, rules.Out.protos[ProtoAny][0].Any.Any.Any)
|
assert.True(t, oneRuleAt(t, rules.Out, ProtoAny, 0).localAny)
|
||||||
|
|
||||||
// Every protocol number is accepted
|
// Every protocol number is accepted
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.NoError(t, rb.AddRule(true, math.MaxUint8, 0, 0, []string{}, "", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, math.MaxUint8, 0, 0, []string{}, "", "", "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.True(t, rules.In.protos[math.MaxUint8][PortAny].Any.Any.Any)
|
assert.True(t, oneRuleAt(t, rules.In, math.MaxUint8, PortAny).remoteAny)
|
||||||
|
|
||||||
// Test error conditions, a bad rule is reported when it's added
|
// Test error conditions, a bad rule is reported when it's added
|
||||||
rb = NewRulesBuilder(l)
|
rb = NewRulesBuilder(l)
|
||||||
require.Error(t, rb.AddRule(true, ProtoAny, 10, 0, []string{}, "", "", "", "", ""))
|
require.Error(t, rb.AddRule(true, ProtoAny, 10, 0, []string{}, "", "", "", "", ""))
|
||||||
|
require.Error(t, rb.AddRule(true, ProtoAny, PortFragment-1, 0, []string{}, "", "", "", "", ""))
|
||||||
|
require.Error(t, rb.AddRule(true, ProtoAny, 1, math.MaxUint16+1, []string{}, "", "", "", "", ""))
|
||||||
require.Error(t, rb.AddRule(true, ProtoAny, 0, 0, []string{}, "", "junk", "", "", ""))
|
require.Error(t, rb.AddRule(true, ProtoAny, 0, 0, []string{}, "", "junk", "", "", ""))
|
||||||
require.Error(t, rb.AddRule(true, ProtoAny, 0, 0, []string{}, "", "", "junk", "", ""))
|
require.Error(t, rb.AddRule(true, ProtoAny, 0, 0, []string{}, "", "", "junk", "", ""))
|
||||||
|
|
||||||
@@ -163,8 +201,9 @@ func TestRulesBuilder_AddRule(t *testing.T) {
|
|||||||
require.NoError(t, rb.AddRule(true, ProtoAny, PortAny, PortAny, []string{"default-group"}, "", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, ProtoAny, PortAny, PortAny, []string{"default-group"}, "", "", "", "", ""))
|
||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMPv6, PortAny, PortAny, []string{"nope"}, "", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolICMPv6, PortAny, PortAny, []string{"nope"}, "", "", "", "", ""))
|
||||||
rules = rb.Build(nil, nil)
|
rules = rb.Build(nil, nil)
|
||||||
assert.Len(t, rules.In.protos[iputil.IPProtocolICMP][PortAny].Any.Groups, 2)
|
assert.Len(t, rules.In.rules, 2)
|
||||||
assert.Len(t, rules.In.protos[iputil.IPProtocolICMPv6][PortAny].Any.Groups, 2)
|
assert.Len(t, rules.In.rulesAt(iputil.IPProtocolICMP, PortAny), 2)
|
||||||
|
assert.Len(t, rules.In.rulesAt(iputil.IPProtocolICMPv6, PortAny), 2)
|
||||||
|
|
||||||
// No rules allow nothing
|
// No rules allow nothing
|
||||||
rules = NewRulesBuilder(l).Build(nil, nil)
|
rules = NewRulesBuilder(l).Build(nil, nil)
|
||||||
@@ -174,10 +213,86 @@ func TestRulesBuilder_AddRule(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRulesBuilder_sharedLocalCIDR ensures local cidrs shared between rules and ports are copied, not changed,
|
// TestRulesBuilder_protoIndex checks which packets each kind of port clause covers, and which protocols
|
||||||
// when another rule's local cidrs are added to them. The prefixes share their first octet so the copy has to reach
|
// share an index.
|
||||||
// past the root of the shared table.
|
func TestRulesBuilder_protoIndex(t *testing.T) {
|
||||||
func TestRulesBuilder_sharedLocalCIDR(t *testing.T) {
|
rb := NewRulesBuilder(test.NewLogger())
|
||||||
|
require.NoError(t, rb.AddRule(true, ProtoAny, PortAny, PortAny, nil, "any", "", "", "", ""))
|
||||||
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 22, 22, nil, "port", "", "", "", ""))
|
||||||
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 1024, math.MaxUint16, nil, "range", "", "", "", ""))
|
||||||
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, PortFragment, PortFragment, nil, "fragment", "", "", "", ""))
|
||||||
|
// A range that includes port 0 is port `any`.
|
||||||
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolUDP, 0, 100, nil, "zero", "", "", "", ""))
|
||||||
|
// GRE has no ports, so a port rule on it is rejected rather than never applying, and `any` and `fragment` apply
|
||||||
|
require.Error(t, rb.AddRule(true, 47, 22, 22, nil, "gre", "", "", "", ""))
|
||||||
|
require.NoError(t, rb.AddRule(true, 47, PortFragment, PortFragment, nil, "gre", "", "", "", ""))
|
||||||
|
rules := rb.Build(nil, nil)
|
||||||
|
|
||||||
|
hosts := func(proto uint8, key int32) []string {
|
||||||
|
var hosts []string
|
||||||
|
for _, r := range rules.In.rulesAt(proto, key) {
|
||||||
|
hosts = append(hosts, r.host)
|
||||||
|
}
|
||||||
|
return hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, []string{"any", "fragment"}, hosts(iputil.IPProtocolTCP, PortFragment))
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(iputil.IPProtocolTCP, PortAny))
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(iputil.IPProtocolTCP, 21))
|
||||||
|
assert.Equal(t, []string{"any", "port"}, hosts(iputil.IPProtocolTCP, 22))
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(iputil.IPProtocolTCP, 23))
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(iputil.IPProtocolTCP, 1023))
|
||||||
|
assert.Equal(t, []string{"any", "range"}, hosts(iputil.IPProtocolTCP, 1024))
|
||||||
|
assert.Equal(t, []string{"any", "range"}, hosts(iputil.IPProtocolTCP, math.MaxUint16))
|
||||||
|
|
||||||
|
assert.Equal(t, []string{"any", "zero"}, hosts(iputil.IPProtocolUDP, PortFragment))
|
||||||
|
assert.Equal(t, []string{"any", "zero"}, hosts(iputil.IPProtocolUDP, PortAny))
|
||||||
|
assert.Equal(t, []string{"any", "zero"}, hosts(iputil.IPProtocolUDP, math.MaxUint16))
|
||||||
|
|
||||||
|
// A protocol without ports sees only the port `any` rules, and the port `fragment` rules for a fragment.
|
||||||
|
assert.False(t, rules.In.protos[47].hasPorts)
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(47, PortAny))
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(47, 22))
|
||||||
|
assert.Equal(t, []string{"any", "gre"}, hosts(47, PortFragment))
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(iputil.IPProtocolICMP, PortFragment))
|
||||||
|
|
||||||
|
// Protocols without rules of their own share an index of the proto `any` rules: one for protocols with
|
||||||
|
// ports and one for protocols without.
|
||||||
|
assert.True(t, rules.In.protos[iputil.IPProtocolSCTP].hasPorts)
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(iputil.IPProtocolSCTP, 5000))
|
||||||
|
assert.Same(t, rules.In.protos[iputil.IPProtocolSCTP], rules.In.protos[iputil.IPProtocolDCCP])
|
||||||
|
assert.NotSame(t, rules.In.protos[iputil.IPProtocolSCTP], rules.In.protos[iputil.IPProtocolTCP])
|
||||||
|
assert.Equal(t, []string{"any"}, hosts(50, PortAny))
|
||||||
|
assert.Same(t, rules.In.protos[ProtoAny], rules.In.protos[50])
|
||||||
|
assert.Same(t, rules.In.protos[ProtoAny], rules.In.protos[iputil.IPProtocolICMP])
|
||||||
|
assert.NotSame(t, rules.In.protos[ProtoAny], rules.In.protos[iputil.IPProtocolSCTP])
|
||||||
|
assert.Nil(t, rules.Out.protos[iputil.IPProtocolTCP])
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRulesBuilder_manyRules checks that rule ids beyond the first byte of a rule set are indexed correctly.
|
||||||
|
func TestRulesBuilder_manyRules(t *testing.T) {
|
||||||
|
rb := NewRulesBuilder(test.NewLogger())
|
||||||
|
const n = 130
|
||||||
|
for i := range n {
|
||||||
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, int32(i+1), int32(i+1), nil, fmt.Sprintf("h%d", i), "", "", "", ""))
|
||||||
|
}
|
||||||
|
require.NoError(t, rb.AddRule(true, ProtoAny, PortAny, PortAny, nil, "any", "", "", "", ""))
|
||||||
|
rules := rb.Build(nil, nil)
|
||||||
|
|
||||||
|
assert.Equal(t, ruleSetLen(n+1), rules.In.protos[iputil.IPProtocolTCP].byPort.setLen)
|
||||||
|
// Ids are the order the rules were added in, so the proto `any` rule comes last
|
||||||
|
for i := range n {
|
||||||
|
rs := rules.In.rulesAt(iputil.IPProtocolTCP, int32(i+1))
|
||||||
|
require.Len(t, rs, 2, "port %d", i+1)
|
||||||
|
assert.Equal(t, fmt.Sprintf("h%d", i), rs[0].host)
|
||||||
|
assert.Equal(t, "any", rs[1].host)
|
||||||
|
}
|
||||||
|
assert.Len(t, rules.In.rulesAt(iputil.IPProtocolTCP, n+1), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRulesBuilder_defaultLocalCIDR checks which local addresses rules allow when there are unsafe networks.
|
||||||
|
// A rule without a local cidr allows only the vpn networks, and a rule with one allows only that cidr.
|
||||||
|
func TestRulesBuilder_defaultLocalCIDR(t *testing.T) {
|
||||||
vpnNetworks := []netip.Prefix{
|
vpnNetworks := []netip.Prefix{
|
||||||
netip.MustParsePrefix("10.1.0.5/16"),
|
netip.MustParsePrefix("10.1.0.5/16"),
|
||||||
netip.MustParsePrefix("10.2.0.5/16"),
|
netip.MustParsePrefix("10.2.0.5/16"),
|
||||||
@@ -203,8 +318,19 @@ func TestRulesBuilder_sharedLocalCIDR(t *testing.T) {
|
|||||||
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 3, 3, nil, "h3", "", "", "", ""))
|
require.NoError(t, rb.AddRule(true, iputil.IPProtocolTCP, 3, 3, nil, "h3", "", "", "", ""))
|
||||||
rules := rb.Build(vpnNetworks, unsafeNetworks)
|
rules := rb.Build(vpnNetworks, unsafeNetworks)
|
||||||
|
|
||||||
|
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||||
|
caPool := cert.NewCAPool()
|
||||||
|
require.NoError(t, caPool.AddCA(ca))
|
||||||
|
certs := map[string]*cert.CachedCertificate{}
|
||||||
|
for _, name := range []string{"h1", "h2", "h3"} {
|
||||||
|
crt, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, name, time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.9/16")}, nil, nil)
|
||||||
|
c, err := caPool.VerifyCertificate(time.Now(), crt)
|
||||||
|
require.NoError(t, err)
|
||||||
|
certs[name] = c
|
||||||
|
}
|
||||||
|
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
port int32
|
port uint16
|
||||||
host string
|
host string
|
||||||
addr netip.Addr
|
addr netip.Addr
|
||||||
want bool
|
want bool
|
||||||
@@ -232,8 +358,10 @@ func TestRulesBuilder_sharedLocalCIDR(t *testing.T) {
|
|||||||
{3, "h3", h1Extra, false},
|
{3, "h3", h1Extra, false},
|
||||||
{3, "h3", h1Extra6, false},
|
{3, "h3", h1Extra6, false},
|
||||||
{3, "h3", h2Own, false},
|
{3, "h3", h2Own, false},
|
||||||
|
// Only h3 is allowed on port 3.
|
||||||
|
{3, "h1", vpn1, false},
|
||||||
} {
|
} {
|
||||||
lr := rules.In.protos[iputil.IPProtocolTCP][tc.port].Any.Hosts[tc.host]
|
p := &Packet{Protocol: iputil.IPProtocolTCP, LocalPort: tc.port, LocalAddr: tc.addr, RemoteAddr: netip.MustParseAddr("10.1.0.9")}
|
||||||
assert.Equal(t, tc.want, lr.match(&Packet{LocalAddr: tc.addr}, nil), "port %d, %s, %s", tc.port, tc.host, tc.addr)
|
assert.Equal(t, tc.want, rules.In.Match(p, true, certs[tc.host], caPool), "port %d, %s, %s", tc.port, tc.host, tc.addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package firewall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"iter"
|
||||||
|
"math/bits"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ruleSet is a set of rule ids, stored as a bitset. s[i] holds ids i*8 through i*8+7, one per bit.
|
||||||
|
// Bytes rather than words keep a set to the size the rule count needs, which matters when there is a set for
|
||||||
|
// every port number.
|
||||||
|
type ruleSet []uint8
|
||||||
|
|
||||||
|
// ruleSetLen returns the length of a ruleSet that can hold ids below n.
|
||||||
|
func ruleSetLen(n int) int {
|
||||||
|
return (n + 7) / 8
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRuleSet returns an empty set that can hold ids below idLimit.
|
||||||
|
func newRuleSet(idLimit int) ruleSet {
|
||||||
|
return make(ruleSet, ruleSetLen(idLimit))
|
||||||
|
}
|
||||||
|
|
||||||
|
// add puts id in s.
|
||||||
|
func (s ruleSet) add(id int) {
|
||||||
|
s[id/8] |= 1 << (id % 8)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ruleSets holds several ruleSet objects of the same length in a single allocation.
|
||||||
|
type ruleSets struct {
|
||||||
|
// setLen is the number of bytes needed to represent one set
|
||||||
|
setLen int
|
||||||
|
// bits holds the sets in order. Set i starts at i*setLen.
|
||||||
|
bits []uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRuleSets returns n empty sets, each of which can hold ids below idLimit.
|
||||||
|
func newRuleSets(n, idLimit int) ruleSets {
|
||||||
|
setLen := ruleSetLen(idLimit)
|
||||||
|
return ruleSets{setLen: setLen, bits: make([]uint8, n*setLen)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// at returns set i.
|
||||||
|
func (s ruleSets) at(i int) ruleSet {
|
||||||
|
return s.bits[i*s.setLen : (i+1)*s.setLen]
|
||||||
|
}
|
||||||
|
|
||||||
|
// all returns an iterator over the ids in s, in ascending order.
|
||||||
|
func (s ruleSet) all() iter.Seq[int] {
|
||||||
|
return func(yield func(int) bool) {
|
||||||
|
for i, ids := range s {
|
||||||
|
for ids != 0 {
|
||||||
|
id := i*8 + bits.TrailingZeros8(ids)
|
||||||
|
ids &= ids - 1 // Clear the lowest set bit, which is id's.
|
||||||
|
if !yield(id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+125
-124
@@ -3,9 +3,7 @@ package firewall
|
|||||||
import (
|
import (
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/iputil"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Rules are the Tables built for each direction, with hashes of the rules they were built from
|
// Rules are the Tables built for each direction, with hashes of the rules they were built from
|
||||||
@@ -18,46 +16,77 @@ type Rules struct {
|
|||||||
HashFNV uint32
|
HashFNV uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
// Table holds the rules for one direction, the evaluation order is:
|
// Table holds the rules for one direction. A packet is allowed when every clause of a single rule allows it:
|
||||||
// Proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR)
|
// proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR).
|
||||||
// A Table doesn't change once built, see RulesBuilder.
|
// A Table does not change once built; see RulesBuilder.
|
||||||
type Table struct {
|
type Table struct {
|
||||||
// protos holds the rules for each IP protocol number, so a packet is only checked against one set of rules.
|
// rules holds every rule for the direction, in the order they were added. A rule's index in this slice is
|
||||||
// A protocol with rules of its own also holds a copy of every proto `any` rule, the rest share the proto `any`
|
// its id in the ruleSets.
|
||||||
// rules, which are at protos[ProtoAny]. nil when a protocol has no rules at all.
|
rules []rule
|
||||||
// ICMP and ICMPv6 share one set of rules.
|
|
||||||
protos [256]portRules
|
// protos holds the index for each IP protocol number, so a packet is checked against a single index.
|
||||||
|
// A protocol with rules of its own has an index that also includes every proto `any` rule. The remaining
|
||||||
|
// protocols share an index of only the proto `any` rules: one for protocols with ports and one for
|
||||||
|
// protocols without; see hasPorts. An entry is nil when the protocol has no rules at all.
|
||||||
|
// ICMP and ICMPv6 share one index.
|
||||||
|
protos [256]*protoIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Even though ports are uint16, int32 maps are faster for lookup
|
// protoIndex holds the rules that can apply to one protocol, in a set for each kind of packet. Rule ids are
|
||||||
// Plus we can use `-1` for fragment rules
|
// indexes into the direction's rules, so every set is sized by the direction's rule count, not the protocol's:
|
||||||
type portRules map[int32]*caRules
|
// byPort costs 64 KB per 8 rules in the direction.
|
||||||
|
type protoIndex struct {
|
||||||
// caRules and the types below it only make their maps and tables once a rule needs them, a range of ports
|
// hasPorts reports whether the protocol has ports; see iputil.HasPorts.
|
||||||
// gets a copy for every port so empty ones add up
|
hasPorts bool
|
||||||
type caRules struct {
|
// byPort has a set for every port number of a protocol with ports. Port 0 is covered only by port `any`
|
||||||
Any *remoteRules
|
// rules, since a range starts at 1.
|
||||||
CANames map[string]*remoteRules
|
byPort ruleSets
|
||||||
CAShas map[string]*remoteRules
|
// packet holds the rules for a packet of a protocol without ports: the port `any` rules.
|
||||||
|
packet ruleSet
|
||||||
|
// fragment holds the rules for a fragment of any protocol: the port `any` and port `fragment` rules.
|
||||||
|
fragment ruleSet
|
||||||
}
|
}
|
||||||
|
|
||||||
type remoteRules struct {
|
// whichMatch returns the set of rules whose proto and port clauses allow p.
|
||||||
// Any makes Hosts, Groups, and CIDR irrelevant
|
func (pi *protoIndex) whichMatch(p *Packet, incoming bool) ruleSet {
|
||||||
Any *localRules
|
switch {
|
||||||
Hosts map[string]*localRules
|
case p.Fragment:
|
||||||
Groups []*groupsRule
|
// The ports of a fragmented packet are in its first fragment, and this is a later one.
|
||||||
CIDR *bart.Table[*localRules]
|
return pi.fragment
|
||||||
|
case !pi.hasPorts:
|
||||||
|
// The port fields are zero, or for ICMP the identifier, which is only for connection tracking.
|
||||||
|
return pi.packet
|
||||||
|
case incoming:
|
||||||
|
return pi.byPort.at(int(p.LocalPort))
|
||||||
|
default:
|
||||||
|
return pi.byPort.at(int(p.RemotePort))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type groupsRule struct {
|
// rule is a parsed rule. A packet is allowed by the rule when its port, certificate, and address clauses all pass.
|
||||||
Groups []string
|
type rule struct {
|
||||||
LocalCIDR *localRules
|
// proto is the IP protocol number the rule applies to, or ProtoAny for every protocol. ICMPv6 rules are kept
|
||||||
}
|
// as ICMP. The protoIndex checks it, so match does not.
|
||||||
|
proto uint8
|
||||||
|
|
||||||
type localRules struct {
|
// startPort and endPort are the port clause. A startPort of PortAny covers every port, every packet of a
|
||||||
Any bool
|
// protocol without ports, and every fragment. PortFragment covers only fragments. A range covers the ports
|
||||||
// LocalCIDR is always set when Any isn't. It's shared with other localRules, so it's never changed.
|
// in it, so it never applies to a protocol without ports.
|
||||||
LocalCIDR *bart.Lite
|
startPort, endPort int32
|
||||||
|
|
||||||
|
// caSha and caName pass a certificate issued by either CA. When neither is set, any CA passes.
|
||||||
|
caSha, caName string
|
||||||
|
|
||||||
|
// remoteAny makes host, groups, and cidr irrelevant. Otherwise, the peer passes when any one of them matches.
|
||||||
|
remoteAny bool
|
||||||
|
host string
|
||||||
|
groups []string
|
||||||
|
cidr netip.Prefix // Invalid when the rule has no cidr.
|
||||||
|
|
||||||
|
// localAny allows any local address. Otherwise, local must contain the address. Neither is set for a rule
|
||||||
|
// without a local cidr until the Table is built and the rule gets the default; see withDefaultLocal.
|
||||||
|
localAny bool
|
||||||
|
local []netip.Prefix
|
||||||
}
|
}
|
||||||
|
|
||||||
// Match reports whether a rule for the direction p is going allows it
|
// Match reports whether a rule for the direction p is going allows it
|
||||||
@@ -71,118 +100,90 @@ func (r *Rules) Match(p *Packet, incoming bool, c *cert.CachedCertificate, caPoo
|
|||||||
|
|
||||||
// Match reports whether a rule allows p
|
// Match reports whether a rule allows p
|
||||||
func (t *Table) Match(p *Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
func (t *Table) Match(p *Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
||||||
return t.protos[p.Protocol].match(p, incoming, c, caPool)
|
proto := t.protos[p.Protocol]
|
||||||
}
|
if proto == nil {
|
||||||
|
// The protocol has no rules of its own, and there are no proto `any` rules.
|
||||||
func (pr portRules) match(p *Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
|
||||||
// We don't have any allowed ports, bail
|
|
||||||
if pr == nil {
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// ICMP has no ports, only the port `any` rules apply, including the ones copied in from proto `any` rules
|
// The index yields every rule whose proto and port clauses allow p.
|
||||||
if p.Protocol == iputil.IPProtocolICMP || p.Protocol == iputil.IPProtocolICMPv6 {
|
// The packet is allowed when the remaining clauses of any of those rules allow it as well.
|
||||||
// port numbers are re-used for connection tracking of ICMP,
|
for id := range proto.whichMatch(p, incoming).all() {
|
||||||
// but we don't want to actually filter on them.
|
if t.rules[id].match(p, c, caPool) {
|
||||||
return pr[PortAny].match(p, c, caPool)
|
|
||||||
}
|
|
||||||
|
|
||||||
var port int32
|
|
||||||
|
|
||||||
if p.Fragment {
|
|
||||||
port = PortFragment
|
|
||||||
} else if incoming {
|
|
||||||
port = int32(p.LocalPort)
|
|
||||||
} else {
|
|
||||||
port = int32(p.RemotePort)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Packets without ports (gre, esp, etc) have port 0, which is PortAny, don't check those rules twice
|
|
||||||
if port != PortAny && pr[port].match(p, c, caPool) {
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
return pr[PortAny].match(p, c, caPool)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cr *caRules) match(p *Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
|
||||||
if cr == nil {
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if cr.Any.match(p, c) {
|
// match reports whether r allows p from the peer with certificate c. The port clause is not checked here; the
|
||||||
|
// protoIndex has already done so.
|
||||||
|
func (r *rule) match(p *Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
||||||
|
return r.matchLocal(p.LocalAddr) && r.matchRemote(p.RemoteAddr, c) && r.matchCA(c, caPool)
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchLocal reports whether r allows the local address addr.
|
||||||
|
func (r *rule) matchLocal(addr netip.Addr) bool {
|
||||||
|
if r.localAny {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
if t, ok := cr.CAShas[c.Certificate.Issuer()]; ok {
|
for _, prefix := range r.local {
|
||||||
if t.match(p, c) {
|
if prefix.Contains(addr) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchRemote reports whether r allows the peer with certificate c, sending from addr. The cidr is checked with
|
||||||
|
// Prefix.Contains, so 0.0.0.0/0 allows any IPv4 address and ::/0 allows any IPv6 address; neither allows the
|
||||||
|
// other family.
|
||||||
|
func (r *rule) matchRemote(addr netip.Addr, c *cert.CachedCertificate) bool {
|
||||||
|
if r.remoteAny {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.cidr.IsValid() && r.cidr.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.host != "" && r.host == c.Certificate.Name() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every group must be present.
|
||||||
|
if len(r.groups) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, g := range r.groups {
|
||||||
|
if _, ok := c.InvertedGroups[g]; !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchCA reports whether c was issued by a CA that r allows.
|
||||||
|
func (r *rule) matchCA(c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
||||||
|
if r.caSha == "" && r.caName == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.caSha != "" && r.caSha == c.Certificate.Issuer() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.caName != "" {
|
||||||
s, err := caPool.GetCAForCert(c.Certificate)
|
s, err := caPool.GetCAForCert(c.Certificate)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
return r.caName == s.Certificate.Name()
|
||||||
return cr.CANames[s.Certificate.Name()].match(p, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rr *remoteRules) match(p *Packet, c *cert.CachedCertificate) bool {
|
|
||||||
if rr == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Shortcut path for if groups, hosts, or cidr contained an `any`
|
|
||||||
if rr.Any.match(p, c) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Need any of group, host, or cidr to match
|
|
||||||
for _, sg := range rr.Groups {
|
|
||||||
found := false
|
|
||||||
|
|
||||||
for _, g := range sg.Groups {
|
|
||||||
if _, ok := c.InvertedGroups[g]; !ok {
|
|
||||||
found = false
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
found = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if found && sg.LocalCIDR.match(p, c) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if rr.Hosts != nil {
|
|
||||||
if lr, ok := rr.Hosts[c.Certificate.Name()]; ok {
|
|
||||||
if lr.match(p, c) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if rr.CIDR != nil {
|
|
||||||
for _, v := range rr.CIDR.Supernets(netip.PrefixFrom(p.RemoteAddr, p.RemoteAddr.BitLen())) {
|
|
||||||
if v.match(p, c) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lr *localRules) match(p *Packet, c *cert.CachedCertificate) bool {
|
|
||||||
if lr == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if lr.Any {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return lr.LocalCIDR.Contains(p.LocalAddr)
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,7 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -389,6 +390,68 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp)
|
ft.Match(&firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// The port 10 rules have a cidr, this cert fails their group and host so only the cidr can pass them
|
||||||
|
cidrCert := &cert.CachedCertificate{
|
||||||
|
Certificate: &dummyCert{name: "nope"},
|
||||||
|
InvertedGroups: map[string]struct{}{"nope": {}},
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
addr netip.Addr
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"pass on cidr", pfix.Addr(), true},
|
||||||
|
{"pass on cidr6", pfix6.Addr(), true},
|
||||||
|
{"pass proto, port, fail group and name, fail on cidr", netip.MustParseAddr("9.254.254.245"), false},
|
||||||
|
{"pass proto, port, fail group and name, fail on cidr6", netip.MustParseAddr("fd99::99"), false},
|
||||||
|
} {
|
||||||
|
p := &firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10, RemoteAddr: tc.addr}
|
||||||
|
b.Run(tc.name, func(b *testing.B) {
|
||||||
|
if ft.Match(p, true, cidrCert, cp) != tc.want {
|
||||||
|
b.Fatal("wrong verdict")
|
||||||
|
}
|
||||||
|
for b.Loop() {
|
||||||
|
benchMatchSink = ft.Match(p, true, cidrCert, cp)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var benchMatchSink bool
|
||||||
|
|
||||||
|
// BenchmarkFirewallTable_matchManyRules measures a table with more rules than fit in one word of a rule set.
|
||||||
|
// Rule 0 is a proto `any` rule that fails on host, and rules 1 through 130 are tcp ports 1 through 130 for hosts
|
||||||
|
// h1 through h130, so the last rule id is the one that passes.
|
||||||
|
func BenchmarkFirewallTable_matchManyRules(b *testing.B) {
|
||||||
|
rb := firewall.NewRulesBuilder(test.NewLogger())
|
||||||
|
require.NoError(b, rb.AddRule(true, firewall.ProtoAny, firewall.PortAny, firewall.PortAny, nil, "nope", "", "", "", ""))
|
||||||
|
for i := 1; i <= 130; i++ {
|
||||||
|
require.NoError(b, rb.AddRule(true, iputil.IPProtocolTCP, int32(i), int32(i), nil, fmt.Sprintf("h%d", i), "", "", "", ""))
|
||||||
|
}
|
||||||
|
ft := rb.Build(nil, nil).In
|
||||||
|
cp := cert.NewCAPool()
|
||||||
|
c := &cert.CachedCertificate{Certificate: &dummyCert{name: "h130"}, InvertedGroups: map[string]struct{}{}}
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
port uint16
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"fail on port", 5000, false},
|
||||||
|
{"pass on name, last id", 130, true},
|
||||||
|
{"fail on name, middle id", 65, false},
|
||||||
|
} {
|
||||||
|
p := &firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: tc.port}
|
||||||
|
b.Run(tc.name, func(b *testing.B) {
|
||||||
|
if ft.Match(p, true, c, cp) != tc.want {
|
||||||
|
b.Fatal("wrong verdict")
|
||||||
|
}
|
||||||
|
for b.Loop() {
|
||||||
|
benchMatchSink = ft.Match(p, true, c, cp)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_Drop2(t *testing.T) {
|
func TestFirewall_Drop2(t *testing.T) {
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ const (
|
|||||||
ICMPv6TypeEchoReply = 129
|
ICMPv6TypeEchoReply = 129
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// HasPorts reports whether packets of proto carry port numbers that the packet parsers read: TCP, UDP, UDPLite,
|
||||||
|
// DCCP, and SCTP. Firewall rules with a port or a port range only apply to these protocols.
|
||||||
|
func HasPorts(proto uint8) bool {
|
||||||
|
switch proto {
|
||||||
|
case IPProtocolTCP, IPProtocolUDP, IPProtocolUDPLite, IPProtocolDCCP, IPProtocolSCTP:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func CreateRejectPacket(packet []byte, out []byte) []byte {
|
func CreateRejectPacket(packet []byte, out []byte) []byte {
|
||||||
if len(packet) < 1 {
|
if len(packet) < 1 {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
+14
-26
@@ -361,31 +361,29 @@ func parseV6(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
|
|||||||
fp.Fragment = isFragment
|
fp.Fragment = isFragment
|
||||||
fp.FragAny = anyFragment
|
fp.FragAny = anyFragment
|
||||||
fp.IPHdrLen = offset
|
fp.IPHdrLen = offset
|
||||||
|
// fp is reused, so the ports are cleared for the packets that have none: fragments, protocols Nebula
|
||||||
|
// doesn't inspect, and ICMPv6 other than echo. Only the cases below set them.
|
||||||
|
fp.RemotePort, fp.LocalPort = 0, 0
|
||||||
if isFragment {
|
if isFragment {
|
||||||
// Non-first fragments carry no transport header, so we have no ports to read
|
// Non-first fragments carry no transport header, so we have no ports to read
|
||||||
fp.RemotePort = 0
|
|
||||||
fp.LocalPort = 0
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
switch proto {
|
switch {
|
||||||
case iputil.IPProtocolICMPv6:
|
case proto == iputil.IPProtocolICMPv6:
|
||||||
// An ICMPv6 message is at least type, code and checksum, 4 bytes. Only echo carries more than we read.
|
// An ICMPv6 message is at least type, code and checksum, 4 bytes. Only echo carries more than we read.
|
||||||
if dataLen < offset+4 {
|
if dataLen < offset+4 {
|
||||||
return ErrIPv6PacketTooShort
|
return ErrIPv6PacketTooShort
|
||||||
}
|
}
|
||||||
fp.LocalPort = 0 //incoming vs outgoing doesn't matter for icmpv6
|
|
||||||
switch data[offset] { //icmp type
|
switch data[offset] { //icmp type
|
||||||
case iputil.ICMPv6TypeEchoRequest, iputil.ICMPv6TypeEchoReply:
|
case iputil.ICMPv6TypeEchoRequest, iputil.ICMPv6TypeEchoReply:
|
||||||
if dataLen < offset+6 {
|
if dataLen < offset+6 {
|
||||||
return ErrIPv6PacketTooShort
|
return ErrIPv6PacketTooShort
|
||||||
}
|
}
|
||||||
fp.RemotePort = binary.BigEndian.Uint16(data[offset+4 : offset+6]) //identifier
|
fp.RemotePort = binary.BigEndian.Uint16(data[offset+4 : offset+6]) //identifier, orientation doesn't matter
|
||||||
default:
|
|
||||||
fp.RemotePort = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case iputil.IPProtocolTCP, iputil.IPProtocolUDP, iputil.IPProtocolDCCP, iputil.IPProtocolSCTP, iputil.IPProtocolUDPLite:
|
case iputil.HasPorts(proto):
|
||||||
if dataLen < offset+4 {
|
if dataLen < offset+4 {
|
||||||
return ErrIPv6PacketTooShort
|
return ErrIPv6PacketTooShort
|
||||||
}
|
}
|
||||||
@@ -396,11 +394,6 @@ func parseV6(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
|
|||||||
fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
|
fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
|
||||||
fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
|
fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
|
||||||
}
|
}
|
||||||
|
|
||||||
default:
|
|
||||||
// don't set ports for protocols Nebula doesn't inspect
|
|
||||||
fp.RemotePort = 0
|
|
||||||
fp.LocalPort = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -453,18 +446,18 @@ func parseV4(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
|
|||||||
fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
|
fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fp is reused, so the ports are cleared for the packets that have none: fragments, and protocols Nebula
|
||||||
|
// doesn't inspect, whose first 4 bytes (GRE, IPIP, AH, etc.) are not ports. Only the cases below set them.
|
||||||
|
fp.RemotePort, fp.LocalPort = 0, 0
|
||||||
if fp.Fragment {
|
if fp.Fragment {
|
||||||
fp.RemotePort = 0
|
|
||||||
fp.LocalPort = 0
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
switch fp.Protocol {
|
switch {
|
||||||
case iputil.IPProtocolICMP: //note that orientation doesn't matter on ICMP
|
case fp.Protocol == iputil.IPProtocolICMP: //note that orientation doesn't matter on ICMP
|
||||||
fp.RemotePort = binary.BigEndian.Uint16(data[ihl+4 : ihl+6]) //identifier
|
fp.RemotePort = binary.BigEndian.Uint16(data[ihl+4 : ihl+6]) //identifier, LocalPort stays 0 but could be the code, data[ihl+1]
|
||||||
fp.LocalPort = 0 //code would be uint16(data[ihl+1])
|
|
||||||
|
|
||||||
case iputil.IPProtocolTCP, iputil.IPProtocolUDP, iputil.IPProtocolDCCP, iputil.IPProtocolSCTP, iputil.IPProtocolUDPLite:
|
case iputil.HasPorts(fp.Protocol):
|
||||||
if incoming {
|
if incoming {
|
||||||
fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
|
fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
|
||||||
fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
|
fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
|
||||||
@@ -472,11 +465,6 @@ func parseV4(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
|
|||||||
fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
|
fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
|
||||||
fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
|
fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
|
||||||
}
|
}
|
||||||
|
|
||||||
default:
|
|
||||||
// don't set ports for protocols Nebula doesn't inspect, the first 4 bytes of GRE, IPIP, AH, etc. are not ports
|
|
||||||
fp.RemotePort = 0
|
|
||||||
fp.LocalPort = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
Reference in new issue
Block a user