firewall.go 28 KB

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