firewall.go 28 KB

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