firewall.go 36 KB

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