firewall.go 19 KB

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