firewall.go 28 KB

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