firewall.go 18 KB

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