firewall.go 25 KB

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