firewall.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. // vpnNetworks holds assignedNetworks for lookup: a source address inside one of them
  53. // belongs to a node of the overlay, and only that node may send as it.
  54. vpnNetworks *bart.Lite
  55. // unsafeNetworks is the list of unsafe networks issued to us in the certificate
  56. unsafeNetworks []netip.Prefix
  57. rules string
  58. rulesVersion uint16
  59. defaultLocalCIDRAny bool
  60. incomingMetrics firewallMetrics
  61. outgoingMetrics firewallMetrics
  62. l *slog.Logger
  63. }
  64. type firewallMetrics struct {
  65. droppedLocalAddr metrics.Counter
  66. droppedRemoteAddr metrics.Counter
  67. droppedNoRule metrics.Counter
  68. }
  69. type FirewallConntrack struct {
  70. sync.Mutex
  71. Conns map[firewall.Packet]*conn
  72. TimerWheel *TimerWheel[firewall.Packet]
  73. }
  74. // FirewallTable is the entry point for a rule, the evaluation order is:
  75. // Proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR)
  76. type FirewallTable struct {
  77. TCP firewallPort
  78. UDP firewallPort
  79. ICMP firewallPort
  80. AnyProto firewallPort
  81. }
  82. func newFirewallTable() *FirewallTable {
  83. return &FirewallTable{
  84. TCP: firewallPort{},
  85. UDP: firewallPort{},
  86. ICMP: firewallPort{},
  87. AnyProto: firewallPort{},
  88. }
  89. }
  90. type FirewallCA struct {
  91. Any *FirewallRule
  92. CANames map[string]*FirewallRule
  93. CAShas map[string]*FirewallRule
  94. }
  95. type FirewallRule struct {
  96. // Any makes Hosts, Groups, and CIDR irrelevant
  97. Any *firewallLocalCIDR
  98. Hosts map[string]*firewallLocalCIDR
  99. Groups []*firewallGroups
  100. CIDR *bart.Table[*firewallLocalCIDR]
  101. }
  102. type firewallGroups struct {
  103. Groups []string
  104. LocalCIDR *firewallLocalCIDR
  105. }
  106. // Even though ports are uint16, int32 maps are faster for lookup
  107. // Plus we can use `-1` for fragment rules
  108. type firewallPort map[int32]*FirewallCA
  109. type firewallLocalCIDR struct {
  110. Any bool
  111. LocalCIDR *bart.Lite
  112. }
  113. // NewFirewall creates a new Firewall object. A TimerWheel is created for you from the provided timeouts.
  114. // The certificate provided should be the highest version loaded in memory.
  115. func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c cert.Certificate) *Firewall {
  116. //TODO: error on 0 duration
  117. var tmin, tmax time.Duration
  118. if tcpTimeout < UDPTimeout {
  119. tmin = tcpTimeout
  120. tmax = UDPTimeout
  121. } else {
  122. tmin = UDPTimeout
  123. tmax = tcpTimeout
  124. }
  125. if defaultTimeout < tmin {
  126. tmin = defaultTimeout
  127. } else if defaultTimeout > tmax {
  128. tmax = defaultTimeout
  129. }
  130. routableNetworks := new(bart.Lite)
  131. vpnNetworks := new(bart.Lite)
  132. var assignedNetworks []netip.Prefix
  133. for _, network := range c.Networks() {
  134. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  135. routableNetworks.Insert(nprefix)
  136. vpnNetworks.Insert(network)
  137. assignedNetworks = append(assignedNetworks, network)
  138. }
  139. unsafeNetworks := c.UnsafeNetworks()
  140. for _, n := range unsafeNetworks {
  141. routableNetworks.Insert(n)
  142. }
  143. return &Firewall{
  144. Conntrack: &FirewallConntrack{
  145. Conns: make(map[firewall.Packet]*conn),
  146. TimerWheel: NewTimerWheel[firewall.Packet](tmin, tmax),
  147. },
  148. InRules: newFirewallTable(),
  149. OutRules: newFirewallTable(),
  150. TCPTimeout: tcpTimeout,
  151. UDPTimeout: UDPTimeout,
  152. DefaultTimeout: defaultTimeout,
  153. routableNetworks: routableNetworks,
  154. assignedNetworks: assignedNetworks,
  155. vpnNetworks: vpnNetworks,
  156. unsafeNetworks: unsafeNetworks,
  157. l: l,
  158. incomingMetrics: firewallMetrics{
  159. droppedLocalAddr: metrics.GetOrRegisterCounter("firewall.incoming.dropped.local_addr", nil),
  160. droppedRemoteAddr: metrics.GetOrRegisterCounter("firewall.incoming.dropped.remote_addr", nil),
  161. droppedNoRule: metrics.GetOrRegisterCounter("firewall.incoming.dropped.no_rule", nil),
  162. },
  163. outgoingMetrics: firewallMetrics{
  164. droppedLocalAddr: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.local_addr", nil),
  165. droppedRemoteAddr: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.remote_addr", nil),
  166. droppedNoRule: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.no_rule", nil),
  167. },
  168. }
  169. }
  170. func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewall, error) {
  171. certificate := cs.getCertificate(cert.Version2)
  172. if certificate == nil {
  173. certificate = cs.getCertificate(cert.Version1)
  174. }
  175. if certificate == nil {
  176. panic("No certificate available to reconfigure the firewall")
  177. }
  178. fw := NewFirewall(
  179. l,
  180. c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12),
  181. c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3),
  182. c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10),
  183. certificate,
  184. //TODO: max_connections
  185. )
  186. fw.defaultLocalCIDRAny = c.GetBool("firewall.default_local_cidr_any", false)
  187. inboundAction := c.GetString("firewall.inbound_action", "drop")
  188. switch inboundAction {
  189. case "reject":
  190. fw.InboundSendReject = true
  191. case "drop":
  192. fw.InboundSendReject = false
  193. default:
  194. l.Warn("invalid firewall.inbound_action, defaulting to `drop`", "action", inboundAction)
  195. fw.InboundSendReject = false
  196. }
  197. outboundAction := c.GetString("firewall.outbound_action", "drop")
  198. switch outboundAction {
  199. case "reject":
  200. fw.OutboundSendReject = true
  201. case "drop":
  202. fw.OutboundSendReject = false
  203. default:
  204. l.Warn("invalid firewall.outbound_action, defaulting to `drop`", "action", outboundAction)
  205. fw.OutboundSendReject = false
  206. }
  207. err := AddFirewallRulesFromConfig(l, false, c, fw)
  208. if err != nil {
  209. return nil, err
  210. }
  211. err = AddFirewallRulesFromConfig(l, true, c, fw)
  212. if err != nil {
  213. return nil, err
  214. }
  215. return fw, nil
  216. }
  217. // AddRule properly creates the in memory rule structure for a firewall table.
  218. func (f *Firewall) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
  219. var (
  220. ft *FirewallTable
  221. fp firewallPort
  222. )
  223. if incoming {
  224. ft = f.InRules
  225. } else {
  226. ft = f.OutRules
  227. }
  228. switch proto {
  229. case iputil.IPProtocolTCP:
  230. fp = ft.TCP
  231. case iputil.IPProtocolUDP:
  232. fp = ft.UDP
  233. case iputil.IPProtocolICMP, iputil.IPProtocolICMPv6:
  234. //ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
  235. if startPort != firewall.PortAny {
  236. f.l.Warn("ignoring port specification for ICMP firewall rule", "startPort", startPort)
  237. }
  238. startPort = firewall.PortAny
  239. endPort = firewall.PortAny
  240. fp = ft.ICMP
  241. case firewall.ProtoAny:
  242. fp = ft.AnyProto
  243. default:
  244. return fmt.Errorf("unknown protocol %v", proto)
  245. }
  246. // We need this rule string because we generate a hash. Removing this will break firewall reload.
  247. ruleString := fmt.Sprintf(
  248. "incoming: %v, proto: %v, startPort: %v, endPort: %v, groups: %v, host: %v, ip: %v, localIp: %v, caName: %v, caSha: %s",
  249. incoming, proto, startPort, endPort, groups, host, cidr, localCidr, caName, caSha,
  250. )
  251. f.rules += ruleString + "\n"
  252. direction := "incoming"
  253. if !incoming {
  254. direction = "outgoing"
  255. }
  256. f.l.Info("Firewall rule added",
  257. "firewallRule", m{"direction": direction, "proto": proto, "startPort": startPort, "endPort": endPort, "groups": groups, "host": host, "cidr": cidr, "localCidr": localCidr, "caName": caName, "caSha": caSha},
  258. )
  259. return fp.addRule(f, startPort, endPort, groups, host, cidr, localCidr, caName, caSha)
  260. }
  261. // GetRuleHash returns a hash representation of all inbound and outbound rules
  262. func (f *Firewall) GetRuleHash() string {
  263. sum := sha256.Sum256([]byte(f.rules))
  264. return hex.EncodeToString(sum[:])
  265. }
  266. // GetRuleHashFNV returns a uint32 FNV-1 hash representation the rules, for use as a metric value
  267. func (f *Firewall) GetRuleHashFNV() uint32 {
  268. h := fnv.New32a()
  269. h.Write([]byte(f.rules))
  270. return h.Sum32()
  271. }
  272. // GetRuleHashes returns both the sha256 and FNV-1 hashes, suitable for logging
  273. func (f *Firewall) GetRuleHashes() string {
  274. return "SHA:" + f.GetRuleHash() + ",FNV:" + strconv.FormatUint(uint64(f.GetRuleHashFNV()), 10)
  275. }
  276. func AddFirewallRulesFromConfig(l *slog.Logger, inbound bool, c *config.C, fw FirewallInterface) error {
  277. var table string
  278. if inbound {
  279. table = "firewall.inbound"
  280. } else {
  281. table = "firewall.outbound"
  282. }
  283. r := c.Get(table)
  284. if r == nil {
  285. return nil
  286. }
  287. rs, ok := r.([]any)
  288. if !ok {
  289. return fmt.Errorf("%s failed to parse, should be an array of rules", table)
  290. }
  291. for i, t := range rs {
  292. r, err := convertRule(l, t, table, i)
  293. if err != nil {
  294. return fmt.Errorf("%s rule #%v; %s", table, i, err)
  295. }
  296. if r.Code != "" && r.Port != "" {
  297. return fmt.Errorf("%s rule #%v; only one of port or code should be provided", table, i)
  298. }
  299. if r.Host == "" && len(r.Groups) == 0 && r.Cidr == "" && r.LocalCidr == "" && r.CAName == "" && r.CASha == "" {
  300. 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)
  301. }
  302. var sPort, errPort string
  303. if r.Code != "" {
  304. errPort = "code"
  305. sPort = r.Code
  306. } else {
  307. errPort = "port"
  308. sPort = r.Port
  309. }
  310. var proto uint8
  311. var startPort, endPort int32
  312. switch r.Proto {
  313. case "any":
  314. proto = firewall.ProtoAny
  315. startPort, endPort, err = parsePort(sPort)
  316. case "tcp":
  317. proto = iputil.IPProtocolTCP
  318. startPort, endPort, err = parsePort(sPort)
  319. case "udp":
  320. proto = iputil.IPProtocolUDP
  321. startPort, endPort, err = parsePort(sPort)
  322. case "icmp":
  323. proto = iputil.IPProtocolICMP
  324. startPort = firewall.PortAny
  325. endPort = firewall.PortAny
  326. if sPort != "" {
  327. l.Warn("ignoring port specification for ICMP firewall rule", "port", sPort)
  328. }
  329. default:
  330. return fmt.Errorf("%s rule #%v; proto was not understood; `%s`", table, i, r.Proto)
  331. }
  332. if err != nil {
  333. return fmt.Errorf("%s rule #%v; %s %s", table, i, errPort, err)
  334. }
  335. if r.Cidr != "" && r.Cidr != "any" {
  336. _, err = netip.ParsePrefix(r.Cidr)
  337. if err != nil {
  338. return fmt.Errorf("%s rule #%v; cidr did not parse; %s", table, i, err)
  339. }
  340. }
  341. if r.LocalCidr != "" && r.LocalCidr != "any" {
  342. _, err = netip.ParsePrefix(r.LocalCidr)
  343. if err != nil {
  344. return fmt.Errorf("%s rule #%v; local_cidr did not parse; %s", table, i, err)
  345. }
  346. }
  347. if warning := r.sanity(); warning != nil {
  348. l.Warn("firewall rule sanity check",
  349. "table", table,
  350. "rule", i,
  351. "warning", warning,
  352. )
  353. }
  354. err = fw.AddRule(inbound, proto, startPort, endPort, r.Groups, r.Host, r.Cidr, r.LocalCidr, r.CAName, r.CASha)
  355. if err != nil {
  356. return fmt.Errorf("%s rule #%v; `%s`", table, i, err)
  357. }
  358. }
  359. return nil
  360. }
  361. var ErrUnknownNetworkType = errors.New("unknown network type")
  362. var ErrPeerRejected = errors.New("remote address is not within a network that we handle")
  363. var ErrInvalidRemoteIP = errors.New("remote address is not in remote certificate networks")
  364. var ErrInvalidLocalIP = errors.New("local address is not in list of handled local addresses")
  365. var ErrNoMatchingRule = errors.New("no matching rule in firewall table")
  366. // Drop returns an error if the packet should be dropped, explaining why. It
  367. // returns nil if the packet should not be dropped.
  368. func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) error {
  369. // Make sure remote address matches nebula certificate, and determine how to treat it
  370. if h.networks == nil {
  371. // Simple case: Certificate has one address and no unsafe networks
  372. if h.vpnAddrs[0] != fp.RemoteAddr {
  373. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  374. return ErrInvalidRemoteIP
  375. }
  376. } else {
  377. nwType, ok := h.networks.Lookup(fp.RemoteAddr)
  378. if !ok {
  379. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  380. return ErrInvalidRemoteIP
  381. }
  382. switch nwType {
  383. case NetworkTypeVPN:
  384. break // nothing special
  385. case NetworkTypeVPNPeer:
  386. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  387. return ErrPeerRejected // reject for now, one day this may have different FW rules
  388. case NetworkTypeUnsafe:
  389. // An unsafe network says what a peer routes for, never who it is. One that
  390. // overlaps our own networks would let the peer send as any node of the overlay,
  391. // and whatever trusts the source address, the firewall's own rules and the
  392. // identity a program looks up for it, would be told the wrong node. A source
  393. // inside our networks is a node's own address, which only that node sends
  394. // from, as NetworkTypeVPN, matched first; through an unsafe network it is
  395. // refused. Outbound the address is a destination and claims nothing.
  396. if incoming && f.vpnNetworks.Contains(fp.RemoteAddr) {
  397. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  398. return ErrInvalidRemoteIP
  399. }
  400. default:
  401. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  402. return ErrUnknownNetworkType //should never happen
  403. }
  404. }
  405. // Make sure we are supposed to be handling this local ip address
  406. if !f.routableNetworks.Contains(fp.LocalAddr) {
  407. f.metrics(incoming).droppedLocalAddr.Inc(1)
  408. return ErrInvalidLocalIP
  409. }
  410. // Check if we spoke to this tuple, if we did then allow this packet
  411. if f.inConns(fp, h, caPool, localCache) {
  412. return nil
  413. }
  414. table := f.OutRules
  415. if incoming {
  416. table = f.InRules
  417. }
  418. // We now know which firewall table to check against
  419. if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
  420. f.metrics(incoming).droppedNoRule.Inc(1)
  421. return ErrNoMatchingRule
  422. }
  423. // We always want to conntrack since it is a faster operation
  424. f.addConn(fp, incoming)
  425. return nil
  426. }
  427. func (f *Firewall) metrics(incoming bool) firewallMetrics {
  428. if incoming {
  429. return f.incomingMetrics
  430. } else {
  431. return f.outgoingMetrics
  432. }
  433. }
  434. // Destroy cleans up any known cyclical references so the object can be freed by GC. This should be called if a new
  435. // firewall object is created
  436. func (f *Firewall) Destroy() {
  437. //TODO: clean references if/when needed
  438. }
  439. func (f *Firewall) EmitStats() {
  440. conntrack := f.Conntrack
  441. conntrack.Lock()
  442. conntrackCount := len(conntrack.Conns)
  443. conntrack.Unlock()
  444. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  445. metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
  446. metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
  447. }
  448. func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
  449. if localCache != nil {
  450. if _, ok := localCache[fp]; ok {
  451. return true
  452. }
  453. }
  454. conntrack := f.Conntrack
  455. conntrack.Lock()
  456. // Purge every time we test
  457. ep, has := conntrack.TimerWheel.Purge()
  458. if has {
  459. f.evict(ep)
  460. }
  461. c, ok := conntrack.Conns[fp]
  462. if !ok {
  463. conntrack.Unlock()
  464. return false
  465. }
  466. if c.rulesVersion != f.rulesVersion {
  467. // This conntrack entry was for an older rule set, validate
  468. // it still passes with the current rule set
  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, fp)
  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 fp.Protocol {
  498. case iputil.IPProtocolTCP:
  499. c.Expires = time.Now().Add(f.TCPTimeout)
  500. case iputil.IPProtocolUDP:
  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[fp] = struct{}{}
  508. }
  509. return true
  510. }
  511. func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
  512. var timeout time.Duration
  513. c := &conn{}
  514. switch fp.Protocol {
  515. case iputil.IPProtocolTCP:
  516. timeout = f.TCPTimeout
  517. case iputil.IPProtocolUDP:
  518. timeout = f.UDPTimeout
  519. default:
  520. timeout = f.DefaultTimeout
  521. }
  522. conntrack := f.Conntrack
  523. conntrack.Lock()
  524. if _, ok := conntrack.Conns[fp]; !ok {
  525. conntrack.TimerWheel.Advance(time.Now())
  526. conntrack.TimerWheel.Add(fp, 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[fp] = 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(p firewall.Packet) {
  539. // Are we still tracking this conn?
  540. conntrack := f.Conntrack
  541. t, ok := conntrack.Conns[p]
  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(p, newT)
  550. return
  551. }
  552. // This conn is done
  553. delete(conntrack.Conns, p)
  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 iputil.IPProtocolTCP:
  561. if ft.TCP.match(p, incoming, c, caPool) {
  562. return true
  563. }
  564. case iputil.IPProtocolUDP:
  565. if ft.UDP.match(p, incoming, c, caPool) {
  566. return true
  567. }
  568. case iputil.IPProtocolICMP, iputil.IPProtocolICMPv6:
  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 == iputil.IPProtocolICMP || p.Protocol == iputil.IPProtocolICMPv6 {
  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 len(f.unsafeNetworks) == 0 || 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. const notAPort int32 = -2
  908. if s == "any" {
  909. return firewall.PortAny, firewall.PortAny, nil
  910. }
  911. if s == "fragment" {
  912. return firewall.PortFragment, firewall.PortFragment, nil
  913. }
  914. if !strings.Contains(s, `-`) {
  915. rPort, err := parsePortValue("", s)
  916. if err != nil {
  917. return notAPort, notAPort, err
  918. }
  919. return rPort, rPort, nil
  920. }
  921. sPorts := strings.SplitN(s, `-`, 2)
  922. for i := range sPorts {
  923. sPorts[i] = strings.Trim(sPorts[i], " ")
  924. }
  925. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  926. return notAPort, notAPort, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  927. }
  928. startPort, err := parsePortValue("beginning range ", sPorts[0])
  929. if err != nil {
  930. return notAPort, notAPort, err
  931. }
  932. endPort, err := parsePortValue("ending range ", sPorts[1])
  933. if err != nil {
  934. return notAPort, notAPort, err
  935. }
  936. if startPort == firewall.PortAny {
  937. endPort = firewall.PortAny
  938. }
  939. return startPort, endPort, nil
  940. }
  941. // parsePortValue accepts a base-10 decimal in [0, 65535] and returns it
  942. // widened to int32. Using strconv.ParseUint with bitSize 16 rejects
  943. // negative input, out-of-range input (>65535), and any non-decimal byte
  944. // by construction, so the int32 widening that follows is provably safe
  945. // and cannot collide with firewall.PortAny (0) or firewall.PortFragment
  946. // (-1) via integer truncation.
  947. //
  948. // prefix is prepended to both error messages so callers can disambiguate
  949. // the single-port path (prefix="") from the range bounds (prefix="beginning
  950. // range " / "ending range "), preserving the historical error strings.
  951. func parsePortValue(prefix, s string) (int32, error) {
  952. n, err := strconv.ParseUint(s, 10, 16)
  953. if err == nil {
  954. return int32(n), nil
  955. }
  956. if errors.Is(err, strconv.ErrRange) {
  957. return 0, fmt.Errorf("%sout of range [0,65535]; `%s`", prefix, s)
  958. }
  959. return 0, fmt.Errorf("%swas not a number; `%s`", prefix, s)
  960. }