firewall.go 28 KB

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