firewall.go 30 KB

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