Debian Codegraph @

firewall.go

raw
1 package nebula
2
3 import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "hash/fnv"
10 "log/slog"
11 "net/netip"
12 "reflect"
13 "slices"
14 "strconv"
15 "strings"
16 "sync"
17 "time"
18
19 "github.com/gaissmai/bart"
20 "github.com/rcrowley/go-metrics"
21 "github.com/slackhq/nebula/cert"
22 "github.com/slackhq/nebula/config"
23 "github.com/slackhq/nebula/firewall"
24 )
25
26 type FirewallInterface interface {
27 AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr string, caName string, caSha string) error
28 }
29
30 type conn struct {
31 Expires time.Time // Time when this conntrack entry will expire
32
33 // record why the original connection passed the firewall, so we can re-validate
34 // after ruleset changes. Note, rulesVersion is a uint16 so that these two
35 // fields pack for free after the uint32 above
36 incoming bool
37 rulesVersion uint16
38 }
39
40 // TODO: need conntrack max tracked connections handling
41 type Firewall struct {
42 Conntrack *FirewallConntrack
43
44 InRules *FirewallTable
45 OutRules *FirewallTable
46
47 InboundSendReject bool
48 OutboundSendReject bool
49
50 //TODO: we should have many more options for TCP, an option for ICMP, and mimic the kernel a bit better
51 // https://www.kernel.org/doc/Documentation/networking/nf_conntrack-sysctl.txt
52 TCPTimeout time.Duration //linux: 5 days max
53 UDPTimeout time.Duration //linux: 180s max
54 DefaultTimeout time.Duration //linux: 600s
55
56 // routableNetworks describes the vpn addresses as well as any unsafe networks issued to us in the certificate.
57 // The vpn addresses are a full bit match while the unsafe networks only match the prefix
58 routableNetworks *bart.Lite
59
60 // assignedNetworks is a list of vpn networks assigned to us in the certificate.
61 assignedNetworks []netip.Prefix
62 // unsafeNetworks is the list of unsafe networks issued to us in the certificate
63 unsafeNetworks []netip.Prefix
64
65 rules string
66 rulesVersion uint16
67
68 defaultLocalCIDRAny bool
69 incomingMetrics firewallMetrics
70 outgoingMetrics firewallMetrics
71
72 l *slog.Logger
73 }
74
75 type firewallMetrics struct {
76 droppedLocalAddr metrics.Counter
77 droppedRemoteAddr metrics.Counter
78 droppedNoRule metrics.Counter
79 }
80
81 type FirewallConntrack struct {
82 sync.Mutex
83
84 Conns map[firewall.Packet]*conn
85 TimerWheel *TimerWheel[firewall.Packet]
86 }
87
88 // FirewallTable is the entry point for a rule, the evaluation order is:
89 // Proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR)
90 type FirewallTable struct {
91 TCP firewallPort
92 UDP firewallPort
93 ICMP firewallPort
94 AnyProto firewallPort
95 }
96
97 func newFirewallTable() *FirewallTable {
98 return &FirewallTable{
99 TCP: firewallPort{},
100 UDP: firewallPort{},
101 ICMP: firewallPort{},
102 AnyProto: firewallPort{},
103 }
104 }
105
106 type FirewallCA struct {
107 Any *FirewallRule
108 CANames map[string]*FirewallRule
109 CAShas map[string]*FirewallRule
110 }
111
112 type FirewallRule struct {
113 // Any makes Hosts, Groups, and CIDR irrelevant
114 Any *firewallLocalCIDR
115 Hosts map[string]*firewallLocalCIDR
116 Groups []*firewallGroups
117 CIDR *bart.Table[*firewallLocalCIDR]
118 }
119
120 type firewallGroups struct {
121 Groups []string
122 LocalCIDR *firewallLocalCIDR
123 }
124
125 // Even though ports are uint16, int32 maps are faster for lookup
126 // Plus we can use `-1` for fragment rules
127 type firewallPort map[int32]*FirewallCA
128
129 type firewallLocalCIDR struct {
130 Any bool
131 LocalCIDR *bart.Lite
132 }
133
134 // NewFirewall creates a new Firewall object. A TimerWheel is created for you from the provided timeouts.
135 // The certificate provided should be the highest version loaded in memory.
136 func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c cert.Certificate) *Firewall {
137 //TODO: error on 0 duration
138 var tmin, tmax time.Duration
139
140 if tcpTimeout < UDPTimeout {
141 tmin = tcpTimeout
142 tmax = UDPTimeout
143 } else {
144 tmin = UDPTimeout
145 tmax = tcpTimeout
146 }
147
148 if defaultTimeout < tmin {
149 tmin = defaultTimeout
150 } else if defaultTimeout > tmax {
151 tmax = defaultTimeout
152 }
153
154 routableNetworks := new(bart.Lite)
155 var assignedNetworks []netip.Prefix
156 for _, network := range c.Networks() {
157 nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
158 routableNetworks.Insert(nprefix)
159 assignedNetworks = append(assignedNetworks, network)
160 }
161
162 unsafeNetworks := c.UnsafeNetworks()
163 for _, n := range unsafeNetworks {
164 routableNetworks.Insert(n)
165 }
166
167 return &Firewall{
168 Conntrack: &FirewallConntrack{
169 Conns: make(map[firewall.Packet]*conn),
170 TimerWheel: NewTimerWheel[firewall.Packet](tmin, tmax),
171 },
172 InRules: newFirewallTable(),
173 OutRules: newFirewallTable(),
174 TCPTimeout: tcpTimeout,
175 UDPTimeout: UDPTimeout,
176 DefaultTimeout: defaultTimeout,
177 routableNetworks: routableNetworks,
178 assignedNetworks: assignedNetworks,
179 unsafeNetworks: unsafeNetworks,
180 l: l,
181
182 incomingMetrics: firewallMetrics{
183 droppedLocalAddr: metrics.GetOrRegisterCounter("firewall.incoming.dropped.local_addr", nil),
184 droppedRemoteAddr: metrics.GetOrRegisterCounter("firewall.incoming.dropped.remote_addr", nil),
185 droppedNoRule: metrics.GetOrRegisterCounter("firewall.incoming.dropped.no_rule", nil),
186 },
187 outgoingMetrics: firewallMetrics{
188 droppedLocalAddr: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.local_addr", nil),
189 droppedRemoteAddr: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.remote_addr", nil),
190 droppedNoRule: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.no_rule", nil),
191 },
192 }
193 }
194
195 func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewall, error) {
196 certificate := cs.getCertificate(cert.Version2)
197 if certificate == nil {
198 certificate = cs.getCertificate(cert.Version1)
199 }
200
201 if certificate == nil {
202 panic("No certificate available to reconfigure the firewall")
203 }
204
205 fw := NewFirewall(
206 l,
207 c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12),
208 c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3),
209 c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10),
210 certificate,
211 //TODO: max_connections
212 )
213
214 fw.defaultLocalCIDRAny = c.GetBool("firewall.default_local_cidr_any", false)
215
216 inboundAction := c.GetString("firewall.inbound_action", "drop")
217 switch inboundAction {
218 case "reject":
219 fw.InboundSendReject = true
220 case "drop":
221 fw.InboundSendReject = false
222 default:
223 l.Warn("invalid firewall.inbound_action, defaulting to `drop`", "action", inboundAction)
224 fw.InboundSendReject = false
225 }
226
227 outboundAction := c.GetString("firewall.outbound_action", "drop")
228 switch outboundAction {
229 case "reject":
230 fw.OutboundSendReject = true
231 case "drop":
232 fw.OutboundSendReject = false
233 default:
234 l.Warn("invalid firewall.outbound_action, defaulting to `drop`", "action", outboundAction)
235 fw.OutboundSendReject = false
236 }
237
238 err := AddFirewallRulesFromConfig(l, false, c, fw)
239 if err != nil {
240 return nil, err
241 }
242
243 err = AddFirewallRulesFromConfig(l, true, c, fw)
244 if err != nil {
245 return nil, err
246 }
247
248 return fw, nil
249 }
250
251 // AddRule properly creates the in memory rule structure for a firewall table.
252 func (f *Firewall) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
253 var (
254 ft *FirewallTable
255 fp firewallPort
256 )
257
258 if incoming {
259 ft = f.InRules
260 } else {
261 ft = f.OutRules
262 }
263
264 switch proto {
265 case firewall.ProtoTCP:
266 fp = ft.TCP
267 case firewall.ProtoUDP:
268 fp = ft.UDP
269 case firewall.ProtoICMP, firewall.ProtoICMPv6:
270 //ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
271 if startPort != firewall.PortAny {
272 f.l.Warn("ignoring port specification for ICMP firewall rule", "startPort", startPort)
273 }
274 startPort = firewall.PortAny
275 endPort = firewall.PortAny
276 fp = ft.ICMP
277 case firewall.ProtoAny:
278 fp = ft.AnyProto
279 default:
280 return fmt.Errorf("unknown protocol %v", proto)
281 }
282
283 // We need this rule string because we generate a hash. Removing this will break firewall reload.
284 ruleString := fmt.Sprintf(
285 "incoming: %v, proto: %v, startPort: %v, endPort: %v, groups: %v, host: %v, ip: %v, localIp: %v, caName: %v, caSha: %s",
286 incoming, proto, startPort, endPort, groups, host, cidr, localCidr, caName, caSha,
287 )
288 f.rules += ruleString + "\n"
289
290 direction := "incoming"
291 if !incoming {
292 direction = "outgoing"
293 }
294 f.l.Info("Firewall rule added",
295 "firewallRule", m{"direction": direction, "proto": proto, "startPort": startPort, "endPort": endPort, "groups": groups, "host": host, "cidr": cidr, "localCidr": localCidr, "caName": caName, "caSha": caSha},
296 )
297
298 return fp.addRule(f, startPort, endPort, groups, host, cidr, localCidr, caName, caSha)
299 }
300
301 // GetRuleHash returns a hash representation of all inbound and outbound rules
302 func (f *Firewall) GetRuleHash() string {
303 sum := sha256.Sum256([]byte(f.rules))
304 return hex.EncodeToString(sum[:])
305 }
306
307 // GetRuleHashFNV returns a uint32 FNV-1 hash representation the rules, for use as a metric value
308 func (f *Firewall) GetRuleHashFNV() uint32 {
309 h := fnv.New32a()
310 h.Write([]byte(f.rules))
311 return h.Sum32()
312 }
313
314 // GetRuleHashes returns both the sha256 and FNV-1 hashes, suitable for logging
315 func (f *Firewall) GetRuleHashes() string {
316 return "SHA:" + f.GetRuleHash() + ",FNV:" + strconv.FormatUint(uint64(f.GetRuleHashFNV()), 10)
317 }
318
319 func AddFirewallRulesFromConfig(l *slog.Logger, inbound bool, c *config.C, fw FirewallInterface) error {
320 var table string
321 if inbound {
322 table = "firewall.inbound"
323 } else {
324 table = "firewall.outbound"
325 }
326
327 r := c.Get(table)
328 if r == nil {
329 return nil
330 }
331
332 rs, ok := r.([]any)
333 if !ok {
334 return fmt.Errorf("%s failed to parse, should be an array of rules", table)
335 }
336
337 for i, t := range rs {
338 r, err := convertRule(l, t, table, i)
339 if err != nil {
340 return fmt.Errorf("%s rule #%v; %s", table, i, err)
341 }
342
343 if r.Code != "" && r.Port != "" {
344 return fmt.Errorf("%s rule #%v; only one of port or code should be provided", table, i)
345 }
346
347 if r.Host == "" && len(r.Groups) == 0 && r.Cidr == "" && r.LocalCidr == "" && r.CAName == "" && r.CASha == "" {
348 return fmt.Errorf("%s rule #%v; at least one of host, group, cidr, local_cidr, ca_name, or ca_sha must be provided", table, i)
349 }
350
351 var sPort, errPort string
352 if r.Code != "" {
353 errPort = "code"
354 sPort = r.Code
355 } else {
356 errPort = "port"
357 sPort = r.Port
358 }
359
360 var proto uint8
361 var startPort, endPort int32
362 switch r.Proto {
363 case "any":
364 proto = firewall.ProtoAny
365 startPort, endPort, err = parsePort(sPort)
366 case "tcp":
367 proto = firewall.ProtoTCP
368 startPort, endPort, err = parsePort(sPort)
369 case "udp":
370 proto = firewall.ProtoUDP
371 startPort, endPort, err = parsePort(sPort)
372 case "icmp":
373 proto = firewall.ProtoICMP
374 startPort = firewall.PortAny
375 endPort = firewall.PortAny
376 if sPort != "" {
377 l.Warn("ignoring port specification for ICMP firewall rule", "port", sPort)
378 }
379 default:
380 return fmt.Errorf("%s rule #%v; proto was not understood; `%s`", table, i, r.Proto)
381 }
382 if err != nil {
383 return fmt.Errorf("%s rule #%v; %s %s", table, i, errPort, err)
384 }
385
386 if r.Cidr != "" && r.Cidr != "any" {
387 _, err = netip.ParsePrefix(r.Cidr)
388 if err != nil {
389 return fmt.Errorf("%s rule #%v; cidr did not parse; %s", table, i, err)
390 }
391 }
392
393 if r.LocalCidr != "" && r.LocalCidr != "any" {
394 _, err = netip.ParsePrefix(r.LocalCidr)
395 if err != nil {
396 return fmt.Errorf("%s rule #%v; local_cidr did not parse; %s", table, i, err)
397 }
398 }
399
400 if warning := r.sanity(); warning != nil {
401 l.Warn("firewall rule sanity check",
402 "table", table,
403 "rule", i,
404 "warning", warning,
405 )
406 }
407
408 err = fw.AddRule(inbound, proto, startPort, endPort, r.Groups, r.Host, r.Cidr, r.LocalCidr, r.CAName, r.CASha)
409 if err != nil {
410 return fmt.Errorf("%s rule #%v; `%s`", table, i, err)
411 }
412 }
413
414 return nil
415 }
416
417 var ErrUnknownNetworkType = errors.New("unknown network type")
418 var ErrPeerRejected = errors.New("remote address is not within a network that we handle")
419 var ErrInvalidRemoteIP = errors.New("remote address is not in remote certificate networks")
420 var ErrInvalidLocalIP = errors.New("local address is not in list of handled local addresses")
421 var ErrNoMatchingRule = errors.New("no matching rule in firewall table")
422
423 // Drop returns an error if the packet should be dropped, explaining why. It
424 // returns nil if the packet should not be dropped.
425 func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) error {
426 // Make sure remote address matches nebula certificate, and determine how to treat it
427 if h.networks == nil {
428 // Simple case: Certificate has one address and no unsafe networks
429 if h.vpnAddrs[0] != fp.RemoteAddr {
430 f.metrics(incoming).droppedRemoteAddr.Inc(1)
431 return ErrInvalidRemoteIP
432 }
433 } else {
434 nwType, ok := h.networks.Lookup(fp.RemoteAddr)
435 if !ok {
436 f.metrics(incoming).droppedRemoteAddr.Inc(1)
437 return ErrInvalidRemoteIP
438 }
439 switch nwType {
440 case NetworkTypeVPN:
441 break // nothing special
442 case NetworkTypeVPNPeer:
443 f.metrics(incoming).droppedRemoteAddr.Inc(1)
444 return ErrPeerRejected // reject for now, one day this may have different FW rules
445 case NetworkTypeUnsafe:
446 break // nothing special, one day this may have different FW rules
447 default:
448 f.metrics(incoming).droppedRemoteAddr.Inc(1)
449 return ErrUnknownNetworkType //should never happen
450 }
451 }
452
453 // Make sure we are supposed to be handling this local ip address
454 if !f.routableNetworks.Contains(fp.LocalAddr) {
455 f.metrics(incoming).droppedLocalAddr.Inc(1)
456 return ErrInvalidLocalIP
457 }
458
459 // Check if we spoke to this tuple, if we did then allow this packet
460 if f.inConns(fp, h, caPool, localCache) {
461 return nil
462 }
463
464 table := f.OutRules
465 if incoming {
466 table = f.InRules
467 }
468
469 // We now know which firewall table to check against
470 if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
471 f.metrics(incoming).droppedNoRule.Inc(1)
472 return ErrNoMatchingRule
473 }
474
475 // We always want to conntrack since it is a faster operation
476 f.addConn(fp, incoming)
477
478 return nil
479 }
480
481 func (f *Firewall) metrics(incoming bool) firewallMetrics {
482 if incoming {
483 return f.incomingMetrics
484 } else {
485 return f.outgoingMetrics
486 }
487 }
488
489 // Destroy cleans up any known cyclical references so the object can be freed by GC. This should be called if a new
490 // firewall object is created
491 func (f *Firewall) Destroy() {
492 //TODO: clean references if/when needed
493 }
494
495 func (f *Firewall) EmitStats() {
496 conntrack := f.Conntrack
497 conntrack.Lock()
498 conntrackCount := len(conntrack.Conns)
499 conntrack.Unlock()
500 metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
501 metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
502 metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
503 }
504
505 func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
506 if localCache != nil {
507 if _, ok := localCache[fp]; ok {
508 return true
509 }
510 }
511 conntrack := f.Conntrack
512 conntrack.Lock()
513
514 // Purge every time we test
515 ep, has := conntrack.TimerWheel.Purge()
516 if has {
517 f.evict(ep)
518 }
519
520 c, ok := conntrack.Conns[fp]
521
522 if !ok {
523 conntrack.Unlock()
524 return false
525 }
526
527 if c.rulesVersion != f.rulesVersion {
528 // This conntrack entry was for an older rule set, validate
529 // it still passes with the current rule set
530 table := f.OutRules
531 if c.incoming {
532 table = f.InRules
533 }
534
535 // We now know which firewall table to check against
536 if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
537 if f.l.Enabled(context.Background(), slog.LevelDebug) {
538 h.logger(f.l).Debug("dropping old conntrack entry, does not match new ruleset",
539 "fwPacket", fp,
540 "incoming", c.incoming,
541 "rulesVersion", f.rulesVersion,
542 "oldRulesVersion", c.rulesVersion,
543 )
544 }
545 delete(conntrack.Conns, fp)
546 conntrack.Unlock()
547 return false
548 }
549
550 if f.l.Enabled(context.Background(), slog.LevelDebug) {
551 h.logger(f.l).Debug("keeping old conntrack entry, does match new ruleset",
552 "fwPacket", fp,
553 "incoming", c.incoming,
554 "rulesVersion", f.rulesVersion,
555 "oldRulesVersion", c.rulesVersion,
556 )
557 }
558
559 c.rulesVersion = f.rulesVersion
560 }
561
562 switch fp.Protocol {
563 case firewall.ProtoTCP:
564 c.Expires = time.Now().Add(f.TCPTimeout)
565 case firewall.ProtoUDP:
566 c.Expires = time.Now().Add(f.UDPTimeout)
567 default:
568 c.Expires = time.Now().Add(f.DefaultTimeout)
569 }
570
571 conntrack.Unlock()
572
573 if localCache != nil {
574 localCache[fp] = struct{}{}
575 }
576
577 return true
578 }
579
580 func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
581 var timeout time.Duration
582 c := &conn{}
583
584 switch fp.Protocol {
585 case firewall.ProtoTCP:
586 timeout = f.TCPTimeout
587 case firewall.ProtoUDP:
588 timeout = f.UDPTimeout
589 default:
590 timeout = f.DefaultTimeout
591 }
592
593 conntrack := f.Conntrack
594 conntrack.Lock()
595 if _, ok := conntrack.Conns[fp]; !ok {
596 conntrack.TimerWheel.Advance(time.Now())
597 conntrack.TimerWheel.Add(fp, timeout)
598 }
599
600 // Record which rulesVersion allowed this connection, so we can retest after
601 // firewall reload
602 c.incoming = incoming
603 c.rulesVersion = f.rulesVersion
604 c.Expires = time.Now().Add(timeout)
605 conntrack.Conns[fp] = c
606 conntrack.Unlock()
607 }
608
609 // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
610 // Caller must own the connMutex lock!
611 func (f *Firewall) evict(p firewall.Packet) {
612 // Are we still tracking this conn?
613 conntrack := f.Conntrack
614 t, ok := conntrack.Conns[p]
615 if !ok {
616 return
617 }
618
619 newT := t.Expires.Sub(time.Now())
620
621 // Timeout is in the future, re-add the timer
622 if newT > 0 {
623 conntrack.TimerWheel.Advance(time.Now())
624 conntrack.TimerWheel.Add(p, newT)
625 return
626 }
627
628 // This conn is done
629 delete(conntrack.Conns, p)
630 }
631
632 func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
633 if ft.AnyProto.match(p, incoming, c, caPool) {
634 return true
635 }
636
637 switch p.Protocol {
638 case firewall.ProtoTCP:
639 if ft.TCP.match(p, incoming, c, caPool) {
640 return true
641 }
642 case firewall.ProtoUDP:
643 if ft.UDP.match(p, incoming, c, caPool) {
644 return true
645 }
646 case firewall.ProtoICMP, firewall.ProtoICMPv6:
647 if ft.ICMP.match(p, incoming, c, caPool) {
648 return true
649 }
650 }
651
652 return false
653 }
654
655 func (fp firewallPort) addRule(f *Firewall, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
656 if startPort > endPort {
657 return fmt.Errorf("start port was lower than end port")
658 }
659
660 for i := startPort; i <= endPort; i++ {
661 if _, ok := fp[i]; !ok {
662 fp[i] = &FirewallCA{
663 CANames: make(map[string]*FirewallRule),
664 CAShas: make(map[string]*FirewallRule),
665 }
666 }
667
668 if err := fp[i].addRule(f, groups, host, cidr, localCidr, caName, caSha); err != nil {
669 return err
670 }
671 }
672
673 return nil
674 }
675
676 func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
677 // We don't have any allowed ports, bail
678 if fp == nil {
679 return false
680 }
681
682 // this branch is here to catch traffic from FirewallTable.Any.match and FirewallTable.ICMP.match
683 if p.Protocol == firewall.ProtoICMP || p.Protocol == firewall.ProtoICMPv6 {
684 // port numbers are re-used for connection tracking of ICMP,
685 // but we don't want to actually filter on them.
686 return fp[firewall.PortAny].match(p, c, caPool)
687 }
688
689 var port int32
690
691 if p.Fragment {
692 port = firewall.PortFragment
693 } else if incoming {
694 port = int32(p.LocalPort)
695 } else {
696 port = int32(p.RemotePort)
697 }
698
699 if fp[port].match(p, c, caPool) {
700 return true
701 }
702
703 return fp[firewall.PortAny].match(p, c, caPool)
704 }
705
706 func (fc *FirewallCA) addRule(f *Firewall, groups []string, host string, cidr, localCidr, caName, caSha string) error {
707 fr := func() *FirewallRule {
708 return &FirewallRule{
709 Hosts: make(map[string]*firewallLocalCIDR),
710 Groups: make([]*firewallGroups, 0),
711 CIDR: new(bart.Table[*firewallLocalCIDR]),
712 }
713 }
714
715 if caSha == "" && caName == "" {
716 if fc.Any == nil {
717 fc.Any = fr()
718 }
719
720 return fc.Any.addRule(f, groups, host, cidr, localCidr)
721 }
722
723 if caSha != "" {
724 if _, ok := fc.CAShas[caSha]; !ok {
725 fc.CAShas[caSha] = fr()
726 }
727 err := fc.CAShas[caSha].addRule(f, groups, host, cidr, localCidr)
728 if err != nil {
729 return err
730 }
731 }
732
733 if caName != "" {
734 if _, ok := fc.CANames[caName]; !ok {
735 fc.CANames[caName] = fr()
736 }
737 err := fc.CANames[caName].addRule(f, groups, host, cidr, localCidr)
738 if err != nil {
739 return err
740 }
741 }
742
743 return nil
744 }
745
746 func (fc *FirewallCA) match(p firewall.Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
747 if fc == nil {
748 return false
749 }
750
751 if fc.Any.match(p, c) {
752 return true
753 }
754
755 if t, ok := fc.CAShas[c.Certificate.Issuer()]; ok {
756 if t.match(p, c) {
757 return true
758 }
759 }
760
761 s, err := caPool.GetCAForCert(c.Certificate)
762 if err != nil {
763 return false
764 }
765
766 return fc.CANames[s.Certificate.Name()].match(p, c)
767 }
768
769 func (fr *FirewallRule) addRule(f *Firewall, groups []string, host, cidr, localCidr string) error {
770 flc := func() *firewallLocalCIDR {
771 return &firewallLocalCIDR{
772 LocalCIDR: new(bart.Lite),
773 }
774 }
775
776 if fr.isAny(groups, host, cidr) {
777 if fr.Any == nil {
778 fr.Any = flc()
779 }
780
781 return fr.Any.addRule(f, localCidr)
782 }
783
784 if len(groups) > 0 {
785 nlc := flc()
786 err := nlc.addRule(f, localCidr)
787 if err != nil {
788 return err
789 }
790
791 fr.Groups = append(fr.Groups, &firewallGroups{
792 Groups: groups,
793 LocalCIDR: nlc,
794 })
795 }
796
797 if host != "" {
798 nlc := fr.Hosts[host]
799 if nlc == nil {
800 nlc = flc()
801 }
802 err := nlc.addRule(f, localCidr)
803 if err != nil {
804 return err
805 }
806 fr.Hosts[host] = nlc
807 }
808
809 if cidr != "" {
810 c, err := netip.ParsePrefix(cidr)
811 if err != nil {
812 return err
813 }
814 nlc, _ := fr.CIDR.Get(c)
815 if nlc == nil {
816 nlc = flc()
817 }
818 err = nlc.addRule(f, localCidr)
819 if err != nil {
820 return err
821 }
822 fr.CIDR.Insert(c, nlc)
823 }
824
825 return nil
826 }
827
828 func (fr *FirewallRule) isAny(groups []string, host string, cidr string) bool {
829 if len(groups) == 0 && host == "" && cidr == "" {
830 return true
831 }
832
833 if slices.Contains(groups, "any") {
834 return true
835 }
836
837 if host == "any" {
838 return true
839 }
840
841 if cidr == "any" {
842 return true
843 }
844
845 return false
846 }
847
848 func (fr *FirewallRule) match(p firewall.Packet, c *cert.CachedCertificate) bool {
849 if fr == nil {
850 return false
851 }
852
853 // Shortcut path for if groups, hosts, or cidr contained an `any`
854 if fr.Any.match(p, c) {
855 return true
856 }
857
858 // Need any of group, host, or cidr to match
859 for _, sg := range fr.Groups {
860 found := false
861
862 for _, g := range sg.Groups {
863 if _, ok := c.InvertedGroups[g]; !ok {
864 found = false
865 break
866 }
867
868 found = true
869 }
870
871 if found && sg.LocalCIDR.match(p, c) {
872 return true
873 }
874 }
875
876 if fr.Hosts != nil {
877 if flc, ok := fr.Hosts[c.Certificate.Name()]; ok {
878 if flc.match(p, c) {
879 return true
880 }
881 }
882 }
883
884 for _, v := range fr.CIDR.Supernets(netip.PrefixFrom(p.RemoteAddr, p.RemoteAddr.BitLen())) {
885 if v.match(p, c) {
886 return true
887 }
888 }
889
890 return false
891 }
892
893 func (flc *firewallLocalCIDR) addRule(f *Firewall, localCidr string) error {
894 if localCidr == "any" {
895 flc.Any = true
896 return nil
897 }
898
899 if localCidr == "" {
900 if len(f.unsafeNetworks) == 0 || f.defaultLocalCIDRAny {
901 flc.Any = true
902 return nil
903 }
904
905 for _, network := range f.assignedNetworks {
906 flc.LocalCIDR.Insert(network)
907 }
908 return nil
909
910 }
911
912 c, err := netip.ParsePrefix(localCidr)
913 if err != nil {
914 return err
915 }
916 flc.LocalCIDR.Insert(c)
917 return nil
918 }
919
920 func (flc *firewallLocalCIDR) match(p firewall.Packet, c *cert.CachedCertificate) bool {
921 if flc == nil {
922 return false
923 }
924
925 if flc.Any {
926 return true
927 }
928
929 return flc.LocalCIDR.Contains(p.LocalAddr)
930 }
931
932 type rule struct {
933 Port string
934 Code string
935 Proto string
936 Host string
937 Groups []string
938 Cidr string
939 LocalCidr string
940 CAName string
941 CASha string
942 }
943
944 func convertRule(l *slog.Logger, p any, table string, i int) (rule, error) {
945 r := rule{}
946
947 m, ok := p.(map[string]any)
948 if !ok {
949 return r, errors.New("could not parse rule")
950 }
951
952 toString := func(k string, m map[string]any) string {
953 v, ok := m[k]
954 if !ok {
955 return ""
956 }
957 return fmt.Sprintf("%v", v)
958 }
959
960 r.Port = toString("port", m)
961 r.Code = toString("code", m)
962 r.Proto = toString("proto", m)
963 r.Host = toString("host", m)
964 r.Cidr = toString("cidr", m)
965 r.LocalCidr = toString("local_cidr", m)
966 r.CAName = toString("ca_name", m)
967 r.CASha = toString("ca_sha", m)
968
969 // Make sure group isn't an array
970 if v, ok := m["group"].([]any); ok {
971 if len(v) > 1 {
972 return r, errors.New("group should contain a single value, an array with more than one entry was provided")
973 }
974
975 l.Warn("group was an array with a single value, converting to simple value",
976 "table", table,
977 "rule", i,
978 )
979 m["group"] = v[0]
980 }
981
982 singleGroup := toString("group", m)
983
984 if rg, ok := m["groups"]; ok {
985 switch reflect.TypeOf(rg).Kind() {
986 case reflect.Slice:
987 v := reflect.ValueOf(rg)
988 r.Groups = make([]string, v.Len())
989 for i := 0; i < v.Len(); i++ {
990 r.Groups[i] = v.Index(i).Interface().(string)
991 }
992 case reflect.String:
993 r.Groups = []string{rg.(string)}
994 default:
995 r.Groups = []string{fmt.Sprintf("%v", rg)}
996 }
997 }
998
999 //flatten group vs groups
1000 if singleGroup != "" {
1001 // Check if we have both groups and group provided in the rule config
1002 if len(r.Groups) > 0 {
1003 return r, fmt.Errorf("only one of group or groups should be defined, both provided")
1004 }
1005 r.Groups = []string{singleGroup}
1006 }
1007
1008 return r, nil
1009 }
1010
1011 // sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
1012 // rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
1013 func (r *rule) sanity() error {
1014 //port, proto, local_cidr are AND, no need to check here
1015 //ca_sha and ca_name don't have a wildcard value, no need to check here
1016 groupsEmpty := len(r.Groups) == 0
1017 hostEmpty := r.Host == ""
1018 cidrEmpty := r.Cidr == ""
1019
1020 if (groupsEmpty && hostEmpty && cidrEmpty) == true {
1021 return nil //no content!
1022 }
1023
1024 groupsHasAny := slices.Contains(r.Groups, "any")
1025 if groupsHasAny && len(r.Groups) > 1 {
1026 return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the other groups specified", r.Groups)
1027 }
1028
1029 if r.Host == "any" {
1030 if !groupsEmpty {
1031 return fmt.Errorf("groups specified as %s, but host=any will match any host, regardless of groups", r.Groups)
1032 }
1033
1034 if !cidrEmpty {
1035 return fmt.Errorf("cidr specified as %s, but host=any will match any host, regardless of cidr", r.Cidr)
1036 }
1037 }
1038
1039 if groupsHasAny {
1040 if !hostEmpty && r.Host != "any" {
1041 return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified host %s", r.Groups, r.Host)
1042 }
1043 if !cidrEmpty {
1044 return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified cidr %s", r.Groups, r.Cidr)
1045 }
1046 }
1047
1048 if r.Code != "" {
1049 return fmt.Errorf("code specified as [%s]. Support for 'code' will be dropped in a future release, as it has never been functional", r.Code)
1050 }
1051
1052 //todo alert on cidr-any
1053
1054 return nil
1055 }
1056
1057 func parsePort(s string) (int32, int32, error) {
1058 const notAPort int32 = -2
1059 if s == "any" {
1060 return firewall.PortAny, firewall.PortAny, nil
1061 }
1062 if s == "fragment" {
1063 return firewall.PortFragment, firewall.PortFragment, nil
1064 }
1065 if !strings.Contains(s, `-`) {
1066 rPort, err := parsePortValue("", s)
1067 if err != nil {
1068 return notAPort, notAPort, err
1069 }
1070 return rPort, rPort, nil
1071 }
1072
1073 sPorts := strings.SplitN(s, `-`, 2)
1074 for i := range sPorts {
1075 sPorts[i] = strings.Trim(sPorts[i], " ")
1076 }
1077 if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
1078 return notAPort, notAPort, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
1079 }
1080
1081 startPort, err := parsePortValue("beginning range ", sPorts[0])
1082 if err != nil {
1083 return notAPort, notAPort, err
1084 }
1085
1086 endPort, err := parsePortValue("ending range ", sPorts[1])
1087 if err != nil {
1088 return notAPort, notAPort, err
1089 }
1090
1091 if startPort == firewall.PortAny {
1092 endPort = firewall.PortAny
1093 }
1094
1095 return startPort, endPort, nil
1096 }
1097
1098 // parsePortValue accepts a base-10 decimal in [0, 65535] and returns it
1099 // widened to int32. Using strconv.ParseUint with bitSize 16 rejects
1100 // negative input, out-of-range input (>65535), and any non-decimal byte
1101 // by construction, so the int32 widening that follows is provably safe
1102 // and cannot collide with firewall.PortAny (0) or firewall.PortFragment
1103 // (-1) via integer truncation.
1104 //
1105 // prefix is prepended to both error messages so callers can disambiguate
1106 // the single-port path (prefix="") from the range bounds (prefix="beginning
1107 // range " / "ending range "), preserving the historical error strings.
1108 func parsePortValue(prefix, s string) (int32, error) {
1109 n, err := strconv.ParseUint(s, 10, 16)
1110 if err == nil {
1111 return int32(n), nil
1112 }
1113 if errors.Is(err, strconv.ErrRange) {
1114 return 0, fmt.Errorf("%sout of range [0,65535]; `%s`", prefix, s)
1115 }
1116 return 0, fmt.Errorf("%swas not a number; `%s`", prefix, s)
1117 }