firewall.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. InLogDrop bool
  41. OutLogDrop bool
  42. //TODO: we should have many more options for TCP, an option for ICMP, and mimic the kernel a bit better
  43. // https://www.kernel.org/doc/Documentation/networking/nf_conntrack-sysctl.txt
  44. TCPTimeout time.Duration //linux: 5 days max
  45. UDPTimeout time.Duration //linux: 180s max
  46. DefaultTimeout time.Duration //linux: 600s
  47. // routableNetworks describes the vpn addresses as well as any unsafe networks issued to us in the certificate.
  48. // The vpn addresses are a full bit match while the unsafe networks only match the prefix
  49. routableNetworks *bart.Lite
  50. // assignedNetworks is a list of vpn networks assigned to us in the certificate.
  51. assignedNetworks []netip.Prefix
  52. hasUnsafeNetworks bool
  53. rules string
  54. rulesVersion uint16
  55. defaultLocalCIDRAny bool
  56. incomingMetrics firewallMetrics
  57. outgoingMetrics firewallMetrics
  58. l *logrus.Logger
  59. }
  60. type firewallMetrics struct {
  61. droppedLocalAddr metrics.Counter
  62. droppedRemoteAddr metrics.Counter
  63. droppedNoRule metrics.Counter
  64. }
  65. type FirewallConntrack struct {
  66. sync.Mutex
  67. Conns map[firewall.Packet]*conn
  68. TimerWheel *TimerWheel[firewall.Packet]
  69. }
  70. // FirewallTable is the entry point for a rule, the evaluation order is:
  71. // Proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR)
  72. type FirewallTable struct {
  73. TCP firewallPort
  74. UDP firewallPort
  75. ICMP firewallPort
  76. AnyProto firewallPort
  77. }
  78. func newFirewallTable() *FirewallTable {
  79. return &FirewallTable{
  80. TCP: firewallPort{},
  81. UDP: firewallPort{},
  82. ICMP: firewallPort{},
  83. AnyProto: firewallPort{},
  84. }
  85. }
  86. type FirewallCA struct {
  87. Any *FirewallRule
  88. CANames map[string]*FirewallRule
  89. CAShas map[string]*FirewallRule
  90. }
  91. type FirewallRule struct {
  92. // Any makes Hosts, Groups, and CIDR irrelevant
  93. Any *firewallLocalCIDR
  94. Hosts map[string]*firewallLocalCIDR
  95. Groups []*firewallGroups
  96. CIDR *bart.Table[*firewallLocalCIDR]
  97. }
  98. type firewallGroups struct {
  99. Groups []string
  100. LocalCIDR *firewallLocalCIDR
  101. }
  102. // Even though ports are uint16, int32 maps are faster for lookup
  103. // Plus we can use `-1` for fragment rules
  104. type firewallPort map[int32]*FirewallCA
  105. type firewallLocalCIDR struct {
  106. Any bool
  107. LocalCIDR *bart.Lite
  108. }
  109. // NewFirewall creates a new Firewall object. A TimerWheel is created for you from the provided timeouts.
  110. // The certificate provided should be the highest version loaded in memory.
  111. func NewFirewall(l *logrus.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c cert.Certificate) *Firewall {
  112. //TODO: error on 0 duration
  113. var tmin, tmax time.Duration
  114. if tcpTimeout < UDPTimeout {
  115. tmin = tcpTimeout
  116. tmax = UDPTimeout
  117. } else {
  118. tmin = UDPTimeout
  119. tmax = tcpTimeout
  120. }
  121. if defaultTimeout < tmin {
  122. tmin = defaultTimeout
  123. } else if defaultTimeout > tmax {
  124. tmax = defaultTimeout
  125. }
  126. routableNetworks := new(bart.Lite)
  127. var assignedNetworks []netip.Prefix
  128. for _, network := range c.Networks() {
  129. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  130. routableNetworks.Insert(nprefix)
  131. assignedNetworks = append(assignedNetworks, network)
  132. }
  133. hasUnsafeNetworks := false
  134. for _, n := range c.UnsafeNetworks() {
  135. routableNetworks.Insert(n)
  136. hasUnsafeNetworks = true
  137. }
  138. return &Firewall{
  139. Conntrack: &FirewallConntrack{
  140. Conns: make(map[firewall.Packet]*conn),
  141. TimerWheel: NewTimerWheel[firewall.Packet](tmin, tmax),
  142. },
  143. InRules: newFirewallTable(),
  144. OutRules: 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. inboundAction := c.GetString("firewall.inbound_action", "drop")
  182. switch inboundAction {
  183. case "reject":
  184. fw.InSendReject = true
  185. fw.InLogDrop = true //todo
  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. fw.OutLogDrop = true //todo
  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. type DropHandler func(fp firewall.Packet, incoming bool, h *HostInfo, err error)
  344. // Drop returns an error if the packet should be dropped, explaining why. It
  345. // returns nil if the packet should not be dropped.
  346. func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache, onDrop DropHandler) error {
  347. // Check if we spoke to this tuple, if we did then allow this packet
  348. if f.inConns(fp, h, caPool, localCache) {
  349. return nil
  350. }
  351. // Make sure remote address matches nebula certificate, and determine how to treat it
  352. if h.networks == nil {
  353. // Simple case: Certificate has one address and no unsafe networks
  354. if h.vpnAddrs[0] != fp.RemoteAddr {
  355. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  356. return ErrInvalidRemoteIP
  357. }
  358. } else {
  359. nwType, ok := h.networks.Lookup(fp.RemoteAddr)
  360. if !ok {
  361. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  362. return ErrInvalidRemoteIP
  363. }
  364. switch nwType {
  365. case NetworkTypeVPN:
  366. break // nothing special
  367. case NetworkTypeVPNPeer:
  368. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  369. return ErrPeerRejected // reject for now, one day this may have different FW rules
  370. case NetworkTypeUnsafe:
  371. break // nothing special, one day this may have different FW rules
  372. default:
  373. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  374. return ErrUnknownNetworkType //should never happen
  375. }
  376. }
  377. // Make sure we are supposed to be handling this local ip address
  378. if !f.routableNetworks.Contains(fp.LocalAddr) {
  379. f.metrics(incoming).droppedLocalAddr.Inc(1)
  380. return ErrInvalidLocalIP
  381. }
  382. table := f.OutRules
  383. if incoming {
  384. table = f.InRules
  385. }
  386. // We now know which firewall table to check against
  387. if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
  388. f.metrics(incoming).droppedNoRule.Inc(1)
  389. return ErrNoMatchingRule
  390. }
  391. // We always want to conntrack since it is a faster operation
  392. f.addConn(fp, incoming)
  393. return nil
  394. }
  395. func (f *Firewall) metrics(incoming bool) firewallMetrics {
  396. if incoming {
  397. return f.incomingMetrics
  398. } else {
  399. return f.outgoingMetrics
  400. }
  401. }
  402. // Destroy cleans up any known cyclical references so the object can be free'd my GC. This should be called if a new
  403. // firewall object is created
  404. func (f *Firewall) Destroy() {
  405. //TODO: clean references if/when needed
  406. }
  407. func (f *Firewall) EmitStats() {
  408. conntrack := f.Conntrack
  409. conntrack.Lock()
  410. conntrackCount := len(conntrack.Conns)
  411. conntrack.Unlock()
  412. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  413. metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
  414. metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
  415. }
  416. func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
  417. if localCache != nil {
  418. if _, ok := localCache[fp]; ok {
  419. return true
  420. }
  421. }
  422. conntrack := f.Conntrack
  423. conntrack.Lock()
  424. // Purge every time we test
  425. ep, has := conntrack.TimerWheel.Purge()
  426. if has {
  427. f.evict(ep)
  428. }
  429. c, ok := conntrack.Conns[fp]
  430. if !ok {
  431. conntrack.Unlock()
  432. return false
  433. }
  434. if c.rulesVersion != f.rulesVersion {
  435. // This conntrack entry was for an older rule set, validate
  436. // it still passes with the current rule set
  437. table := f.OutRules
  438. if c.incoming {
  439. table = f.InRules
  440. }
  441. // We now know which firewall table to check against
  442. if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
  443. if f.l.Level >= logrus.DebugLevel {
  444. h.logger(f.l).
  445. WithField("fwPacket", fp).
  446. WithField("incoming", c.incoming).
  447. WithField("rulesVersion", f.rulesVersion).
  448. WithField("oldRulesVersion", c.rulesVersion).
  449. Debugln("dropping old conntrack entry, does not match new ruleset")
  450. }
  451. delete(conntrack.Conns, fp)
  452. conntrack.Unlock()
  453. return false
  454. }
  455. if f.l.Level >= logrus.DebugLevel {
  456. h.logger(f.l).
  457. WithField("fwPacket", fp).
  458. WithField("incoming", c.incoming).
  459. WithField("rulesVersion", f.rulesVersion).
  460. WithField("oldRulesVersion", c.rulesVersion).
  461. Debugln("keeping old conntrack entry, does match new ruleset")
  462. }
  463. c.rulesVersion = f.rulesVersion
  464. }
  465. switch fp.Protocol {
  466. case firewall.ProtoTCP:
  467. c.Expires = time.Now().Add(f.TCPTimeout)
  468. case firewall.ProtoUDP:
  469. c.Expires = time.Now().Add(f.UDPTimeout)
  470. default:
  471. c.Expires = time.Now().Add(f.DefaultTimeout)
  472. }
  473. conntrack.Unlock()
  474. if localCache != nil {
  475. localCache[fp] = struct{}{}
  476. }
  477. return true
  478. }
  479. func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
  480. var timeout time.Duration
  481. c := &conn{}
  482. switch fp.Protocol {
  483. case firewall.ProtoTCP:
  484. timeout = f.TCPTimeout
  485. case firewall.ProtoUDP:
  486. timeout = f.UDPTimeout
  487. default:
  488. timeout = f.DefaultTimeout
  489. }
  490. conntrack := f.Conntrack
  491. conntrack.Lock()
  492. if _, ok := conntrack.Conns[fp]; !ok {
  493. conntrack.TimerWheel.Advance(time.Now())
  494. conntrack.TimerWheel.Add(fp, timeout)
  495. }
  496. // Record which rulesVersion allowed this connection, so we can retest after
  497. // firewall reload
  498. c.incoming = incoming
  499. c.rulesVersion = f.rulesVersion
  500. c.Expires = time.Now().Add(timeout)
  501. conntrack.Conns[fp] = c
  502. conntrack.Unlock()
  503. }
  504. // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
  505. // Caller must own the connMutex lock!
  506. func (f *Firewall) evict(p firewall.Packet) {
  507. // Are we still tracking this conn?
  508. conntrack := f.Conntrack
  509. t, ok := conntrack.Conns[p]
  510. if !ok {
  511. return
  512. }
  513. newT := t.Expires.Sub(time.Now())
  514. // Timeout is in the future, re-add the timer
  515. if newT > 0 {
  516. conntrack.TimerWheel.Advance(time.Now())
  517. conntrack.TimerWheel.Add(p, newT)
  518. return
  519. }
  520. // This conn is done
  521. delete(conntrack.Conns, p)
  522. }
  523. func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  524. if ft.AnyProto.match(p, incoming, c, caPool) {
  525. return true
  526. }
  527. switch p.Protocol {
  528. case firewall.ProtoTCP:
  529. if ft.TCP.match(p, incoming, c, caPool) {
  530. return true
  531. }
  532. case firewall.ProtoUDP:
  533. if ft.UDP.match(p, incoming, c, caPool) {
  534. return true
  535. }
  536. case firewall.ProtoICMP, firewall.ProtoICMPv6:
  537. if ft.ICMP.match(p, incoming, c, caPool) {
  538. return true
  539. }
  540. }
  541. return false
  542. }
  543. func (fp firewallPort) addRule(f *Firewall, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
  544. if startPort > endPort {
  545. return fmt.Errorf("start port was lower than end port")
  546. }
  547. for i := startPort; i <= endPort; i++ {
  548. if _, ok := fp[i]; !ok {
  549. fp[i] = &FirewallCA{
  550. CANames: make(map[string]*FirewallRule),
  551. CAShas: make(map[string]*FirewallRule),
  552. }
  553. }
  554. if err := fp[i].addRule(f, groups, host, cidr, localCidr, caName, caSha); err != nil {
  555. return err
  556. }
  557. }
  558. return nil
  559. }
  560. func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  561. // We don't have any allowed ports, bail
  562. if fp == nil {
  563. return false
  564. }
  565. var port int32
  566. if p.Fragment {
  567. port = firewall.PortFragment
  568. } else if incoming {
  569. port = int32(p.LocalPort)
  570. } else {
  571. port = int32(p.RemotePort)
  572. }
  573. if fp[port].match(p, c, caPool) {
  574. return true
  575. }
  576. return fp[firewall.PortAny].match(p, c, caPool)
  577. }
  578. func (fc *FirewallCA) addRule(f *Firewall, groups []string, host string, cidr, localCidr, caName, caSha string) error {
  579. fr := func() *FirewallRule {
  580. return &FirewallRule{
  581. Hosts: make(map[string]*firewallLocalCIDR),
  582. Groups: make([]*firewallGroups, 0),
  583. CIDR: new(bart.Table[*firewallLocalCIDR]),
  584. }
  585. }
  586. if caSha == "" && caName == "" {
  587. if fc.Any == nil {
  588. fc.Any = fr()
  589. }
  590. return fc.Any.addRule(f, groups, host, cidr, localCidr)
  591. }
  592. if caSha != "" {
  593. if _, ok := fc.CAShas[caSha]; !ok {
  594. fc.CAShas[caSha] = fr()
  595. }
  596. err := fc.CAShas[caSha].addRule(f, groups, host, cidr, localCidr)
  597. if err != nil {
  598. return err
  599. }
  600. }
  601. if caName != "" {
  602. if _, ok := fc.CANames[caName]; !ok {
  603. fc.CANames[caName] = fr()
  604. }
  605. err := fc.CANames[caName].addRule(f, groups, host, cidr, localCidr)
  606. if err != nil {
  607. return err
  608. }
  609. }
  610. return nil
  611. }
  612. func (fc *FirewallCA) match(p firewall.Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  613. if fc == nil {
  614. return false
  615. }
  616. if fc.Any.match(p, c) {
  617. return true
  618. }
  619. if t, ok := fc.CAShas[c.Certificate.Issuer()]; ok {
  620. if t.match(p, c) {
  621. return true
  622. }
  623. }
  624. s, err := caPool.GetCAForCert(c.Certificate)
  625. if err != nil {
  626. return false
  627. }
  628. return fc.CANames[s.Certificate.Name()].match(p, c)
  629. }
  630. func (fr *FirewallRule) addRule(f *Firewall, groups []string, host, cidr, localCidr string) error {
  631. flc := func() *firewallLocalCIDR {
  632. return &firewallLocalCIDR{
  633. LocalCIDR: new(bart.Lite),
  634. }
  635. }
  636. if fr.isAny(groups, host, cidr) {
  637. if fr.Any == nil {
  638. fr.Any = flc()
  639. }
  640. return fr.Any.addRule(f, localCidr)
  641. }
  642. if len(groups) > 0 {
  643. nlc := flc()
  644. err := nlc.addRule(f, localCidr)
  645. if err != nil {
  646. return err
  647. }
  648. fr.Groups = append(fr.Groups, &firewallGroups{
  649. Groups: groups,
  650. LocalCIDR: nlc,
  651. })
  652. }
  653. if host != "" {
  654. nlc := fr.Hosts[host]
  655. if nlc == nil {
  656. nlc = flc()
  657. }
  658. err := nlc.addRule(f, localCidr)
  659. if err != nil {
  660. return err
  661. }
  662. fr.Hosts[host] = nlc
  663. }
  664. if cidr != "" {
  665. c, err := netip.ParsePrefix(cidr)
  666. if err != nil {
  667. return err
  668. }
  669. nlc, _ := fr.CIDR.Get(c)
  670. if nlc == nil {
  671. nlc = flc()
  672. }
  673. err = nlc.addRule(f, localCidr)
  674. if err != nil {
  675. return err
  676. }
  677. fr.CIDR.Insert(c, nlc)
  678. }
  679. return nil
  680. }
  681. func (fr *FirewallRule) isAny(groups []string, host string, cidr string) bool {
  682. if len(groups) == 0 && host == "" && cidr == "" {
  683. return true
  684. }
  685. for _, group := range groups {
  686. if group == "any" {
  687. return true
  688. }
  689. }
  690. if host == "any" {
  691. return true
  692. }
  693. if cidr == "any" {
  694. return true
  695. }
  696. return false
  697. }
  698. func (fr *FirewallRule) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  699. if fr == nil {
  700. return false
  701. }
  702. // Shortcut path for if groups, hosts, or cidr contained an `any`
  703. if fr.Any.match(p, c) {
  704. return true
  705. }
  706. // Need any of group, host, or cidr to match
  707. for _, sg := range fr.Groups {
  708. found := false
  709. for _, g := range sg.Groups {
  710. if _, ok := c.InvertedGroups[g]; !ok {
  711. found = false
  712. break
  713. }
  714. found = true
  715. }
  716. if found && sg.LocalCIDR.match(p, c) {
  717. return true
  718. }
  719. }
  720. if fr.Hosts != nil {
  721. if flc, ok := fr.Hosts[c.Certificate.Name()]; ok {
  722. if flc.match(p, c) {
  723. return true
  724. }
  725. }
  726. }
  727. for _, v := range fr.CIDR.Supernets(netip.PrefixFrom(p.RemoteAddr, p.RemoteAddr.BitLen())) {
  728. if v.match(p, c) {
  729. return true
  730. }
  731. }
  732. return false
  733. }
  734. func (flc *firewallLocalCIDR) addRule(f *Firewall, localCidr string) error {
  735. if localCidr == "any" {
  736. flc.Any = true
  737. return nil
  738. }
  739. if localCidr == "" {
  740. if !f.hasUnsafeNetworks || f.defaultLocalCIDRAny {
  741. flc.Any = true
  742. return nil
  743. }
  744. for _, network := range f.assignedNetworks {
  745. flc.LocalCIDR.Insert(network)
  746. }
  747. return nil
  748. }
  749. c, err := netip.ParsePrefix(localCidr)
  750. if err != nil {
  751. return err
  752. }
  753. flc.LocalCIDR.Insert(c)
  754. return nil
  755. }
  756. func (flc *firewallLocalCIDR) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  757. if flc == nil {
  758. return false
  759. }
  760. if flc.Any {
  761. return true
  762. }
  763. return flc.LocalCIDR.Contains(p.LocalAddr)
  764. }
  765. type rule struct {
  766. Port string
  767. Code string
  768. Proto string
  769. Host string
  770. Groups []string
  771. Cidr string
  772. LocalCidr string
  773. CAName string
  774. CASha string
  775. }
  776. func convertRule(l *logrus.Logger, p any, table string, i int) (rule, error) {
  777. r := rule{}
  778. m, ok := p.(map[string]any)
  779. if !ok {
  780. return r, errors.New("could not parse rule")
  781. }
  782. toString := func(k string, m map[string]any) string {
  783. v, ok := m[k]
  784. if !ok {
  785. return ""
  786. }
  787. return fmt.Sprintf("%v", v)
  788. }
  789. r.Port = toString("port", m)
  790. r.Code = toString("code", m)
  791. r.Proto = toString("proto", m)
  792. r.Host = toString("host", m)
  793. r.Cidr = toString("cidr", m)
  794. r.LocalCidr = toString("local_cidr", m)
  795. r.CAName = toString("ca_name", m)
  796. r.CASha = toString("ca_sha", m)
  797. // Make sure group isn't an array
  798. if v, ok := m["group"].([]any); ok {
  799. if len(v) > 1 {
  800. return r, errors.New("group should contain a single value, an array with more than one entry was provided")
  801. }
  802. l.Warnf("%s rule #%v; group was an array with a single value, converting to simple value", table, i)
  803. m["group"] = v[0]
  804. }
  805. singleGroup := toString("group", m)
  806. if rg, ok := m["groups"]; ok {
  807. switch reflect.TypeOf(rg).Kind() {
  808. case reflect.Slice:
  809. v := reflect.ValueOf(rg)
  810. r.Groups = make([]string, v.Len())
  811. for i := 0; i < v.Len(); i++ {
  812. r.Groups[i] = v.Index(i).Interface().(string)
  813. }
  814. case reflect.String:
  815. r.Groups = []string{rg.(string)}
  816. default:
  817. r.Groups = []string{fmt.Sprintf("%v", rg)}
  818. }
  819. }
  820. //flatten group vs groups
  821. if singleGroup != "" {
  822. // Check if we have both groups and group provided in the rule config
  823. if len(r.Groups) > 0 {
  824. return r, fmt.Errorf("only one of group or groups should be defined, both provided")
  825. }
  826. r.Groups = []string{singleGroup}
  827. }
  828. return r, nil
  829. }
  830. // sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
  831. // rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
  832. func (r *rule) sanity() error {
  833. //port, proto, local_cidr are AND, no need to check here
  834. //ca_sha and ca_name don't have a wildcard value, no need to check here
  835. groupsEmpty := len(r.Groups) == 0
  836. hostEmpty := r.Host == ""
  837. cidrEmpty := r.Cidr == ""
  838. if (groupsEmpty && hostEmpty && cidrEmpty) == true {
  839. return nil //no content!
  840. }
  841. groupsHasAny := slices.Contains(r.Groups, "any")
  842. if groupsHasAny && len(r.Groups) > 1 {
  843. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the other groups specified", r.Groups)
  844. }
  845. if r.Host == "any" {
  846. if !groupsEmpty {
  847. return fmt.Errorf("groups specified as %s, but host=any will match any host, regardless of groups", r.Groups)
  848. }
  849. if !cidrEmpty {
  850. return fmt.Errorf("cidr specified as %s, but host=any will match any host, regardless of cidr", r.Cidr)
  851. }
  852. }
  853. if groupsHasAny {
  854. if !hostEmpty && r.Host != "any" {
  855. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified host %s", r.Groups, r.Host)
  856. }
  857. if !cidrEmpty {
  858. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified cidr %s", r.Groups, r.Cidr)
  859. }
  860. }
  861. //todo alert on cidr-any
  862. return nil
  863. }
  864. func parsePort(s string) (startPort, endPort int32, err error) {
  865. if s == "any" {
  866. startPort = firewall.PortAny
  867. endPort = firewall.PortAny
  868. } else if s == "fragment" {
  869. startPort = firewall.PortFragment
  870. endPort = firewall.PortFragment
  871. } else if strings.Contains(s, `-`) {
  872. sPorts := strings.SplitN(s, `-`, 2)
  873. sPorts[0] = strings.Trim(sPorts[0], " ")
  874. sPorts[1] = strings.Trim(sPorts[1], " ")
  875. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  876. return 0, 0, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  877. }
  878. rStartPort, err := strconv.Atoi(sPorts[0])
  879. if err != nil {
  880. return 0, 0, fmt.Errorf("beginning range was not a number; `%s`", sPorts[0])
  881. }
  882. rEndPort, err := strconv.Atoi(sPorts[1])
  883. if err != nil {
  884. return 0, 0, fmt.Errorf("ending range was not a number; `%s`", sPorts[1])
  885. }
  886. startPort = int32(rStartPort)
  887. endPort = int32(rEndPort)
  888. if startPort == firewall.PortAny {
  889. endPort = firewall.PortAny
  890. }
  891. } else {
  892. rPort, err := strconv.Atoi(s)
  893. if err != nil {
  894. return 0, 0, fmt.Errorf("was not a number; `%s`", s)
  895. }
  896. startPort = int32(rPort)
  897. endPort = startPort
  898. }
  899. return
  900. }