firewall.go 29 KB

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