firewall.go 29 KB

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