firewall.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. package nebula
  2. import (
  3. "crypto/sha256"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "hash/fnv"
  9. "net/netip"
  10. "reflect"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/gaissmai/bart"
  17. "github.com/rcrowley/go-metrics"
  18. "github.com/sirupsen/logrus"
  19. "github.com/slackhq/nebula/cert"
  20. "github.com/slackhq/nebula/config"
  21. "github.com/slackhq/nebula/firewall"
  22. )
  23. var ErrCannotSNAT = errors.New("cannot SNAT this packet")
  24. var ErrSNATIdentityMismatch = errors.New("refusing to SNAT for mismatched host")
  25. const ipv4SourcePosition = 12
  26. const ipv4DestinationPosition = 16
  27. const sourcePortOffset = 0
  28. const destinationPortOffset = 2
  29. type FirewallInterface interface {
  30. AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr string, caName string, caSha string) error
  31. }
  32. type snatInfo struct {
  33. //Src is the source IP+port to write into unsafe-route-bound packet
  34. Src netip.AddrPort
  35. //SrcVpnIp is the overlay IP associated with this flow. It's needed to associate reply traffic so we can get it back to the right host.
  36. SrcVpnIp netip.Addr
  37. //SnatPort is the port to rewrite into an overlay-bound packet
  38. SnatPort uint16
  39. }
  40. func (s *snatInfo) Valid() bool {
  41. if s == nil {
  42. return false
  43. }
  44. return s.Src.IsValid()
  45. }
  46. type conn struct {
  47. Expires time.Time // Time when this conntrack entry will expire
  48. // record why the original connection passed the firewall, so we can re-validate
  49. // after ruleset changes. Note, rulesVersion is a uint16 so that these two
  50. // fields pack for free after the uint32 above
  51. incoming bool
  52. rulesVersion uint16
  53. //for SNAT support
  54. snat *snatInfo
  55. }
  56. // TODO: need conntrack max tracked connections handling
  57. type Firewall struct {
  58. Conntrack *FirewallConntrack
  59. InRules *FirewallTable
  60. OutRules *FirewallTable
  61. InSendReject bool
  62. OutSendReject bool
  63. //TODO: we should have many more options for TCP, an option for ICMP, and mimic the kernel a bit better
  64. // https://www.kernel.org/doc/Documentation/networking/nf_conntrack-sysctl.txt
  65. TCPTimeout time.Duration //linux: 5 days max
  66. UDPTimeout time.Duration //linux: 180s max
  67. DefaultTimeout time.Duration //linux: 600s
  68. // routableNetworks describes the vpn addresses as well as any unsafe networks issued to us in the certificate.
  69. // The vpn addresses are a full bit match while the unsafe networks only match the prefix
  70. routableNetworks *bart.Lite
  71. // assignedNetworks is a list of vpn networks assigned to us in the certificate.
  72. assignedNetworks []netip.Prefix
  73. hasUnsafeNetworks bool
  74. rules string
  75. rulesVersion uint16
  76. defaultLocalCIDRAny bool
  77. incomingMetrics firewallMetrics
  78. outgoingMetrics firewallMetrics
  79. unsafeIPv4Origin netip.Addr
  80. snatAddr netip.Addr
  81. l *logrus.Logger
  82. }
  83. type firewallMetrics struct {
  84. droppedLocalAddr metrics.Counter
  85. droppedRemoteAddr metrics.Counter
  86. droppedNoRule metrics.Counter
  87. }
  88. type FirewallConntrack struct {
  89. sync.Mutex
  90. Conns map[firewall.Packet]*conn
  91. TimerWheel *TimerWheel[firewall.Packet]
  92. }
  93. // FirewallTable is the entry point for a rule, the evaluation order is:
  94. // Proto AND port AND (CA SHA or CA name) AND local CIDR AND (group OR groups OR name OR remote CIDR)
  95. type FirewallTable struct {
  96. TCP firewallPort
  97. UDP firewallPort
  98. ICMP firewallPort
  99. AnyProto firewallPort
  100. }
  101. func newFirewallTable() *FirewallTable {
  102. return &FirewallTable{
  103. TCP: firewallPort{},
  104. UDP: firewallPort{},
  105. ICMP: firewallPort{},
  106. AnyProto: firewallPort{},
  107. }
  108. }
  109. type FirewallCA struct {
  110. Any *FirewallRule
  111. CANames map[string]*FirewallRule
  112. CAShas map[string]*FirewallRule
  113. }
  114. type FirewallRule struct {
  115. // Any makes Hosts, Groups, and CIDR irrelevant
  116. Any *firewallLocalCIDR
  117. Hosts map[string]*firewallLocalCIDR
  118. Groups []*firewallGroups
  119. CIDR *bart.Table[*firewallLocalCIDR]
  120. }
  121. type firewallGroups struct {
  122. Groups []string
  123. LocalCIDR *firewallLocalCIDR
  124. }
  125. // Even though ports are uint16, int32 maps are faster for lookup
  126. // Plus we can use `-1` for fragment rules
  127. type firewallPort map[int32]*FirewallCA
  128. type firewallLocalCIDR struct {
  129. Any bool
  130. LocalCIDR *bart.Lite
  131. }
  132. // NewFirewall creates a new Firewall object. A TimerWheel is created for you from the provided timeouts.
  133. // The certificate provided should be the highest version loaded in memory.
  134. func NewFirewall(l *logrus.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c cert.Certificate) *Firewall {
  135. //TODO: error on 0 duration
  136. var tmin, tmax time.Duration
  137. if tcpTimeout < UDPTimeout {
  138. tmin = tcpTimeout
  139. tmax = UDPTimeout
  140. } else {
  141. tmin = UDPTimeout
  142. tmax = tcpTimeout
  143. }
  144. if defaultTimeout < tmin {
  145. tmin = defaultTimeout
  146. } else if defaultTimeout > tmax {
  147. tmax = defaultTimeout
  148. }
  149. routableNetworks := new(bart.Lite)
  150. var assignedNetworks []netip.Prefix
  151. for _, network := range c.Networks() {
  152. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  153. routableNetworks.Insert(nprefix)
  154. assignedNetworks = append(assignedNetworks, network)
  155. }
  156. hasUnsafeNetworks := false
  157. for _, n := range c.UnsafeNetworks() {
  158. routableNetworks.Insert(n)
  159. hasUnsafeNetworks = true
  160. }
  161. return &Firewall{
  162. Conntrack: &FirewallConntrack{
  163. Conns: make(map[firewall.Packet]*conn),
  164. TimerWheel: NewTimerWheel[firewall.Packet](tmin, tmax),
  165. },
  166. InRules: newFirewallTable(),
  167. OutRules: newFirewallTable(),
  168. TCPTimeout: tcpTimeout,
  169. UDPTimeout: UDPTimeout,
  170. DefaultTimeout: defaultTimeout,
  171. routableNetworks: routableNetworks,
  172. assignedNetworks: assignedNetworks,
  173. hasUnsafeNetworks: hasUnsafeNetworks,
  174. l: l,
  175. incomingMetrics: firewallMetrics{
  176. droppedLocalAddr: metrics.GetOrRegisterCounter("firewall.incoming.dropped.local_addr", nil),
  177. droppedRemoteAddr: metrics.GetOrRegisterCounter("firewall.incoming.dropped.remote_addr", nil),
  178. droppedNoRule: metrics.GetOrRegisterCounter("firewall.incoming.dropped.no_rule", nil),
  179. },
  180. outgoingMetrics: firewallMetrics{
  181. droppedLocalAddr: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.local_addr", nil),
  182. droppedRemoteAddr: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.remote_addr", nil),
  183. droppedNoRule: metrics.GetOrRegisterCounter("firewall.outgoing.dropped.no_rule", nil),
  184. },
  185. }
  186. }
  187. func NewFirewallFromConfig(l *logrus.Logger, cs *CertState, c *config.C) (*Firewall, error) {
  188. certificate := cs.getCertificate(cert.Version2)
  189. if certificate == nil {
  190. certificate = cs.getCertificate(cert.Version1)
  191. }
  192. if certificate == nil {
  193. panic("No certificate available to reconfigure the firewall")
  194. }
  195. fw := NewFirewall(
  196. l,
  197. c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12),
  198. c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3),
  199. c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10),
  200. certificate,
  201. )
  202. fw.defaultLocalCIDRAny = c.GetBool("firewall.default_local_cidr_any", false)
  203. inboundAction := c.GetString("firewall.inbound_action", "drop")
  204. switch inboundAction {
  205. case "reject":
  206. fw.InSendReject = true
  207. case "drop":
  208. fw.InSendReject = false
  209. default:
  210. l.WithField("action", inboundAction).Warn("invalid firewall.inbound_action, defaulting to `drop`")
  211. fw.InSendReject = false
  212. }
  213. outboundAction := c.GetString("firewall.outbound_action", "drop")
  214. switch outboundAction {
  215. case "reject":
  216. fw.OutSendReject = true
  217. case "drop":
  218. fw.OutSendReject = false
  219. default:
  220. l.WithField("action", inboundAction).Warn("invalid firewall.outbound_action, defaulting to `drop`")
  221. fw.OutSendReject = false
  222. }
  223. err := AddFirewallRulesFromConfig(l, false, c, fw)
  224. if err != nil {
  225. return nil, err
  226. }
  227. err = AddFirewallRulesFromConfig(l, true, c, fw)
  228. if err != nil {
  229. return nil, err
  230. }
  231. return fw, nil
  232. }
  233. // AddRule properly creates the in memory rule structure for a firewall table.
  234. func (f *Firewall) AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
  235. var (
  236. ft *FirewallTable
  237. fp firewallPort
  238. )
  239. if incoming {
  240. ft = f.InRules
  241. } else {
  242. ft = f.OutRules
  243. }
  244. switch proto {
  245. case firewall.ProtoTCP:
  246. fp = ft.TCP
  247. case firewall.ProtoUDP:
  248. fp = ft.UDP
  249. case firewall.ProtoICMP, firewall.ProtoICMPv6:
  250. //ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
  251. if startPort != firewall.PortAny {
  252. f.l.WithField("startPort", startPort).Warn("ignoring port specification for ICMP firewall rule")
  253. }
  254. startPort = firewall.PortAny
  255. endPort = firewall.PortAny
  256. fp = ft.ICMP
  257. case firewall.ProtoAny:
  258. fp = ft.AnyProto
  259. default:
  260. return fmt.Errorf("unknown protocol %v", proto)
  261. }
  262. // We need this rule string because we generate a hash. Removing this will break firewall reload.
  263. ruleString := fmt.Sprintf(
  264. "incoming: %v, proto: %v, startPort: %v, endPort: %v, groups: %v, host: %v, ip: %v, localIp: %v, caName: %v, caSha: %s",
  265. incoming, proto, startPort, endPort, groups, host, cidr, localCidr, caName, caSha,
  266. )
  267. f.rules += ruleString + "\n"
  268. direction := "incoming"
  269. if !incoming {
  270. direction = "outgoing"
  271. }
  272. f.l.WithField("firewallRule", m{"direction": direction, "proto": proto, "startPort": startPort, "endPort": endPort, "groups": groups, "host": host, "cidr": cidr, "localCidr": localCidr, "caName": caName, "caSha": caSha}).
  273. Info("Firewall rule added")
  274. return fp.addRule(f, startPort, endPort, groups, host, cidr, localCidr, caName, caSha)
  275. }
  276. // GetRuleHash returns a hash representation of all inbound and outbound rules
  277. func (f *Firewall) GetRuleHash() string {
  278. sum := sha256.Sum256([]byte(f.rules))
  279. return hex.EncodeToString(sum[:])
  280. }
  281. // GetRuleHashFNV returns a uint32 FNV-1 hash representation the rules, for use as a metric value
  282. func (f *Firewall) GetRuleHashFNV() uint32 {
  283. h := fnv.New32a()
  284. h.Write([]byte(f.rules))
  285. return h.Sum32()
  286. }
  287. // GetRuleHashes returns both the sha256 and FNV-1 hashes, suitable for logging
  288. func (f *Firewall) GetRuleHashes() string {
  289. return "SHA:" + f.GetRuleHash() + ",FNV:" + strconv.FormatUint(uint64(f.GetRuleHashFNV()), 10)
  290. }
  291. func (f *Firewall) SetSNATAddressFromInterface(i *Interface) {
  292. //address-mutation-avoidance is done inside Interface, the firewall doesn't need to care
  293. //todo should snatted conntracks get expired out? Probably not needed until if/when we allow reload
  294. f.snatAddr = i.inside.SNATAddress().Addr()
  295. f.unsafeIPv4Origin = i.inside.UnsafeIPv4OriginAddress().Addr()
  296. }
  297. func (f *Firewall) ShouldUnSNAT(fp *firewall.Packet) bool {
  298. // f.snatAddr is only valid if we're a snat-capable router
  299. return f.snatAddr.IsValid() && fp.RemoteAddr == f.snatAddr
  300. }
  301. func AddFirewallRulesFromConfig(l *logrus.Logger, inbound bool, c *config.C, fw FirewallInterface) error {
  302. var table string
  303. if inbound {
  304. table = "firewall.inbound"
  305. } else {
  306. table = "firewall.outbound"
  307. }
  308. r := c.Get(table)
  309. if r == nil {
  310. return nil
  311. }
  312. rs, ok := r.([]any)
  313. if !ok {
  314. return fmt.Errorf("%s failed to parse, should be an array of rules", table)
  315. }
  316. for i, t := range rs {
  317. r, err := convertRule(l, t, table, i)
  318. if err != nil {
  319. return fmt.Errorf("%s rule #%v; %s", table, i, err)
  320. }
  321. if r.Code != "" && r.Port != "" {
  322. return fmt.Errorf("%s rule #%v; only one of port or code should be provided", table, i)
  323. }
  324. if r.Host == "" && len(r.Groups) == 0 && r.Cidr == "" && r.LocalCidr == "" && r.CAName == "" && r.CASha == "" {
  325. return fmt.Errorf("%s rule #%v; at least one of host, group, cidr, local_cidr, ca_name, or ca_sha must be provided", table, i)
  326. }
  327. var sPort, errPort string
  328. if r.Code != "" {
  329. errPort = "code"
  330. sPort = r.Code
  331. } else {
  332. errPort = "port"
  333. sPort = r.Port
  334. }
  335. var proto uint8
  336. var startPort, endPort int32
  337. switch r.Proto {
  338. case "any":
  339. proto = firewall.ProtoAny
  340. startPort, endPort, err = parsePort(sPort)
  341. case "tcp":
  342. proto = firewall.ProtoTCP
  343. startPort, endPort, err = parsePort(sPort)
  344. case "udp":
  345. proto = firewall.ProtoUDP
  346. startPort, endPort, err = parsePort(sPort)
  347. case "icmp":
  348. proto = firewall.ProtoICMP
  349. startPort = firewall.PortAny
  350. endPort = firewall.PortAny
  351. if sPort != "" {
  352. l.WithField("port", sPort).Warn("ignoring port specification for ICMP firewall rule")
  353. }
  354. default:
  355. return fmt.Errorf("%s rule #%v; proto was not understood; `%s`", table, i, r.Proto)
  356. }
  357. if err != nil {
  358. return fmt.Errorf("%s rule #%v; %s %s", table, i, errPort, err)
  359. }
  360. if r.Cidr != "" && r.Cidr != "any" {
  361. _, err = netip.ParsePrefix(r.Cidr)
  362. if err != nil {
  363. return fmt.Errorf("%s rule #%v; cidr did not parse; %s", table, i, err)
  364. }
  365. }
  366. if r.LocalCidr != "" && r.LocalCidr != "any" {
  367. _, err = netip.ParsePrefix(r.LocalCidr)
  368. if err != nil {
  369. return fmt.Errorf("%s rule #%v; local_cidr did not parse; %s", table, i, err)
  370. }
  371. }
  372. if warning := r.sanity(); warning != nil {
  373. l.Warnf("%s rule #%v; %s", table, i, warning)
  374. }
  375. err = fw.AddRule(inbound, proto, startPort, endPort, r.Groups, r.Host, r.Cidr, r.LocalCidr, r.CAName, r.CASha)
  376. if err != nil {
  377. return fmt.Errorf("%s rule #%v; `%s`", table, i, err)
  378. }
  379. }
  380. return nil
  381. }
  382. var ErrUnknownNetworkType = errors.New("unknown network type")
  383. var ErrPeerRejected = errors.New("remote address is not within a network that we handle")
  384. var ErrInvalidRemoteIP = errors.New("remote address is not in remote certificate networks")
  385. var ErrInvalidLocalIP = errors.New("local address is not in list of handled local addresses")
  386. var ErrNoMatchingRule = errors.New("no matching rule in firewall table")
  387. func (f *Firewall) unSnat(data []byte, fp *firewall.Packet) netip.Addr {
  388. c := f.peek(*fp) //unfortunately this needs to lock. Surely there's a better way.
  389. if c == nil {
  390. return netip.Addr{}
  391. }
  392. if !c.snat.Valid() {
  393. return netip.Addr{}
  394. }
  395. oldIP := netip.AddrPortFrom(f.snatAddr, fp.RemotePort)
  396. rewritePacket(data, fp, oldIP, c.snat.Src, ipv4DestinationPosition, destinationPortOffset)
  397. return c.snat.SrcVpnIp
  398. }
  399. func rewritePacket(data []byte, fp *firewall.Packet, oldIP netip.AddrPort, newIP netip.AddrPort, ipOffset int, portOffset int) {
  400. //change address
  401. copy(data[ipOffset:], newIP.Addr().AsSlice())
  402. recalcIPv4Checksum(data, oldIP.Addr(), newIP.Addr())
  403. ipHeaderLen := int(data[0]&0x0F) * 4
  404. switch fp.Protocol {
  405. case firewall.ProtoICMP:
  406. binary.BigEndian.PutUint16(data[ipHeaderLen+4:ipHeaderLen+6], newIP.Port()) //we use the ID field as a "port" for ICMP
  407. icmpCode := uint16(data[ipHeaderLen+1]) //todo not snatting on code yet (but Linux would)
  408. recalcICMPv4Checksum(data, icmpCode, icmpCode, oldIP.Port(), newIP.Port())
  409. case firewall.ProtoUDP:
  410. dstport := ipHeaderLen + portOffset
  411. binary.BigEndian.PutUint16(data[dstport:dstport+2], newIP.Port())
  412. recalcUDPv4Checksum(data, oldIP, newIP)
  413. case firewall.ProtoTCP:
  414. dstport := ipHeaderLen + portOffset
  415. binary.BigEndian.PutUint16(data[dstport:dstport+2], newIP.Port())
  416. recalcTCPv4Checksum(data, oldIP, newIP)
  417. }
  418. }
  419. func (f *Firewall) findUsableSNATPort(fp *firewall.Packet, c *conn) error {
  420. const halfThePorts = 0x7fff
  421. oldPort := fp.RemotePort
  422. conntrack := f.Conntrack
  423. conntrack.Lock()
  424. defer conntrack.Unlock()
  425. for numPortsChecked := 0; numPortsChecked < halfThePorts; numPortsChecked++ {
  426. _, ok := conntrack.Conns[*fp]
  427. if !ok {
  428. //yay, we can use this port
  429. //track the snatted flow with the same expiration as the unsnatted version
  430. c.snat.SnatPort = fp.RemotePort
  431. conntrack.Conns[*fp] = c
  432. return nil
  433. }
  434. //increment and retry. There's probably better strategies out there
  435. fp.RemotePort++
  436. if fp.RemotePort < halfThePorts {
  437. fp.RemotePort += halfThePorts // keep it ephemeral for now
  438. }
  439. }
  440. //if we made it here, we failed
  441. fp.RemotePort = oldPort
  442. return ErrCannotSNAT
  443. }
  444. func (f *Firewall) applySnat(data []byte, fp *firewall.Packet, c *conn, hostinfo *HostInfo) error {
  445. if !f.snatAddr.IsValid() {
  446. return ErrCannotSNAT
  447. }
  448. if f.snatAddr == fp.LocalAddr { //a packet that came from UDP (incoming) should never ever have our snat address on it
  449. return ErrSNATIdentityMismatch
  450. }
  451. if c.snat.Valid() {
  452. //old flow: make sure it came from the right place
  453. if !slices.Contains(hostinfo.vpnAddrs, c.snat.SrcVpnIp) {
  454. return ErrSNATIdentityMismatch
  455. }
  456. fp.RemoteAddr = f.snatAddr
  457. fp.RemotePort = c.snat.SnatPort
  458. } else if hostinfo.vpnAddrs[0].Is6() {
  459. //we got a new flow
  460. c.snat = &snatInfo{
  461. Src: netip.AddrPortFrom(fp.RemoteAddr, fp.RemotePort),
  462. SrcVpnIp: hostinfo.vpnAddrs[0],
  463. }
  464. fp.RemoteAddr = f.snatAddr
  465. //find a new port to use, if needed
  466. err := f.findUsableSNATPort(fp, c)
  467. if err != nil {
  468. c.snat = nil
  469. return err
  470. }
  471. } else {
  472. return ErrCannotSNAT
  473. }
  474. newIP := netip.AddrPortFrom(f.snatAddr, c.snat.SnatPort)
  475. rewritePacket(data, fp, c.snat.Src, newIP, ipv4SourcePosition, sourcePortOffset)
  476. return nil
  477. }
  478. func (f *Firewall) identifyRemoteNetworkType(h *HostInfo, fp firewall.Packet) NetworkType {
  479. if h.networks == nil {
  480. // Simple case: Certificate has one address and no unsafe networks
  481. if h.vpnAddrs[0] == fp.RemoteAddr {
  482. return NetworkTypeVPN
  483. } //else, fallthrough
  484. } else if nwType, ok := h.networks.Lookup(fp.RemoteAddr); ok {
  485. return nwType //will return NetworkTypeVPN or NetworkTypeUnsafe
  486. }
  487. //RemoteAddr not in our networks table
  488. if f.snatAddr.IsValid() && fp.IsIPv4() && h.HasOnlyV6Addresses() {
  489. return NetworkTypeUncheckedSNATPeer
  490. } else {
  491. return NetworkTypeInvalidPeer
  492. }
  493. }
  494. func (f *Firewall) allowRemoteNetworkType(nwType NetworkType, fp firewall.Packet) error {
  495. switch nwType {
  496. case NetworkTypeVPN:
  497. return nil
  498. case NetworkTypeInvalidPeer:
  499. return ErrInvalidRemoteIP
  500. case NetworkTypeVPNPeer:
  501. //one day we might need a specialSnatMode case in here to handle routers with v4 addresses when we don't also have a v4 address?
  502. return ErrPeerRejected // reject for now, one day this may have different FW rules
  503. case NetworkTypeUnsafe:
  504. return nil // nothing special, one day this may have different FW rules
  505. case NetworkTypeUncheckedSNATPeer:
  506. if f.unsafeIPv4Origin.IsValid() && fp.LocalAddr == f.unsafeIPv4Origin {
  507. return nil //the client case
  508. }
  509. if f.snatAddr.IsValid() {
  510. if fp.RemoteAddr == f.snatAddr {
  511. return ErrInvalidRemoteIP //we should never get a packet with our SNAT addr as the destination, or "from" our SNAT addr
  512. }
  513. return nil
  514. } else {
  515. return ErrInvalidRemoteIP
  516. }
  517. default:
  518. return ErrUnknownNetworkType //should never happen
  519. }
  520. }
  521. func (f *Firewall) willingToHandleLocalAddr(incoming bool, fp firewall.Packet, remoteNwType NetworkType) error {
  522. if f.routableNetworks.Contains(fp.LocalAddr) {
  523. return nil //easy, this should handle NetworkTypeVPN in all cases, and NetworkTypeUnsafe on the router side
  524. }
  525. if incoming { //at least for now, reject all traffic other than what we've already decided is locally routable
  526. return ErrInvalidLocalIP
  527. }
  528. //below this line, all traffic is outgoing. Outgoing traffic to NetworkTypeUnsafe is not required to be considered inbound-routable
  529. if remoteNwType == NetworkTypeUnsafe {
  530. return nil
  531. }
  532. return ErrInvalidLocalIP
  533. }
  534. // Drop returns an error if the packet should be dropped, explaining why. It
  535. // returns nil if the packet should not be dropped.
  536. func (f *Firewall) Drop(fp firewall.Packet, pkt []byte, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) error {
  537. table := f.OutRules
  538. if incoming {
  539. table = f.InRules
  540. }
  541. snatmode := fp.IsIPv4() && h.HasOnlyV6Addresses() && f.snatAddr.IsValid()
  542. if snatmode {
  543. //if this is an IPv4 packet from a V6 only host, and we're configured to snat that kind of traffic, it must be snatted,
  544. //so it can never be in the localcache, which lacks SNAT data
  545. //nil out the pointer to avoid ever using it
  546. localCache = nil
  547. }
  548. // Check if we spoke to this tuple, if we did then allow this packet
  549. if localCache != nil {
  550. if _, ok := localCache[fp]; ok {
  551. return nil //packet matched the cache, we're not snatting, we can return early
  552. }
  553. }
  554. c := f.inConns(fp, h, caPool, localCache)
  555. if c != nil {
  556. if incoming && snatmode {
  557. return f.applySnat(pkt, &fp, c, h)
  558. }
  559. return nil
  560. }
  561. // Make sure remote address matches nebula certificate, and determine how to treat it
  562. remoteNetworkType := f.identifyRemoteNetworkType(h, fp)
  563. if err := f.allowRemoteNetworkType(remoteNetworkType, fp); err != nil {
  564. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  565. return err
  566. }
  567. // Make sure we are supposed to be handling this local ip address
  568. if err := f.willingToHandleLocalAddr(incoming, fp, remoteNetworkType); err != nil {
  569. f.metrics(incoming).droppedLocalAddr.Inc(1)
  570. return err
  571. }
  572. // We now know which firewall table to check against
  573. if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
  574. f.metrics(incoming).droppedNoRule.Inc(1)
  575. return ErrNoMatchingRule
  576. }
  577. // We always want to conntrack since it is a faster operation
  578. c = f.addConn(fp, incoming)
  579. if incoming && remoteNetworkType == NetworkTypeUncheckedSNATPeer {
  580. return f.applySnat(pkt, &fp, c, h)
  581. } else {
  582. //outgoing snat is handled before this function is called
  583. return nil
  584. }
  585. }
  586. func (f *Firewall) metrics(incoming bool) firewallMetrics {
  587. if incoming {
  588. return f.incomingMetrics
  589. } else {
  590. return f.outgoingMetrics
  591. }
  592. }
  593. // Destroy cleans up any known cyclical references so the object can be freed by GC. This should be called if a new
  594. // firewall object is created
  595. func (f *Firewall) Destroy() {
  596. //TODO: clean references if/when needed
  597. }
  598. func (f *Firewall) EmitStats() {
  599. conntrack := f.Conntrack
  600. conntrack.Lock()
  601. conntrackCount := len(conntrack.Conns)
  602. conntrack.Unlock()
  603. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  604. metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
  605. metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
  606. }
  607. func (f *Firewall) peek(fp firewall.Packet) *conn {
  608. f.Conntrack.Lock()
  609. c := f.Conntrack.Conns[fp]
  610. f.Conntrack.Unlock()
  611. return c
  612. }
  613. func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) *conn {
  614. conntrack := f.Conntrack
  615. conntrack.Lock()
  616. // Purge every time we test
  617. ep, has := conntrack.TimerWheel.Purge()
  618. if has {
  619. f.evict(ep)
  620. }
  621. c, ok := conntrack.Conns[fp]
  622. if !ok {
  623. conntrack.Unlock()
  624. return nil
  625. }
  626. if c.rulesVersion != f.rulesVersion {
  627. // This conntrack entry was for an older rule set, validate
  628. // it still passes with the current rule set
  629. table := f.OutRules
  630. if c.incoming {
  631. table = f.InRules
  632. }
  633. // We now know which firewall table to check against
  634. if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
  635. if f.l.Level >= logrus.DebugLevel {
  636. h.logger(f.l).
  637. WithField("fwPacket", fp).
  638. WithField("incoming", c.incoming).
  639. WithField("rulesVersion", f.rulesVersion).
  640. WithField("oldRulesVersion", c.rulesVersion).
  641. Debugln("dropping old conntrack entry, does not match new ruleset")
  642. }
  643. delete(conntrack.Conns, fp)
  644. conntrack.Unlock()
  645. return nil
  646. }
  647. if f.l.Level >= logrus.DebugLevel {
  648. h.logger(f.l).
  649. WithField("fwPacket", fp).
  650. WithField("incoming", c.incoming).
  651. WithField("rulesVersion", f.rulesVersion).
  652. WithField("oldRulesVersion", c.rulesVersion).
  653. Debugln("keeping old conntrack entry, does match new ruleset")
  654. }
  655. c.rulesVersion = f.rulesVersion
  656. }
  657. switch fp.Protocol {
  658. case firewall.ProtoTCP:
  659. c.Expires = time.Now().Add(f.TCPTimeout)
  660. case firewall.ProtoUDP:
  661. c.Expires = time.Now().Add(f.UDPTimeout)
  662. default:
  663. c.Expires = time.Now().Add(f.DefaultTimeout)
  664. }
  665. conntrack.Unlock()
  666. if localCache != nil {
  667. localCache[fp] = struct{}{}
  668. }
  669. return c
  670. }
  671. func (f *Firewall) packetTimeout(fp firewall.Packet) time.Duration {
  672. var timeout time.Duration
  673. switch fp.Protocol {
  674. case firewall.ProtoTCP:
  675. timeout = f.TCPTimeout
  676. case firewall.ProtoUDP:
  677. timeout = f.UDPTimeout
  678. default:
  679. timeout = f.DefaultTimeout
  680. }
  681. return timeout
  682. }
  683. func (f *Firewall) addConn(fp firewall.Packet, incoming bool) *conn {
  684. c := &conn{}
  685. timeout := f.packetTimeout(fp)
  686. conntrack := f.Conntrack
  687. conntrack.Lock()
  688. if _, ok := conntrack.Conns[fp]; !ok {
  689. conntrack.TimerWheel.Advance(time.Now())
  690. conntrack.TimerWheel.Add(fp, timeout)
  691. }
  692. // Record which rulesVersion allowed this connection, so we can retest after
  693. // firewall reload
  694. c.incoming = incoming
  695. c.rulesVersion = f.rulesVersion
  696. c.Expires = time.Now().Add(timeout)
  697. conntrack.Conns[fp] = c
  698. conntrack.Unlock()
  699. return c
  700. }
  701. // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
  702. // Caller must own the connMutex lock!
  703. func (f *Firewall) evict(p firewall.Packet) {
  704. // Are we still tracking this conn?
  705. conntrack := f.Conntrack
  706. t, ok := conntrack.Conns[p]
  707. if !ok {
  708. return
  709. }
  710. newT := t.Expires.Sub(time.Now())
  711. // Timeout is in the future, re-add the timer
  712. if newT > 0 {
  713. conntrack.TimerWheel.Advance(time.Now())
  714. conntrack.TimerWheel.Add(p, newT)
  715. return
  716. }
  717. // This conn is done
  718. delete(conntrack.Conns, p)
  719. }
  720. func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  721. if ft.AnyProto.match(p, incoming, c, caPool) {
  722. return true
  723. }
  724. switch p.Protocol {
  725. case firewall.ProtoTCP:
  726. if ft.TCP.match(p, incoming, c, caPool) {
  727. return true
  728. }
  729. case firewall.ProtoUDP:
  730. if ft.UDP.match(p, incoming, c, caPool) {
  731. return true
  732. }
  733. case firewall.ProtoICMP, firewall.ProtoICMPv6:
  734. if ft.ICMP.match(p, incoming, c, caPool) {
  735. return true
  736. }
  737. }
  738. return false
  739. }
  740. func (fp firewallPort) addRule(f *Firewall, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
  741. if startPort > endPort {
  742. return fmt.Errorf("start port was lower than end port")
  743. }
  744. for i := startPort; i <= endPort; i++ {
  745. if _, ok := fp[i]; !ok {
  746. fp[i] = &FirewallCA{
  747. CANames: make(map[string]*FirewallRule),
  748. CAShas: make(map[string]*FirewallRule),
  749. }
  750. }
  751. if err := fp[i].addRule(f, groups, host, cidr, localCidr, caName, caSha); err != nil {
  752. return err
  753. }
  754. }
  755. return nil
  756. }
  757. func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  758. // We don't have any allowed ports, bail
  759. if fp == nil {
  760. return false
  761. }
  762. // this branch is here to catch traffic from FirewallTable.Any.match and FirewallTable.ICMP.match
  763. if p.Protocol == firewall.ProtoICMP || p.Protocol == firewall.ProtoICMPv6 {
  764. // port numbers are re-used for connection tracking of ICMP,
  765. // but we don't want to actually filter on them.
  766. return fp[firewall.PortAny].match(p, c, caPool)
  767. }
  768. var port int32
  769. if p.Fragment {
  770. port = firewall.PortFragment
  771. } else if incoming {
  772. port = int32(p.LocalPort)
  773. } else {
  774. port = int32(p.RemotePort)
  775. }
  776. if fp[port].match(p, c, caPool) {
  777. return true
  778. }
  779. return fp[firewall.PortAny].match(p, c, caPool)
  780. }
  781. func (fc *FirewallCA) addRule(f *Firewall, groups []string, host string, cidr, localCidr, caName, caSha string) error {
  782. fr := func() *FirewallRule {
  783. return &FirewallRule{
  784. Hosts: make(map[string]*firewallLocalCIDR),
  785. Groups: make([]*firewallGroups, 0),
  786. CIDR: new(bart.Table[*firewallLocalCIDR]),
  787. }
  788. }
  789. if caSha == "" && caName == "" {
  790. if fc.Any == nil {
  791. fc.Any = fr()
  792. }
  793. return fc.Any.addRule(f, groups, host, cidr, localCidr)
  794. }
  795. if caSha != "" {
  796. if _, ok := fc.CAShas[caSha]; !ok {
  797. fc.CAShas[caSha] = fr()
  798. }
  799. err := fc.CAShas[caSha].addRule(f, groups, host, cidr, localCidr)
  800. if err != nil {
  801. return err
  802. }
  803. }
  804. if caName != "" {
  805. if _, ok := fc.CANames[caName]; !ok {
  806. fc.CANames[caName] = fr()
  807. }
  808. err := fc.CANames[caName].addRule(f, groups, host, cidr, localCidr)
  809. if err != nil {
  810. return err
  811. }
  812. }
  813. return nil
  814. }
  815. func (fc *FirewallCA) match(p firewall.Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  816. if fc == nil {
  817. return false
  818. }
  819. if fc.Any.match(p, c) {
  820. return true
  821. }
  822. if t, ok := fc.CAShas[c.Certificate.Issuer()]; ok {
  823. if t.match(p, c) {
  824. return true
  825. }
  826. }
  827. s, err := caPool.GetCAForCert(c.Certificate)
  828. if err != nil {
  829. return false
  830. }
  831. return fc.CANames[s.Certificate.Name()].match(p, c)
  832. }
  833. func (fr *FirewallRule) addRule(f *Firewall, groups []string, host, cidr, localCidr string) error {
  834. flc := func() *firewallLocalCIDR {
  835. return &firewallLocalCIDR{
  836. LocalCIDR: new(bart.Lite),
  837. }
  838. }
  839. if fr.isAny(groups, host, cidr) {
  840. if fr.Any == nil {
  841. fr.Any = flc()
  842. }
  843. return fr.Any.addRule(f, localCidr)
  844. }
  845. if len(groups) > 0 {
  846. nlc := flc()
  847. err := nlc.addRule(f, localCidr)
  848. if err != nil {
  849. return err
  850. }
  851. fr.Groups = append(fr.Groups, &firewallGroups{
  852. Groups: groups,
  853. LocalCIDR: nlc,
  854. })
  855. }
  856. if host != "" {
  857. nlc := fr.Hosts[host]
  858. if nlc == nil {
  859. nlc = flc()
  860. }
  861. err := nlc.addRule(f, localCidr)
  862. if err != nil {
  863. return err
  864. }
  865. fr.Hosts[host] = nlc
  866. }
  867. if cidr != "" {
  868. c, err := netip.ParsePrefix(cidr)
  869. if err != nil {
  870. return err
  871. }
  872. nlc, _ := fr.CIDR.Get(c)
  873. if nlc == nil {
  874. nlc = flc()
  875. }
  876. err = nlc.addRule(f, localCidr)
  877. if err != nil {
  878. return err
  879. }
  880. fr.CIDR.Insert(c, nlc)
  881. }
  882. return nil
  883. }
  884. func (fr *FirewallRule) isAny(groups []string, host string, cidr string) bool {
  885. if len(groups) == 0 && host == "" && cidr == "" {
  886. return true
  887. }
  888. if slices.Contains(groups, "any") {
  889. return true
  890. }
  891. if host == "any" {
  892. return true
  893. }
  894. if cidr == "any" {
  895. return true
  896. }
  897. return false
  898. }
  899. func (fr *FirewallRule) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  900. if fr == nil {
  901. return false
  902. }
  903. // Shortcut path for if groups, hosts, or cidr contained an `any`
  904. if fr.Any.match(p, c) {
  905. return true
  906. }
  907. // Need any of group, host, or cidr to match
  908. for _, sg := range fr.Groups {
  909. found := false
  910. for _, g := range sg.Groups {
  911. if _, ok := c.InvertedGroups[g]; !ok {
  912. found = false
  913. break
  914. }
  915. found = true
  916. }
  917. if found && sg.LocalCIDR.match(p, c) {
  918. return true
  919. }
  920. }
  921. if fr.Hosts != nil {
  922. if flc, ok := fr.Hosts[c.Certificate.Name()]; ok {
  923. if flc.match(p, c) {
  924. return true
  925. }
  926. }
  927. }
  928. for _, v := range fr.CIDR.Supernets(netip.PrefixFrom(p.RemoteAddr, p.RemoteAddr.BitLen())) {
  929. if v.match(p, c) {
  930. return true
  931. }
  932. }
  933. return false
  934. }
  935. func (flc *firewallLocalCIDR) addRule(f *Firewall, localCidr string) error {
  936. if localCidr == "any" {
  937. flc.Any = true
  938. return nil
  939. }
  940. if localCidr == "" {
  941. if !f.hasUnsafeNetworks || f.defaultLocalCIDRAny {
  942. flc.Any = true
  943. return nil
  944. }
  945. for _, network := range f.assignedNetworks {
  946. flc.LocalCIDR.Insert(network)
  947. }
  948. return nil
  949. }
  950. c, err := netip.ParsePrefix(localCidr)
  951. if err != nil {
  952. return err
  953. }
  954. flc.LocalCIDR.Insert(c)
  955. return nil
  956. }
  957. func (flc *firewallLocalCIDR) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  958. if flc == nil {
  959. return false
  960. }
  961. if flc.Any {
  962. return true
  963. }
  964. return flc.LocalCIDR.Contains(p.LocalAddr)
  965. }
  966. type rule struct {
  967. Port string
  968. Code string
  969. Proto string
  970. Host string
  971. Groups []string
  972. Cidr string
  973. LocalCidr string
  974. CAName string
  975. CASha string
  976. }
  977. func convertRule(l *logrus.Logger, p any, table string, i int) (rule, error) {
  978. r := rule{}
  979. m, ok := p.(map[string]any)
  980. if !ok {
  981. return r, errors.New("could not parse rule")
  982. }
  983. toString := func(k string, m map[string]any) string {
  984. v, ok := m[k]
  985. if !ok {
  986. return ""
  987. }
  988. return fmt.Sprintf("%v", v)
  989. }
  990. r.Port = toString("port", m)
  991. r.Code = toString("code", m)
  992. r.Proto = toString("proto", m)
  993. r.Host = toString("host", m)
  994. r.Cidr = toString("cidr", m)
  995. r.LocalCidr = toString("local_cidr", m)
  996. r.CAName = toString("ca_name", m)
  997. r.CASha = toString("ca_sha", m)
  998. // Make sure group isn't an array
  999. if v, ok := m["group"].([]any); ok {
  1000. if len(v) > 1 {
  1001. return r, errors.New("group should contain a single value, an array with more than one entry was provided")
  1002. }
  1003. l.Warnf("%s rule #%v; group was an array with a single value, converting to simple value", table, i)
  1004. m["group"] = v[0]
  1005. }
  1006. singleGroup := toString("group", m)
  1007. if rg, ok := m["groups"]; ok {
  1008. switch reflect.TypeOf(rg).Kind() {
  1009. case reflect.Slice:
  1010. v := reflect.ValueOf(rg)
  1011. r.Groups = make([]string, v.Len())
  1012. for i := 0; i < v.Len(); i++ {
  1013. r.Groups[i] = v.Index(i).Interface().(string)
  1014. }
  1015. case reflect.String:
  1016. r.Groups = []string{rg.(string)}
  1017. default:
  1018. r.Groups = []string{fmt.Sprintf("%v", rg)}
  1019. }
  1020. }
  1021. //flatten group vs groups
  1022. if singleGroup != "" {
  1023. // Check if we have both groups and group provided in the rule config
  1024. if len(r.Groups) > 0 {
  1025. return r, fmt.Errorf("only one of group or groups should be defined, both provided")
  1026. }
  1027. r.Groups = []string{singleGroup}
  1028. }
  1029. return r, nil
  1030. }
  1031. // sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
  1032. // rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
  1033. func (r *rule) sanity() error {
  1034. //port, proto, local_cidr are AND, no need to check here
  1035. //ca_sha and ca_name don't have a wildcard value, no need to check here
  1036. groupsEmpty := len(r.Groups) == 0
  1037. hostEmpty := r.Host == ""
  1038. cidrEmpty := r.Cidr == ""
  1039. if (groupsEmpty && hostEmpty && cidrEmpty) == true {
  1040. return nil //no content!
  1041. }
  1042. groupsHasAny := slices.Contains(r.Groups, "any")
  1043. if groupsHasAny && len(r.Groups) > 1 {
  1044. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the other groups specified", r.Groups)
  1045. }
  1046. if r.Host == "any" {
  1047. if !groupsEmpty {
  1048. return fmt.Errorf("groups specified as %s, but host=any will match any host, regardless of groups", r.Groups)
  1049. }
  1050. if !cidrEmpty {
  1051. return fmt.Errorf("cidr specified as %s, but host=any will match any host, regardless of cidr", r.Cidr)
  1052. }
  1053. }
  1054. if groupsHasAny {
  1055. if !hostEmpty && r.Host != "any" {
  1056. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified host %s", r.Groups, r.Host)
  1057. }
  1058. if !cidrEmpty {
  1059. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified cidr %s", r.Groups, r.Cidr)
  1060. }
  1061. }
  1062. if r.Code != "" {
  1063. return fmt.Errorf("code specified as [%s]. Support for 'code' will be dropped in a future release, as it has never been functional", r.Code)
  1064. }
  1065. //todo alert on cidr-any
  1066. return nil
  1067. }
  1068. func parsePort(s string) (int32, int32, error) {
  1069. var err error
  1070. const notAPort int32 = -2
  1071. if s == "any" {
  1072. return firewall.PortAny, firewall.PortAny, nil
  1073. }
  1074. if s == "fragment" {
  1075. return firewall.PortFragment, firewall.PortFragment, nil
  1076. }
  1077. if !strings.Contains(s, `-`) {
  1078. rPort, err := strconv.Atoi(s)
  1079. if err != nil {
  1080. return notAPort, notAPort, fmt.Errorf("was not a number; `%s`", s)
  1081. }
  1082. return int32(rPort), int32(rPort), nil
  1083. }
  1084. sPorts := strings.SplitN(s, `-`, 2)
  1085. for i := range sPorts {
  1086. sPorts[i] = strings.Trim(sPorts[i], " ")
  1087. }
  1088. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  1089. return notAPort, notAPort, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  1090. }
  1091. rStartPort, err := strconv.Atoi(sPorts[0])
  1092. if err != nil {
  1093. return notAPort, notAPort, fmt.Errorf("beginning range was not a number; `%s`", sPorts[0])
  1094. }
  1095. rEndPort, err := strconv.Atoi(sPorts[1])
  1096. if err != nil {
  1097. return notAPort, notAPort, fmt.Errorf("ending range was not a number; `%s`", sPorts[1])
  1098. }
  1099. startPort := int32(rStartPort)
  1100. endPort := int32(rEndPort)
  1101. if startPort == firewall.PortAny {
  1102. endPort = firewall.PortAny
  1103. }
  1104. return startPort, endPort, nil
  1105. }