firewall.go 21 KB

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