firewall.go 31 KB

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