firewall.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. package nebula
  2. import (
  3. "crypto/sha256"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "hash/fnv"
  9. "net"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/rcrowley/go-metrics"
  16. "github.com/sirupsen/logrus"
  17. "github.com/slackhq/nebula/cert"
  18. "github.com/slackhq/nebula/cidr"
  19. "github.com/slackhq/nebula/config"
  20. "github.com/slackhq/nebula/firewall"
  21. )
  22. const tcpACK = 0x10
  23. const tcpFIN = 0x01
  24. type FirewallInterface interface {
  25. AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, ip *net.IPNet, localIp *net.IPNet, caName string, caSha string) error
  26. }
  27. type conn struct {
  28. Expires time.Time // Time when this conntrack entry will expire
  29. Sent time.Time // If tcp rtt tracking is enabled this will be when Seq was last set
  30. Seq uint32 // If tcp rtt tracking is enabled this will be the seq we are looking for an ack
  31. // record why the original connection passed the firewall, so we can re-validate
  32. // after ruleset changes. Note, rulesVersion is a uint16 so that these two
  33. // fields pack for free after the uint32 above
  34. incoming bool
  35. rulesVersion uint16
  36. }
  37. // TODO: need conntrack max tracked connections handling
  38. type Firewall struct {
  39. Conntrack *FirewallConntrack
  40. InRules *FirewallTable
  41. OutRules *FirewallTable
  42. InSendReject bool
  43. OutSendReject bool
  44. //TODO: we should have many more options for TCP, an option for ICMP, and mimic the kernel a bit better
  45. // https://www.kernel.org/doc/Documentation/networking/nf_conntrack-sysctl.txt
  46. TCPTimeout time.Duration //linux: 5 days max
  47. UDPTimeout time.Duration //linux: 180s max
  48. DefaultTimeout time.Duration //linux: 600s
  49. // Used to ensure we don't emit local packets for ips we don't own
  50. localIps *cidr.Tree4[struct{}]
  51. assignedCIDR *net.IPNet
  52. hasSubnets bool
  53. rules string
  54. rulesVersion uint16
  55. defaultLocalCIDRAny bool
  56. trackTCPRTT bool
  57. metricTCPRTT metrics.Histogram
  58. incomingMetrics firewallMetrics
  59. outgoingMetrics firewallMetrics
  60. l *logrus.Logger
  61. }
  62. type firewallMetrics struct {
  63. droppedLocalIP metrics.Counter
  64. droppedRemoteIP metrics.Counter
  65. droppedNoRule metrics.Counter
  66. }
  67. type FirewallConntrack struct {
  68. sync.Mutex
  69. Conns map[firewall.Packet]*conn
  70. TimerWheel *TimerWheel[firewall.Packet]
  71. }
  72. // FirewallTable is the entry point for a rule, the evaluation order is:
  73. // Proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR)
  74. type FirewallTable struct {
  75. TCP firewallPort
  76. UDP firewallPort
  77. ICMP firewallPort
  78. AnyProto firewallPort
  79. }
  80. func newFirewallTable() *FirewallTable {
  81. return &FirewallTable{
  82. TCP: firewallPort{},
  83. UDP: firewallPort{},
  84. ICMP: firewallPort{},
  85. AnyProto: firewallPort{},
  86. }
  87. }
  88. type FirewallCA struct {
  89. Any *FirewallRule
  90. CANames map[string]*FirewallRule
  91. CAShas map[string]*FirewallRule
  92. }
  93. type FirewallRule struct {
  94. // Any makes Hosts, Groups, and CIDR irrelevant
  95. Any *firewallLocalCIDR
  96. Hosts map[string]*firewallLocalCIDR
  97. Groups []*firewallGroups
  98. CIDR *cidr.Tree4[*firewallLocalCIDR]
  99. }
  100. type firewallGroups struct {
  101. Groups []string
  102. LocalCIDR *firewallLocalCIDR
  103. }
  104. // Even though ports are uint16, int32 maps are faster for lookup
  105. // Plus we can use `-1` for fragment rules
  106. type firewallPort map[int32]*FirewallCA
  107. type firewallLocalCIDR struct {
  108. Any bool
  109. LocalCIDR *cidr.Tree4[struct{}]
  110. }
  111. // NewFirewall creates a new Firewall object. A TimerWheel is created for you from the provided timeouts.
  112. func NewFirewall(l *logrus.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c *cert.NebulaCertificate) *Firewall {
  113. //TODO: error on 0 duration
  114. var min, max time.Duration
  115. if tcpTimeout < UDPTimeout {
  116. min = tcpTimeout
  117. max = UDPTimeout
  118. } else {
  119. min = UDPTimeout
  120. max = tcpTimeout
  121. }
  122. if defaultTimeout < min {
  123. min = defaultTimeout
  124. } else if defaultTimeout > max {
  125. max = defaultTimeout
  126. }
  127. localIps := cidr.NewTree4[struct{}]()
  128. var assignedCIDR *net.IPNet
  129. for _, ip := range c.Details.Ips {
  130. ipNet := &net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}
  131. localIps.AddCIDR(ipNet, struct{}{})
  132. if assignedCIDR == nil {
  133. // Only grabbing the first one in the cert since any more than that currently has undefined behavior
  134. assignedCIDR = ipNet
  135. }
  136. }
  137. for _, n := range c.Details.Subnets {
  138. localIps.AddCIDR(n, struct{}{})
  139. }
  140. return &Firewall{
  141. Conntrack: &FirewallConntrack{
  142. Conns: make(map[firewall.Packet]*conn),
  143. TimerWheel: NewTimerWheel[firewall.Packet](min, max),
  144. },
  145. InRules: newFirewallTable(),
  146. OutRules: newFirewallTable(),
  147. TCPTimeout: tcpTimeout,
  148. UDPTimeout: UDPTimeout,
  149. DefaultTimeout: defaultTimeout,
  150. localIps: localIps,
  151. assignedCIDR: assignedCIDR,
  152. hasSubnets: len(c.Details.Subnets) > 0,
  153. l: l,
  154. metricTCPRTT: metrics.GetOrRegisterHistogram("network.tcp.rtt", nil, metrics.NewExpDecaySample(1028, 0.015)),
  155. incomingMetrics: firewallMetrics{
  156. droppedLocalIP: metrics.GetOrRegisterCounter("firewall.incoming.dropped.local_ip", nil),
  157. droppedRemoteIP: metrics.GetOrRegisterCounter("firewall.incoming.dropped.remote_ip", nil),
  158. droppedNoRule: metrics.GetOrRegisterCounter("firewall.incoming.dropped.no_rule", nil),
  159. },
  160. outgoingMetrics: firewallMetrics{
  161. droppedLocalIP: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.local_ip", nil),
  162. droppedRemoteIP: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.remote_ip", nil),
  163. droppedNoRule: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.no_rule", nil),
  164. },
  165. }
  166. }
  167. func NewFirewallFromConfig(l *logrus.Logger, nc *cert.NebulaCertificate, c *config.C) (*Firewall, error) {
  168. fw := NewFirewall(
  169. l,
  170. c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12),
  171. c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3),
  172. c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10),
  173. nc,
  174. //TODO: max_connections
  175. )
  176. //TODO: Flip to false after v1.9 release
  177. fw.defaultLocalCIDRAny = c.GetBool("firewall.default_local_cidr_any", true)
  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 *net.IPNet, localIp *net.IPNet, 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 != nil {
  214. sIp = ip.String()
  215. }
  216. lIp := ""
  217. if localIp != nil {
  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:
  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.([]interface{})
  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 *net.IPNet
  333. if r.Cidr != "" {
  334. _, cidr, err = net.ParseCIDR(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 *net.IPNet
  340. if r.LocalCidr != "" {
  341. _, localCidr, err = net.ParseCIDR(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(packet []byte, fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.NebulaCAPool, localCache firewall.ConntrackCache) error {
  359. // Check if we spoke to this tuple, if we did then allow this packet
  360. if f.inConns(packet, fp, incoming, h, caPool, localCache) {
  361. return nil
  362. }
  363. // Make sure remote address matches nebula certificate
  364. if remoteCidr := h.remoteCidr; remoteCidr != nil {
  365. ok, _ := remoteCidr.Contains(fp.RemoteIP)
  366. if !ok {
  367. f.metrics(incoming).droppedRemoteIP.Inc(1)
  368. return ErrInvalidRemoteIP
  369. }
  370. } else {
  371. // Simple case: Certificate has one IP and no subnets
  372. if fp.RemoteIP != h.vpnIp {
  373. f.metrics(incoming).droppedRemoteIP.Inc(1)
  374. return ErrInvalidRemoteIP
  375. }
  376. }
  377. // Make sure we are supposed to be handling this local ip address
  378. ok, _ := f.localIps.Contains(fp.LocalIP)
  379. if !ok {
  380. f.metrics(incoming).droppedLocalIP.Inc(1)
  381. return ErrInvalidLocalIP
  382. }
  383. table := f.OutRules
  384. if incoming {
  385. table = f.InRules
  386. }
  387. // We now know which firewall table to check against
  388. if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
  389. f.metrics(incoming).droppedNoRule.Inc(1)
  390. return ErrNoMatchingRule
  391. }
  392. // We always want to conntrack since it is a faster operation
  393. f.addConn(packet, fp, incoming)
  394. return nil
  395. }
  396. func (f *Firewall) metrics(incoming bool) firewallMetrics {
  397. if incoming {
  398. return f.incomingMetrics
  399. } else {
  400. return f.outgoingMetrics
  401. }
  402. }
  403. // Destroy cleans up any known cyclical references so the object can be free'd my GC. This should be called if a new
  404. // firewall object is created
  405. func (f *Firewall) Destroy() {
  406. //TODO: clean references if/when needed
  407. }
  408. func (f *Firewall) EmitStats() {
  409. conntrack := f.Conntrack
  410. conntrack.Lock()
  411. conntrackCount := len(conntrack.Conns)
  412. conntrack.Unlock()
  413. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  414. metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
  415. metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
  416. }
  417. func (f *Firewall) inConns(packet []byte, fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.NebulaCAPool, localCache firewall.ConntrackCache) bool {
  418. if localCache != nil {
  419. if _, ok := localCache[fp]; ok {
  420. return true
  421. }
  422. }
  423. conntrack := f.Conntrack
  424. conntrack.Lock()
  425. // Purge every time we test
  426. ep, has := conntrack.TimerWheel.Purge()
  427. if has {
  428. f.evict(ep)
  429. }
  430. c, ok := conntrack.Conns[fp]
  431. if !ok {
  432. conntrack.Unlock()
  433. return false
  434. }
  435. if c.rulesVersion != f.rulesVersion {
  436. // This conntrack entry was for an older rule set, validate
  437. // it still passes with the current rule set
  438. table := f.OutRules
  439. if c.incoming {
  440. table = f.InRules
  441. }
  442. // We now know which firewall table to check against
  443. if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
  444. if f.l.Level >= logrus.DebugLevel {
  445. h.logger(f.l).
  446. WithField("fwPacket", fp).
  447. WithField("incoming", c.incoming).
  448. WithField("rulesVersion", f.rulesVersion).
  449. WithField("oldRulesVersion", c.rulesVersion).
  450. Debugln("dropping old conntrack entry, does not match new ruleset")
  451. }
  452. delete(conntrack.Conns, fp)
  453. conntrack.Unlock()
  454. return false
  455. }
  456. if f.l.Level >= logrus.DebugLevel {
  457. h.logger(f.l).
  458. WithField("fwPacket", fp).
  459. WithField("incoming", c.incoming).
  460. WithField("rulesVersion", f.rulesVersion).
  461. WithField("oldRulesVersion", c.rulesVersion).
  462. Debugln("keeping old conntrack entry, does match new ruleset")
  463. }
  464. c.rulesVersion = f.rulesVersion
  465. }
  466. switch fp.Protocol {
  467. case firewall.ProtoTCP:
  468. c.Expires = time.Now().Add(f.TCPTimeout)
  469. if incoming {
  470. f.checkTCPRTT(c, packet)
  471. } else {
  472. setTCPRTTTracking(c, packet)
  473. }
  474. case firewall.ProtoUDP:
  475. c.Expires = time.Now().Add(f.UDPTimeout)
  476. default:
  477. c.Expires = time.Now().Add(f.DefaultTimeout)
  478. }
  479. conntrack.Unlock()
  480. if localCache != nil {
  481. localCache[fp] = struct{}{}
  482. }
  483. return true
  484. }
  485. func (f *Firewall) addConn(packet []byte, fp firewall.Packet, incoming bool) {
  486. var timeout time.Duration
  487. c := &conn{}
  488. switch fp.Protocol {
  489. case firewall.ProtoTCP:
  490. timeout = f.TCPTimeout
  491. if !incoming {
  492. setTCPRTTTracking(c, packet)
  493. }
  494. case firewall.ProtoUDP:
  495. timeout = f.UDPTimeout
  496. default:
  497. timeout = f.DefaultTimeout
  498. }
  499. conntrack := f.Conntrack
  500. conntrack.Lock()
  501. if _, ok := conntrack.Conns[fp]; !ok {
  502. conntrack.TimerWheel.Advance(time.Now())
  503. conntrack.TimerWheel.Add(fp, timeout)
  504. }
  505. // Record which rulesVersion allowed this connection, so we can retest after
  506. // firewall reload
  507. c.incoming = incoming
  508. c.rulesVersion = f.rulesVersion
  509. c.Expires = time.Now().Add(timeout)
  510. conntrack.Conns[fp] = c
  511. conntrack.Unlock()
  512. }
  513. // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
  514. // Caller must own the connMutex lock!
  515. func (f *Firewall) evict(p firewall.Packet) {
  516. //TODO: report a stat if the tcp rtt tracking was never resolved?
  517. // Are we still tracking this conn?
  518. conntrack := f.Conntrack
  519. t, ok := conntrack.Conns[p]
  520. if !ok {
  521. return
  522. }
  523. newT := t.Expires.Sub(time.Now())
  524. // Timeout is in the future, re-add the timer
  525. if newT > 0 {
  526. conntrack.TimerWheel.Advance(time.Now())
  527. conntrack.TimerWheel.Add(p, newT)
  528. return
  529. }
  530. // This conn is done
  531. delete(conntrack.Conns, p)
  532. }
  533. func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.NebulaCertificate, caPool *cert.NebulaCAPool) bool {
  534. if ft.AnyProto.match(p, incoming, c, caPool) {
  535. return true
  536. }
  537. switch p.Protocol {
  538. case firewall.ProtoTCP:
  539. if ft.TCP.match(p, incoming, c, caPool) {
  540. return true
  541. }
  542. case firewall.ProtoUDP:
  543. if ft.UDP.match(p, incoming, c, caPool) {
  544. return true
  545. }
  546. case firewall.ProtoICMP:
  547. if ft.ICMP.match(p, incoming, c, caPool) {
  548. return true
  549. }
  550. }
  551. return false
  552. }
  553. func (fp firewallPort) addRule(f *Firewall, startPort int32, endPort int32, groups []string, host string, ip *net.IPNet, localIp *net.IPNet, caName string, caSha string) error {
  554. if startPort > endPort {
  555. return fmt.Errorf("start port was lower than end port")
  556. }
  557. for i := startPort; i <= endPort; i++ {
  558. if _, ok := fp[i]; !ok {
  559. fp[i] = &FirewallCA{
  560. CANames: make(map[string]*FirewallRule),
  561. CAShas: make(map[string]*FirewallRule),
  562. }
  563. }
  564. if err := fp[i].addRule(f, groups, host, ip, localIp, caName, caSha); err != nil {
  565. return err
  566. }
  567. }
  568. return nil
  569. }
  570. func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.NebulaCertificate, caPool *cert.NebulaCAPool) bool {
  571. // We don't have any allowed ports, bail
  572. if fp == nil {
  573. return false
  574. }
  575. var port int32
  576. if p.Fragment {
  577. port = firewall.PortFragment
  578. } else if incoming {
  579. port = int32(p.LocalPort)
  580. } else {
  581. port = int32(p.RemotePort)
  582. }
  583. if fp[port].match(p, c, caPool) {
  584. return true
  585. }
  586. return fp[firewall.PortAny].match(p, c, caPool)
  587. }
  588. func (fc *FirewallCA) addRule(f *Firewall, groups []string, host string, ip, localIp *net.IPNet, caName, caSha string) error {
  589. fr := func() *FirewallRule {
  590. return &FirewallRule{
  591. Hosts: make(map[string]*firewallLocalCIDR),
  592. Groups: make([]*firewallGroups, 0),
  593. CIDR: cidr.NewTree4[*firewallLocalCIDR](),
  594. }
  595. }
  596. if caSha == "" && caName == "" {
  597. if fc.Any == nil {
  598. fc.Any = fr()
  599. }
  600. return fc.Any.addRule(f, groups, host, ip, localIp)
  601. }
  602. if caSha != "" {
  603. if _, ok := fc.CAShas[caSha]; !ok {
  604. fc.CAShas[caSha] = fr()
  605. }
  606. err := fc.CAShas[caSha].addRule(f, groups, host, ip, localIp)
  607. if err != nil {
  608. return err
  609. }
  610. }
  611. if caName != "" {
  612. if _, ok := fc.CANames[caName]; !ok {
  613. fc.CANames[caName] = fr()
  614. }
  615. err := fc.CANames[caName].addRule(f, groups, host, ip, localIp)
  616. if err != nil {
  617. return err
  618. }
  619. }
  620. return nil
  621. }
  622. func (fc *FirewallCA) match(p firewall.Packet, c *cert.NebulaCertificate, caPool *cert.NebulaCAPool) bool {
  623. if fc == nil {
  624. return false
  625. }
  626. if fc.Any.match(p, c) {
  627. return true
  628. }
  629. if t, ok := fc.CAShas[c.Details.Issuer]; ok {
  630. if t.match(p, c) {
  631. return true
  632. }
  633. }
  634. s, err := caPool.GetCAForCert(c)
  635. if err != nil {
  636. return false
  637. }
  638. return fc.CANames[s.Details.Name].match(p, c)
  639. }
  640. func (fr *FirewallRule) addRule(f *Firewall, groups []string, host string, ip *net.IPNet, localCIDR *net.IPNet) error {
  641. flc := func() *firewallLocalCIDR {
  642. return &firewallLocalCIDR{
  643. LocalCIDR: cidr.NewTree4[struct{}](),
  644. }
  645. }
  646. if fr.isAny(groups, host, ip) {
  647. if fr.Any == nil {
  648. fr.Any = flc()
  649. }
  650. return fr.Any.addRule(f, localCIDR)
  651. }
  652. if len(groups) > 0 {
  653. nlc := flc()
  654. err := nlc.addRule(f, localCIDR)
  655. if err != nil {
  656. return err
  657. }
  658. fr.Groups = append(fr.Groups, &firewallGroups{
  659. Groups: groups,
  660. LocalCIDR: nlc,
  661. })
  662. }
  663. if host != "" {
  664. nlc := fr.Hosts[host]
  665. if nlc == nil {
  666. nlc = flc()
  667. }
  668. err := nlc.addRule(f, localCIDR)
  669. if err != nil {
  670. return err
  671. }
  672. fr.Hosts[host] = nlc
  673. }
  674. if ip != nil {
  675. _, nlc := fr.CIDR.GetCIDR(ip)
  676. if nlc == nil {
  677. nlc = flc()
  678. }
  679. err := nlc.addRule(f, localCIDR)
  680. if err != nil {
  681. return err
  682. }
  683. fr.CIDR.AddCIDR(ip, nlc)
  684. }
  685. return nil
  686. }
  687. func (fr *FirewallRule) isAny(groups []string, host string, ip *net.IPNet) bool {
  688. if len(groups) == 0 && host == "" && ip == nil {
  689. return true
  690. }
  691. for _, group := range groups {
  692. if group == "any" {
  693. return true
  694. }
  695. }
  696. if host == "any" {
  697. return true
  698. }
  699. if ip != nil && ip.Contains(net.IPv4(0, 0, 0, 0)) {
  700. return true
  701. }
  702. return false
  703. }
  704. func (fr *FirewallRule) match(p firewall.Packet, c *cert.NebulaCertificate) bool {
  705. if fr == nil {
  706. return false
  707. }
  708. // Shortcut path for if groups, hosts, or cidr contained an `any`
  709. if fr.Any.match(p, c) {
  710. return true
  711. }
  712. // Need any of group, host, or cidr to match
  713. for _, sg := range fr.Groups {
  714. found := false
  715. for _, g := range sg.Groups {
  716. if _, ok := c.Details.InvertedGroups[g]; !ok {
  717. found = false
  718. break
  719. }
  720. found = true
  721. }
  722. if found && sg.LocalCIDR.match(p, c) {
  723. return true
  724. }
  725. }
  726. if fr.Hosts != nil {
  727. if flc, ok := fr.Hosts[c.Details.Name]; ok {
  728. if flc.match(p, c) {
  729. return true
  730. }
  731. }
  732. }
  733. return fr.CIDR.EachContains(p.RemoteIP, func(flc *firewallLocalCIDR) bool {
  734. return flc.match(p, c)
  735. })
  736. }
  737. func (flc *firewallLocalCIDR) addRule(f *Firewall, localIp *net.IPNet) error {
  738. if localIp == nil || (localIp != nil && localIp.Contains(net.IPv4(0, 0, 0, 0))) {
  739. if !f.hasSubnets || f.defaultLocalCIDRAny {
  740. flc.Any = true
  741. return nil
  742. }
  743. localIp = f.assignedCIDR
  744. }
  745. flc.LocalCIDR.AddCIDR(localIp, struct{}{})
  746. return nil
  747. }
  748. func (flc *firewallLocalCIDR) match(p firewall.Packet, c *cert.NebulaCertificate) bool {
  749. if flc == nil {
  750. return false
  751. }
  752. if flc.Any {
  753. return true
  754. }
  755. ok, _ := flc.LocalCIDR.Contains(p.LocalIP)
  756. return ok
  757. }
  758. type rule struct {
  759. Port string
  760. Code string
  761. Proto string
  762. Host string
  763. Group string
  764. Groups []string
  765. Cidr string
  766. LocalCidr string
  767. CAName string
  768. CASha string
  769. }
  770. func convertRule(l *logrus.Logger, p interface{}, table string, i int) (rule, error) {
  771. r := rule{}
  772. m, ok := p.(map[interface{}]interface{})
  773. if !ok {
  774. return r, errors.New("could not parse rule")
  775. }
  776. toString := func(k string, m map[interface{}]interface{}) string {
  777. v, ok := m[k]
  778. if !ok {
  779. return ""
  780. }
  781. return fmt.Sprintf("%v", v)
  782. }
  783. r.Port = toString("port", m)
  784. r.Code = toString("code", m)
  785. r.Proto = toString("proto", m)
  786. r.Host = toString("host", m)
  787. r.Cidr = toString("cidr", m)
  788. r.LocalCidr = toString("local_cidr", m)
  789. r.CAName = toString("ca_name", m)
  790. r.CASha = toString("ca_sha", m)
  791. // Make sure group isn't an array
  792. if v, ok := m["group"].([]interface{}); ok {
  793. if len(v) > 1 {
  794. return r, errors.New("group should contain a single value, an array with more than one entry was provided")
  795. }
  796. l.Warnf("%s rule #%v; group was an array with a single value, converting to simple value", table, i)
  797. m["group"] = v[0]
  798. }
  799. r.Group = toString("group", m)
  800. if rg, ok := m["groups"]; ok {
  801. switch reflect.TypeOf(rg).Kind() {
  802. case reflect.Slice:
  803. v := reflect.ValueOf(rg)
  804. r.Groups = make([]string, v.Len())
  805. for i := 0; i < v.Len(); i++ {
  806. r.Groups[i] = v.Index(i).Interface().(string)
  807. }
  808. case reflect.String:
  809. r.Groups = []string{rg.(string)}
  810. default:
  811. r.Groups = []string{fmt.Sprintf("%v", rg)}
  812. }
  813. }
  814. return r, nil
  815. }
  816. func parsePort(s string) (startPort, endPort int32, err error) {
  817. if s == "any" {
  818. startPort = firewall.PortAny
  819. endPort = firewall.PortAny
  820. } else if s == "fragment" {
  821. startPort = firewall.PortFragment
  822. endPort = firewall.PortFragment
  823. } else if strings.Contains(s, `-`) {
  824. sPorts := strings.SplitN(s, `-`, 2)
  825. sPorts[0] = strings.Trim(sPorts[0], " ")
  826. sPorts[1] = strings.Trim(sPorts[1], " ")
  827. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  828. return 0, 0, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  829. }
  830. rStartPort, err := strconv.Atoi(sPorts[0])
  831. if err != nil {
  832. return 0, 0, fmt.Errorf("beginning range was not a number; `%s`", sPorts[0])
  833. }
  834. rEndPort, err := strconv.Atoi(sPorts[1])
  835. if err != nil {
  836. return 0, 0, fmt.Errorf("ending range was not a number; `%s`", sPorts[1])
  837. }
  838. startPort = int32(rStartPort)
  839. endPort = int32(rEndPort)
  840. if startPort == firewall.PortAny {
  841. endPort = firewall.PortAny
  842. }
  843. } else {
  844. rPort, err := strconv.Atoi(s)
  845. if err != nil {
  846. return 0, 0, fmt.Errorf("was not a number; `%s`", s)
  847. }
  848. startPort = int32(rPort)
  849. endPort = startPort
  850. }
  851. return
  852. }
  853. // TODO: write tests for these
  854. func setTCPRTTTracking(c *conn, p []byte) {
  855. if c.Seq != 0 {
  856. return
  857. }
  858. ihl := int(p[0]&0x0f) << 2
  859. // Don't track FIN packets
  860. if p[ihl+13]&tcpFIN != 0 {
  861. return
  862. }
  863. c.Seq = binary.BigEndian.Uint32(p[ihl+4 : ihl+8])
  864. c.Sent = time.Now()
  865. }
  866. func (f *Firewall) checkTCPRTT(c *conn, p []byte) bool {
  867. if c.Seq == 0 {
  868. return false
  869. }
  870. ihl := int(p[0]&0x0f) << 2
  871. if p[ihl+13]&tcpACK == 0 {
  872. return false
  873. }
  874. // Deal with wrap around, signed int cuts the ack window in half
  875. // 0 is a bad ack, no data acknowledged
  876. // positive number is a bad ack, ack is over half the window away
  877. if int32(c.Seq-binary.BigEndian.Uint32(p[ihl+8:ihl+12])) >= 0 {
  878. return false
  879. }
  880. f.metricTCPRTT.Update(time.Since(c.Sent).Nanoseconds())
  881. c.Seq = 0
  882. return true
  883. }