firewall.go 35 KB

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