firewall.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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.PacketKey]*conn
  67. TimerWheel *TimerWheel[firewall.PacketKey]
  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.PacketKey]*conn),
  140. TimerWheel: NewTimerWheel[firewall.PacketKey](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. //
  362. // key is the dense conntrack key — used as-is for the inConns fast path
  363. // without touching fp at all. fp is the rich Packet form rule matching
  364. // needs (CIDR lookups, family checks); on the conntrack-miss slow path
  365. // Drop ensures fp is hydrated from key (idempotent if the caller already
  366. // filled fp). On accept-via-conntrack the caller's fp is left untouched.
  367. func (f *Firewall) Drop(key firewall.PacketKey, fp *firewall.Packet, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) error {
  368. // Check if we spoke to this tuple, if we did then allow this packet.
  369. // Hot path: only the dense key is touched.
  370. if f.inConns(key, h, caPool, localCache) {
  371. return nil
  372. }
  373. // Conntrack miss → rule matching needs the rich Packet form. Hydrate
  374. // from the key if the caller passed a zero-valued fp (the inbound path
  375. // after ParseInbound). Outbound callers fill fp via newPacket and skip
  376. // this hop.
  377. if !fp.LocalAddr.IsValid() {
  378. key.Hydrate(fp)
  379. }
  380. // Make sure remote address matches nebula certificate, and determine how to treat it
  381. if h.networks == nil {
  382. // Simple case: Certificate has one address and no unsafe networks
  383. if h.vpnAddrs[0] != fp.RemoteAddr {
  384. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  385. return ErrInvalidRemoteIP
  386. }
  387. } else {
  388. nwType, ok := h.networks.Lookup(fp.RemoteAddr)
  389. if !ok {
  390. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  391. return ErrInvalidRemoteIP
  392. }
  393. switch nwType {
  394. case NetworkTypeVPN:
  395. break // nothing special
  396. case NetworkTypeVPNPeer:
  397. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  398. return ErrPeerRejected // reject for now, one day this may have different FW rules
  399. case NetworkTypeUnsafe:
  400. break // nothing special, one day this may have different FW rules
  401. default:
  402. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  403. return ErrUnknownNetworkType //should never happen
  404. }
  405. }
  406. // Make sure we are supposed to be handling this local ip address
  407. if !f.routableNetworks.Contains(fp.LocalAddr) {
  408. f.metrics(incoming).droppedLocalAddr.Inc(1)
  409. return ErrInvalidLocalIP
  410. }
  411. table := f.OutRules
  412. if incoming {
  413. table = f.InRules
  414. }
  415. // We now know which firewall table to check against
  416. if !table.match(*fp, incoming, h.ConnectionState.peerCert, caPool) {
  417. f.metrics(incoming).droppedNoRule.Inc(1)
  418. return ErrNoMatchingRule
  419. }
  420. // We always want to conntrack since it is a faster operation
  421. f.addConn(key, fp.Protocol, incoming)
  422. return nil
  423. }
  424. func (f *Firewall) metrics(incoming bool) firewallMetrics {
  425. if incoming {
  426. return f.incomingMetrics
  427. } else {
  428. return f.outgoingMetrics
  429. }
  430. }
  431. // Destroy cleans up any known cyclical references so the object can be freed by GC. This should be called if a new
  432. // firewall object is created
  433. func (f *Firewall) Destroy() {
  434. //TODO: clean references if/when needed
  435. }
  436. func (f *Firewall) EmitStats() {
  437. conntrack := f.Conntrack
  438. conntrack.Lock()
  439. conntrackCount := len(conntrack.Conns)
  440. conntrack.Unlock()
  441. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  442. metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
  443. metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
  444. }
  445. func (f *Firewall) inConns(key firewall.PacketKey, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
  446. if localCache != nil {
  447. if _, ok := localCache[key]; ok {
  448. return true
  449. }
  450. }
  451. conntrack := f.Conntrack
  452. conntrack.Lock()
  453. // Purge every time we test
  454. ep, has := conntrack.TimerWheel.Purge()
  455. if has {
  456. f.evict(ep)
  457. }
  458. c, ok := conntrack.Conns[key]
  459. if !ok {
  460. conntrack.Unlock()
  461. return false
  462. }
  463. if c.rulesVersion != f.rulesVersion {
  464. // This conntrack entry was for an older rule set, validate
  465. // it still passes with the current rule set. Rule matching needs
  466. // the rich Packet form, so hydrate from key.
  467. var fp firewall.Packet
  468. key.Hydrate(&fp)
  469. table := f.OutRules
  470. if c.incoming {
  471. table = f.InRules
  472. }
  473. // We now know which firewall table to check against
  474. if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
  475. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  476. h.logger(f.l).Debug("dropping old conntrack entry, does not match new ruleset",
  477. "fwPacket", fp,
  478. "incoming", c.incoming,
  479. "rulesVersion", f.rulesVersion,
  480. "oldRulesVersion", c.rulesVersion,
  481. )
  482. }
  483. delete(conntrack.Conns, key)
  484. conntrack.Unlock()
  485. return false
  486. }
  487. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  488. h.logger(f.l).Debug("keeping old conntrack entry, does match new ruleset",
  489. "fwPacket", fp,
  490. "incoming", c.incoming,
  491. "rulesVersion", f.rulesVersion,
  492. "oldRulesVersion", c.rulesVersion,
  493. )
  494. }
  495. c.rulesVersion = f.rulesVersion
  496. }
  497. switch key.Protocol {
  498. case firewall.ProtoTCP:
  499. c.Expires = time.Now().Add(f.TCPTimeout)
  500. case firewall.ProtoUDP:
  501. c.Expires = time.Now().Add(f.UDPTimeout)
  502. default:
  503. c.Expires = time.Now().Add(f.DefaultTimeout)
  504. }
  505. conntrack.Unlock()
  506. if localCache != nil {
  507. localCache[key] = struct{}{}
  508. }
  509. return true
  510. }
  511. func (f *Firewall) addConn(key firewall.PacketKey, protocol uint8, incoming bool) {
  512. var timeout time.Duration
  513. c := &conn{}
  514. switch protocol {
  515. case firewall.ProtoTCP:
  516. timeout = f.TCPTimeout
  517. case firewall.ProtoUDP:
  518. timeout = f.UDPTimeout
  519. default:
  520. timeout = f.DefaultTimeout
  521. }
  522. conntrack := f.Conntrack
  523. conntrack.Lock()
  524. if _, ok := conntrack.Conns[key]; !ok {
  525. conntrack.TimerWheel.Advance(time.Now())
  526. conntrack.TimerWheel.Add(key, timeout)
  527. }
  528. // Record which rulesVersion allowed this connection, so we can retest after
  529. // firewall reload
  530. c.incoming = incoming
  531. c.rulesVersion = f.rulesVersion
  532. c.Expires = time.Now().Add(timeout)
  533. conntrack.Conns[key] = c
  534. conntrack.Unlock()
  535. }
  536. // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
  537. // Caller must own the connMutex lock!
  538. func (f *Firewall) evict(key firewall.PacketKey) {
  539. // Are we still tracking this conn?
  540. conntrack := f.Conntrack
  541. t, ok := conntrack.Conns[key]
  542. if !ok {
  543. return
  544. }
  545. newT := t.Expires.Sub(time.Now())
  546. // Timeout is in the future, re-add the timer
  547. if newT > 0 {
  548. conntrack.TimerWheel.Advance(time.Now())
  549. conntrack.TimerWheel.Add(key, newT)
  550. return
  551. }
  552. // This conn is done
  553. delete(conntrack.Conns, key)
  554. }
  555. func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  556. if ft.AnyProto.match(p, incoming, c, caPool) {
  557. return true
  558. }
  559. switch p.Protocol {
  560. case firewall.ProtoTCP:
  561. if ft.TCP.match(p, incoming, c, caPool) {
  562. return true
  563. }
  564. case firewall.ProtoUDP:
  565. if ft.UDP.match(p, incoming, c, caPool) {
  566. return true
  567. }
  568. case firewall.ProtoICMP, firewall.ProtoICMPv6:
  569. if ft.ICMP.match(p, incoming, c, caPool) {
  570. return true
  571. }
  572. }
  573. return false
  574. }
  575. func (fp firewallPort) addRule(f *Firewall, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
  576. if startPort > endPort {
  577. return fmt.Errorf("start port was lower than end port")
  578. }
  579. for i := startPort; i <= endPort; i++ {
  580. if _, ok := fp[i]; !ok {
  581. fp[i] = &FirewallCA{
  582. CANames: make(map[string]*FirewallRule),
  583. CAShas: make(map[string]*FirewallRule),
  584. }
  585. }
  586. if err := fp[i].addRule(f, groups, host, cidr, localCidr, caName, caSha); err != nil {
  587. return err
  588. }
  589. }
  590. return nil
  591. }
  592. func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  593. // We don't have any allowed ports, bail
  594. if fp == nil {
  595. return false
  596. }
  597. // this branch is here to catch traffic from FirewallTable.Any.match and FirewallTable.ICMP.match
  598. if p.Protocol == firewall.ProtoICMP || p.Protocol == firewall.ProtoICMPv6 {
  599. // port numbers are re-used for connection tracking of ICMP,
  600. // but we don't want to actually filter on them.
  601. return fp[firewall.PortAny].match(p, c, caPool)
  602. }
  603. var port int32
  604. if p.Fragment {
  605. port = firewall.PortFragment
  606. } else if incoming {
  607. port = int32(p.LocalPort)
  608. } else {
  609. port = int32(p.RemotePort)
  610. }
  611. if fp[port].match(p, c, caPool) {
  612. return true
  613. }
  614. return fp[firewall.PortAny].match(p, c, caPool)
  615. }
  616. func (fc *FirewallCA) addRule(f *Firewall, groups []string, host string, cidr, localCidr, caName, caSha string) error {
  617. fr := func() *FirewallRule {
  618. return &FirewallRule{
  619. Hosts: make(map[string]*firewallLocalCIDR),
  620. Groups: make([]*firewallGroups, 0),
  621. CIDR: new(bart.Table[*firewallLocalCIDR]),
  622. }
  623. }
  624. if caSha == "" && caName == "" {
  625. if fc.Any == nil {
  626. fc.Any = fr()
  627. }
  628. return fc.Any.addRule(f, groups, host, cidr, localCidr)
  629. }
  630. if caSha != "" {
  631. if _, ok := fc.CAShas[caSha]; !ok {
  632. fc.CAShas[caSha] = fr()
  633. }
  634. err := fc.CAShas[caSha].addRule(f, groups, host, cidr, localCidr)
  635. if err != nil {
  636. return err
  637. }
  638. }
  639. if caName != "" {
  640. if _, ok := fc.CANames[caName]; !ok {
  641. fc.CANames[caName] = fr()
  642. }
  643. err := fc.CANames[caName].addRule(f, groups, host, cidr, localCidr)
  644. if err != nil {
  645. return err
  646. }
  647. }
  648. return nil
  649. }
  650. func (fc *FirewallCA) match(p firewall.Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  651. if fc == nil {
  652. return false
  653. }
  654. if fc.Any.match(p, c) {
  655. return true
  656. }
  657. if t, ok := fc.CAShas[c.Certificate.Issuer()]; ok {
  658. if t.match(p, c) {
  659. return true
  660. }
  661. }
  662. s, err := caPool.GetCAForCert(c.Certificate)
  663. if err != nil {
  664. return false
  665. }
  666. return fc.CANames[s.Certificate.Name()].match(p, c)
  667. }
  668. func (fr *FirewallRule) addRule(f *Firewall, groups []string, host, cidr, localCidr string) error {
  669. flc := func() *firewallLocalCIDR {
  670. return &firewallLocalCIDR{
  671. LocalCIDR: new(bart.Lite),
  672. }
  673. }
  674. if fr.isAny(groups, host, cidr) {
  675. if fr.Any == nil {
  676. fr.Any = flc()
  677. }
  678. return fr.Any.addRule(f, localCidr)
  679. }
  680. if len(groups) > 0 {
  681. nlc := flc()
  682. err := nlc.addRule(f, localCidr)
  683. if err != nil {
  684. return err
  685. }
  686. fr.Groups = append(fr.Groups, &firewallGroups{
  687. Groups: groups,
  688. LocalCIDR: nlc,
  689. })
  690. }
  691. if host != "" {
  692. nlc := fr.Hosts[host]
  693. if nlc == nil {
  694. nlc = flc()
  695. }
  696. err := nlc.addRule(f, localCidr)
  697. if err != nil {
  698. return err
  699. }
  700. fr.Hosts[host] = nlc
  701. }
  702. if cidr != "" {
  703. c, err := netip.ParsePrefix(cidr)
  704. if err != nil {
  705. return err
  706. }
  707. nlc, _ := fr.CIDR.Get(c)
  708. if nlc == nil {
  709. nlc = flc()
  710. }
  711. err = nlc.addRule(f, localCidr)
  712. if err != nil {
  713. return err
  714. }
  715. fr.CIDR.Insert(c, nlc)
  716. }
  717. return nil
  718. }
  719. func (fr *FirewallRule) isAny(groups []string, host string, cidr string) bool {
  720. if len(groups) == 0 && host == "" && cidr == "" {
  721. return true
  722. }
  723. if slices.Contains(groups, "any") {
  724. return true
  725. }
  726. if host == "any" {
  727. return true
  728. }
  729. if cidr == "any" {
  730. return true
  731. }
  732. return false
  733. }
  734. func (fr *FirewallRule) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  735. if fr == nil {
  736. return false
  737. }
  738. // Shortcut path for if groups, hosts, or cidr contained an `any`
  739. if fr.Any.match(p, c) {
  740. return true
  741. }
  742. // Need any of group, host, or cidr to match
  743. for _, sg := range fr.Groups {
  744. found := false
  745. for _, g := range sg.Groups {
  746. if _, ok := c.InvertedGroups[g]; !ok {
  747. found = false
  748. break
  749. }
  750. found = true
  751. }
  752. if found && sg.LocalCIDR.match(p, c) {
  753. return true
  754. }
  755. }
  756. if fr.Hosts != nil {
  757. if flc, ok := fr.Hosts[c.Certificate.Name()]; ok {
  758. if flc.match(p, c) {
  759. return true
  760. }
  761. }
  762. }
  763. for _, v := range fr.CIDR.Supernets(netip.PrefixFrom(p.RemoteAddr, p.RemoteAddr.BitLen())) {
  764. if v.match(p, c) {
  765. return true
  766. }
  767. }
  768. return false
  769. }
  770. func (flc *firewallLocalCIDR) addRule(f *Firewall, localCidr string) error {
  771. if localCidr == "any" {
  772. flc.Any = true
  773. return nil
  774. }
  775. if localCidr == "" {
  776. if !f.hasUnsafeNetworks || f.defaultLocalCIDRAny {
  777. flc.Any = true
  778. return nil
  779. }
  780. for _, network := range f.assignedNetworks {
  781. flc.LocalCIDR.Insert(network)
  782. }
  783. return nil
  784. }
  785. c, err := netip.ParsePrefix(localCidr)
  786. if err != nil {
  787. return err
  788. }
  789. flc.LocalCIDR.Insert(c)
  790. return nil
  791. }
  792. func (flc *firewallLocalCIDR) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  793. if flc == nil {
  794. return false
  795. }
  796. if flc.Any {
  797. return true
  798. }
  799. return flc.LocalCIDR.Contains(p.LocalAddr)
  800. }
  801. type rule struct {
  802. Port string
  803. Code string
  804. Proto string
  805. Host string
  806. Groups []string
  807. Cidr string
  808. LocalCidr string
  809. CAName string
  810. CASha string
  811. }
  812. func convertRule(l *slog.Logger, p any, table string, i int) (rule, error) {
  813. r := rule{}
  814. m, ok := p.(map[string]any)
  815. if !ok {
  816. return r, errors.New("could not parse rule")
  817. }
  818. toString := func(k string, m map[string]any) string {
  819. v, ok := m[k]
  820. if !ok {
  821. return ""
  822. }
  823. return fmt.Sprintf("%v", v)
  824. }
  825. r.Port = toString("port", m)
  826. r.Code = toString("code", m)
  827. r.Proto = toString("proto", m)
  828. r.Host = toString("host", m)
  829. r.Cidr = toString("cidr", m)
  830. r.LocalCidr = toString("local_cidr", m)
  831. r.CAName = toString("ca_name", m)
  832. r.CASha = toString("ca_sha", m)
  833. // Make sure group isn't an array
  834. if v, ok := m["group"].([]any); ok {
  835. if len(v) > 1 {
  836. return r, errors.New("group should contain a single value, an array with more than one entry was provided")
  837. }
  838. l.Warn("group was an array with a single value, converting to simple value",
  839. "table", table,
  840. "rule", i,
  841. )
  842. m["group"] = v[0]
  843. }
  844. singleGroup := toString("group", m)
  845. if rg, ok := m["groups"]; ok {
  846. switch reflect.TypeOf(rg).Kind() {
  847. case reflect.Slice:
  848. v := reflect.ValueOf(rg)
  849. r.Groups = make([]string, v.Len())
  850. for i := 0; i < v.Len(); i++ {
  851. r.Groups[i] = v.Index(i).Interface().(string)
  852. }
  853. case reflect.String:
  854. r.Groups = []string{rg.(string)}
  855. default:
  856. r.Groups = []string{fmt.Sprintf("%v", rg)}
  857. }
  858. }
  859. //flatten group vs groups
  860. if singleGroup != "" {
  861. // Check if we have both groups and group provided in the rule config
  862. if len(r.Groups) > 0 {
  863. return r, fmt.Errorf("only one of group or groups should be defined, both provided")
  864. }
  865. r.Groups = []string{singleGroup}
  866. }
  867. return r, nil
  868. }
  869. // sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
  870. // rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
  871. func (r *rule) sanity() error {
  872. //port, proto, local_cidr are AND, no need to check here
  873. //ca_sha and ca_name don't have a wildcard value, no need to check here
  874. groupsEmpty := len(r.Groups) == 0
  875. hostEmpty := r.Host == ""
  876. cidrEmpty := r.Cidr == ""
  877. if (groupsEmpty && hostEmpty && cidrEmpty) == true {
  878. return nil //no content!
  879. }
  880. groupsHasAny := slices.Contains(r.Groups, "any")
  881. if groupsHasAny && len(r.Groups) > 1 {
  882. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the other groups specified", r.Groups)
  883. }
  884. if r.Host == "any" {
  885. if !groupsEmpty {
  886. return fmt.Errorf("groups specified as %s, but host=any will match any host, regardless of groups", r.Groups)
  887. }
  888. if !cidrEmpty {
  889. return fmt.Errorf("cidr specified as %s, but host=any will match any host, regardless of cidr", r.Cidr)
  890. }
  891. }
  892. if groupsHasAny {
  893. if !hostEmpty && r.Host != "any" {
  894. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified host %s", r.Groups, r.Host)
  895. }
  896. if !cidrEmpty {
  897. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified cidr %s", r.Groups, r.Cidr)
  898. }
  899. }
  900. if r.Code != "" {
  901. 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)
  902. }
  903. //todo alert on cidr-any
  904. return nil
  905. }
  906. func parsePort(s string) (int32, int32, error) {
  907. var err error
  908. const notAPort int32 = -2
  909. if s == "any" {
  910. return firewall.PortAny, firewall.PortAny, nil
  911. }
  912. if s == "fragment" {
  913. return firewall.PortFragment, firewall.PortFragment, nil
  914. }
  915. if !strings.Contains(s, `-`) {
  916. rPort, err := strconv.Atoi(s)
  917. if err != nil {
  918. return notAPort, notAPort, fmt.Errorf("was not a number; `%s`", s)
  919. }
  920. return int32(rPort), int32(rPort), nil
  921. }
  922. sPorts := strings.SplitN(s, `-`, 2)
  923. for i := range sPorts {
  924. sPorts[i] = strings.Trim(sPorts[i], " ")
  925. }
  926. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  927. return notAPort, notAPort, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  928. }
  929. rStartPort, err := strconv.Atoi(sPorts[0])
  930. if err != nil {
  931. return notAPort, notAPort, fmt.Errorf("beginning range was not a number; `%s`", sPorts[0])
  932. }
  933. rEndPort, err := strconv.Atoi(sPorts[1])
  934. if err != nil {
  935. return notAPort, notAPort, fmt.Errorf("ending range was not a number; `%s`", sPorts[1])
  936. }
  937. startPort := int32(rStartPort)
  938. endPort := int32(rEndPort)
  939. if startPort == firewall.PortAny {
  940. endPort = firewall.PortAny
  941. }
  942. return startPort, endPort, nil
  943. }