firewall.go 28 KB

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