firewall.go 27 KB

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