firewall.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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 h.remoteCidr.Contains(fp.RemoteIP) == nil {
  300. return true
  301. }
  302. // Make sure we are supposed to be handling this local ip address
  303. if f.localIps.Contains(fp.LocalIP) == nil {
  304. return true
  305. }
  306. table := f.OutRules
  307. if incoming {
  308. table = f.InRules
  309. }
  310. // We now know which firewall table to check against
  311. if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
  312. return true
  313. }
  314. // We always want to conntrack since it is a faster operation
  315. f.addConn(packet, fp, incoming)
  316. return false
  317. }
  318. // Destroy cleans up any known cyclical references so the object can be free'd my GC. This should be called if a new
  319. // firewall object is created
  320. func (f *Firewall) Destroy() {
  321. //TODO: clean references if/when needed
  322. }
  323. func (f *Firewall) EmitStats() {
  324. conntrackCount := len(f.Conns)
  325. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  326. }
  327. func (f *Firewall) inConns(packet []byte, fp FirewallPacket, incoming bool) bool {
  328. f.connMutex.Lock()
  329. // Purge every time we test
  330. ep, has := f.TimerWheel.Purge()
  331. if has {
  332. f.evict(ep)
  333. }
  334. c, ok := f.Conns[fp]
  335. if !ok {
  336. f.connMutex.Unlock()
  337. return false
  338. }
  339. switch fp.Protocol {
  340. case fwProtoTCP:
  341. c.Expires = time.Now().Add(f.TCPTimeout)
  342. if incoming {
  343. f.checkTCPRTT(c, packet)
  344. } else {
  345. setTCPRTTTracking(c, packet)
  346. }
  347. case fwProtoUDP:
  348. c.Expires = time.Now().Add(f.UDPTimeout)
  349. default:
  350. c.Expires = time.Now().Add(f.DefaultTimeout)
  351. }
  352. f.connMutex.Unlock()
  353. return true
  354. }
  355. func (f *Firewall) addConn(packet []byte, fp FirewallPacket, incoming bool) {
  356. var timeout time.Duration
  357. c := &conn{}
  358. switch fp.Protocol {
  359. case fwProtoTCP:
  360. timeout = f.TCPTimeout
  361. if !incoming {
  362. setTCPRTTTracking(c, packet)
  363. }
  364. case fwProtoUDP:
  365. timeout = f.UDPTimeout
  366. default:
  367. timeout = f.DefaultTimeout
  368. }
  369. f.connMutex.Lock()
  370. if _, ok := f.Conns[fp]; !ok {
  371. f.TimerWheel.Add(fp, timeout)
  372. }
  373. c.Expires = time.Now().Add(timeout)
  374. f.Conns[fp] = c
  375. f.connMutex.Unlock()
  376. }
  377. // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
  378. // Caller must own the connMutex lock!
  379. func (f *Firewall) evict(p FirewallPacket) {
  380. //TODO: report a stat if the tcp rtt tracking was never resolved?
  381. // Are we still tracking this conn?
  382. t, ok := f.Conns[p]
  383. if !ok {
  384. return
  385. }
  386. newT := t.Expires.Sub(time.Now())
  387. // Timeout is in the future, re-add the timer
  388. if newT > 0 {
  389. f.TimerWheel.Add(p, newT)
  390. return
  391. }
  392. // This conn is done
  393. delete(f.Conns, p)
  394. }
  395. func (ft *FirewallTable) match(p FirewallPacket, incoming bool, c *cert.NebulaCertificate, caPool *cert.NebulaCAPool) bool {
  396. if ft.AnyProto.match(p, incoming, c, caPool) {
  397. return true
  398. }
  399. switch p.Protocol {
  400. case fwProtoTCP:
  401. if ft.TCP.match(p, incoming, c, caPool) {
  402. return true
  403. }
  404. case fwProtoUDP:
  405. if ft.UDP.match(p, incoming, c, caPool) {
  406. return true
  407. }
  408. case fwProtoICMP:
  409. if ft.ICMP.match(p, incoming, c, caPool) {
  410. return true
  411. }
  412. }
  413. return false
  414. }
  415. func (fp firewallPort) addRule(startPort int32, endPort int32, groups []string, host string, ip *net.IPNet, caName string, caSha string) error {
  416. if startPort > endPort {
  417. return fmt.Errorf("start port was lower than end port")
  418. }
  419. for i := startPort; i <= endPort; i++ {
  420. if _, ok := fp[i]; !ok {
  421. fp[i] = &FirewallCA{
  422. CANames: make(map[string]*FirewallRule),
  423. CAShas: make(map[string]*FirewallRule),
  424. }
  425. }
  426. if err := fp[i].addRule(groups, host, ip, caName, caSha); err != nil {
  427. return err
  428. }
  429. }
  430. return nil
  431. }
  432. func (fp firewallPort) match(p FirewallPacket, incoming bool, c *cert.NebulaCertificate, caPool *cert.NebulaCAPool) bool {
  433. // We don't have any allowed ports, bail
  434. if fp == nil {
  435. return false
  436. }
  437. var port int32
  438. if p.Fragment {
  439. port = fwPortFragment
  440. } else if incoming {
  441. port = int32(p.LocalPort)
  442. } else {
  443. port = int32(p.RemotePort)
  444. }
  445. if fp[port].match(p, c, caPool) {
  446. return true
  447. }
  448. return fp[fwPortAny].match(p, c, caPool)
  449. }
  450. func (fc *FirewallCA) addRule(groups []string, host string, ip *net.IPNet, caName, caSha string) error {
  451. // If there is an any rule then there is no need to establish specific ca rules
  452. if fc.Any != nil {
  453. return fc.Any.addRule(groups, host, ip)
  454. }
  455. fr := func() *FirewallRule {
  456. return &FirewallRule{
  457. Hosts: make(map[string]struct{}),
  458. Groups: make([][]string, 0),
  459. CIDR: NewCIDRTree(),
  460. }
  461. }
  462. any := false
  463. if caSha == "" && caName == "" {
  464. any = true
  465. }
  466. if any {
  467. if fc.Any == nil {
  468. fc.Any = fr()
  469. }
  470. // If it's any we need to wipe out any pre-existing rules to save on memory
  471. fc.CAShas = make(map[string]*FirewallRule)
  472. fc.CANames = make(map[string]*FirewallRule)
  473. return fc.Any.addRule(groups, host, ip)
  474. }
  475. if caSha != "" {
  476. if _, ok := fc.CAShas[caSha]; !ok {
  477. fc.CAShas[caSha] = fr()
  478. }
  479. err := fc.CAShas[caSha].addRule(groups, host, ip)
  480. if err != nil {
  481. return err
  482. }
  483. }
  484. if caName != "" {
  485. if _, ok := fc.CANames[caName]; !ok {
  486. fc.CANames[caName] = fr()
  487. }
  488. err := fc.CANames[caName].addRule(groups, host, ip)
  489. if err != nil {
  490. return err
  491. }
  492. }
  493. return nil
  494. }
  495. func (fc *FirewallCA) match(p FirewallPacket, c *cert.NebulaCertificate, caPool *cert.NebulaCAPool) bool {
  496. if fc == nil {
  497. return false
  498. }
  499. if fc.Any != nil {
  500. return fc.Any.match(p, c)
  501. }
  502. if t, ok := fc.CAShas[c.Details.Issuer]; ok {
  503. if t.match(p, c) {
  504. return true
  505. }
  506. }
  507. s, err := caPool.GetCAForCert(c)
  508. if err != nil {
  509. return false
  510. }
  511. return fc.CANames[s.Details.Name].match(p, c)
  512. }
  513. func (fr *FirewallRule) addRule(groups []string, host string, ip *net.IPNet) error {
  514. if fr.Any {
  515. return nil
  516. }
  517. if fr.isAny(groups, host, ip) {
  518. fr.Any = true
  519. // If it's any we need to wipe out any pre-existing rules to save on memory
  520. fr.Groups = make([][]string, 0)
  521. fr.Hosts = make(map[string]struct{})
  522. fr.CIDR = NewCIDRTree()
  523. } else {
  524. if len(groups) > 0 {
  525. fr.Groups = append(fr.Groups, groups)
  526. }
  527. if host != "" {
  528. fr.Hosts[host] = struct{}{}
  529. }
  530. if ip != nil {
  531. fr.CIDR.AddCIDR(ip, struct{}{})
  532. }
  533. }
  534. return nil
  535. }
  536. func (fr *FirewallRule) isAny(groups []string, host string, ip *net.IPNet) bool {
  537. for _, group := range groups {
  538. if group == "any" {
  539. return true
  540. }
  541. }
  542. if host == "any" {
  543. return true
  544. }
  545. if ip != nil && ip.Contains(net.IPv4(0, 0, 0, 0)) {
  546. return true
  547. }
  548. return false
  549. }
  550. func (fr *FirewallRule) match(p FirewallPacket, c *cert.NebulaCertificate) bool {
  551. if fr == nil {
  552. return false
  553. }
  554. // Shortcut path for if groups, hosts, or cidr contained an `any`
  555. if fr.Any {
  556. return true
  557. }
  558. // Need any of group, host, or cidr to match
  559. for _, sg := range fr.Groups {
  560. found := false
  561. for _, g := range sg {
  562. if _, ok := c.Details.InvertedGroups[g]; !ok {
  563. found = false
  564. break
  565. }
  566. found = true
  567. }
  568. if found {
  569. return true
  570. }
  571. }
  572. if fr.Hosts != nil {
  573. if _, ok := fr.Hosts[c.Details.Name]; ok {
  574. return true
  575. }
  576. }
  577. if fr.CIDR != nil && fr.CIDR.Contains(p.RemoteIP) != nil {
  578. return true
  579. }
  580. // No host, group, or cidr matched, bye bye
  581. return false
  582. }
  583. type rule struct {
  584. Port string
  585. Code string
  586. Proto string
  587. Host string
  588. Group string
  589. Groups []string
  590. Cidr string
  591. CAName string
  592. CASha string
  593. }
  594. func convertRule(p interface{}, table string, i int) (rule, error) {
  595. r := rule{}
  596. m, ok := p.(map[interface{}]interface{})
  597. if !ok {
  598. return r, errors.New("could not parse rule")
  599. }
  600. toString := func(k string, m map[interface{}]interface{}) string {
  601. v, ok := m[k]
  602. if !ok {
  603. return ""
  604. }
  605. return fmt.Sprintf("%v", v)
  606. }
  607. r.Port = toString("port", m)
  608. r.Code = toString("code", m)
  609. r.Proto = toString("proto", m)
  610. r.Host = toString("host", m)
  611. r.Cidr = toString("cidr", m)
  612. r.CAName = toString("ca_name", m)
  613. r.CASha = toString("ca_sha", m)
  614. // Make sure group isn't an array
  615. if v, ok := m["group"].([]interface{}); ok {
  616. if len(v) > 1 {
  617. return r, errors.New("group should contain a single value, an array with more than one entry was provided")
  618. }
  619. l.Warnf("%s rule #%v; group was an array with a single value, converting to simple value", table, i)
  620. m["group"] = v[0]
  621. }
  622. r.Group = toString("group", m)
  623. if rg, ok := m["groups"]; ok {
  624. switch reflect.TypeOf(rg).Kind() {
  625. case reflect.Slice:
  626. v := reflect.ValueOf(rg)
  627. r.Groups = make([]string, v.Len())
  628. for i := 0; i < v.Len(); i++ {
  629. r.Groups[i] = v.Index(i).Interface().(string)
  630. }
  631. case reflect.String:
  632. r.Groups = []string{rg.(string)}
  633. default:
  634. r.Groups = []string{fmt.Sprintf("%v", rg)}
  635. }
  636. }
  637. return r, nil
  638. }
  639. func parsePort(s string) (startPort, endPort int32, err error) {
  640. if s == "any" {
  641. startPort = fwPortAny
  642. endPort = fwPortAny
  643. } else if s == "fragment" {
  644. startPort = fwPortFragment
  645. endPort = fwPortFragment
  646. } else if strings.Contains(s, `-`) {
  647. sPorts := strings.SplitN(s, `-`, 2)
  648. sPorts[0] = strings.Trim(sPorts[0], " ")
  649. sPorts[1] = strings.Trim(sPorts[1], " ")
  650. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  651. return 0, 0, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  652. }
  653. rStartPort, err := strconv.Atoi(sPorts[0])
  654. if err != nil {
  655. return 0, 0, fmt.Errorf("beginning range was not a number; `%s`", sPorts[0])
  656. }
  657. rEndPort, err := strconv.Atoi(sPorts[1])
  658. if err != nil {
  659. return 0, 0, fmt.Errorf("ending range was not a number; `%s`", sPorts[1])
  660. }
  661. startPort = int32(rStartPort)
  662. endPort = int32(rEndPort)
  663. if startPort == fwPortAny {
  664. endPort = fwPortAny
  665. }
  666. } else {
  667. rPort, err := strconv.Atoi(s)
  668. if err != nil {
  669. return 0, 0, fmt.Errorf("was not a number; `%s`", s)
  670. }
  671. startPort = int32(rPort)
  672. endPort = startPort
  673. }
  674. return
  675. }
  676. //TODO: write tests for these
  677. func setTCPRTTTracking(c *conn, p []byte) {
  678. if c.Seq != 0 {
  679. return
  680. }
  681. ihl := int(p[0]&0x0f) << 2
  682. // Don't track FIN packets
  683. if p[ihl+13]&tcpFIN != 0 {
  684. return
  685. }
  686. c.Seq = binary.BigEndian.Uint32(p[ihl+4 : ihl+8])
  687. c.Sent = time.Now()
  688. }
  689. func (f *Firewall) checkTCPRTT(c *conn, p []byte) bool {
  690. if c.Seq == 0 {
  691. return false
  692. }
  693. ihl := int(p[0]&0x0f) << 2
  694. if p[ihl+13]&tcpACK == 0 {
  695. return false
  696. }
  697. // Deal with wrap around, signed int cuts the ack window in half
  698. // 0 is a bad ack, no data acknowledged
  699. // positive number is a bad ack, ack is over half the window away
  700. if int32(c.Seq-binary.BigEndian.Uint32(p[ihl+8:ihl+12])) >= 0 {
  701. return false
  702. }
  703. f.metricTCPRTT.Update(time.Since(c.Sent).Nanoseconds())
  704. c.Seq = 0
  705. return true
  706. }