firewall.go 24 KB

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