firewall.go 23 KB

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