firewall.go 29 KB

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