firewall.go 26 KB

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