firewall.go 35 KB

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