firewall.go 27 KB

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