1
0

firewall.go 29 KB

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