firewall.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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. oldPort := fp.RemotePort
  425. conntrack := f.Conntrack
  426. conntrack.Lock()
  427. defer conntrack.Unlock()
  428. for numPortsChecked := 0; numPortsChecked < 0x7ff; numPortsChecked++ {
  429. _, ok := conntrack.Conns[*fp]
  430. if !ok {
  431. //yay, we can use this port
  432. //track the snatted flow with the same expiration as the unsnatted version
  433. conntrack.dupeConnUnlocked(*fp, c, f.packetTimeout(*fp))
  434. return nil
  435. }
  436. //increment and retry. There's probably better strategies out there
  437. fp.RemotePort++
  438. if fp.RemotePort < 0x7fff {
  439. fp.RemotePort += 0x7fff // keep it ephemeral for now
  440. }
  441. }
  442. //if we made it here, we failed
  443. fp.RemotePort = oldPort
  444. return ErrCannotSNAT
  445. }
  446. func (f *Firewall) applySnat(data []byte, fp *firewall.Packet, c *conn, hostinfo *HostInfo) error {
  447. if !f.snatAddr.IsValid() {
  448. return ErrCannotSNAT
  449. }
  450. if f.snatAddr == fp.LocalAddr { //a packet that came from UDP (incoming) should never ever have our snat address on it
  451. return ErrSNATIdentityMismatch
  452. }
  453. if c.snat.Valid() {
  454. //old flow: make sure it came from the right place
  455. if !slices.Contains(hostinfo.vpnAddrs, c.snat.SrcVpnIp) {
  456. return ErrSNATIdentityMismatch
  457. }
  458. fp.RemoteAddr = f.snatAddr
  459. fp.RemotePort = c.snat.SnatPort
  460. } else if hostinfo.vpnAddrs[0].Is6() {
  461. //we got a new flow
  462. c.snat = &snatInfo{
  463. Src: netip.AddrPortFrom(fp.RemoteAddr, fp.RemotePort),
  464. SrcVpnIp: hostinfo.vpnAddrs[0],
  465. }
  466. fp.RemoteAddr = f.snatAddr
  467. //find a new port to use, if needed
  468. err := f.findUsableSNATPort(fp, c)
  469. if err != nil {
  470. c.snat = nil
  471. return err
  472. }
  473. c.snat.SnatPort = fp.RemotePort //may have been updated inside f.findUsableSNATPort
  474. } else {
  475. return ErrCannotSNAT
  476. }
  477. newIP := netip.AddrPortFrom(f.snatAddr, c.snat.SnatPort)
  478. rewritePacket(data, fp, c.snat.Src, newIP, 12, 0)
  479. return nil
  480. }
  481. func (f *Firewall) identifyRemoteNetworkType(h *HostInfo, fp firewall.Packet) NetworkType {
  482. if h.networks == nil {
  483. // Simple case: Certificate has one address and no unsafe networks
  484. if h.vpnAddrs[0] == fp.RemoteAddr {
  485. return NetworkTypeVPN
  486. } //else, fallthrough
  487. } else if nwType, ok := h.networks.Lookup(fp.RemoteAddr); ok {
  488. return nwType //will return NetworkTypeVPN or NetworkTypeUnsafe
  489. }
  490. //RemoteAddr not in our networks table
  491. if f.snatAddr.IsValid() && fp.IsIPv4() && h.HasOnlyV6Addresses() {
  492. return NetworkTypeUncheckedSNATPeer
  493. } else {
  494. return NetworkTypeInvalidPeer
  495. }
  496. }
  497. func (f *Firewall) allowRemoteNetworkType(nwType NetworkType, fp firewall.Packet) error {
  498. switch nwType {
  499. case NetworkTypeVPN:
  500. return nil
  501. case NetworkTypeInvalidPeer:
  502. return ErrInvalidRemoteIP
  503. case NetworkTypeVPNPeer:
  504. //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?
  505. return ErrPeerRejected // reject for now, one day this may have different FW rules
  506. case NetworkTypeUnsafe:
  507. return nil // nothing special, one day this may have different FW rules
  508. case NetworkTypeUncheckedSNATPeer:
  509. if f.unsafeIPv4Origin.IsValid() && fp.LocalAddr == f.unsafeIPv4Origin {
  510. return nil //the client case
  511. }
  512. if f.snatAddr.IsValid() {
  513. if fp.RemoteAddr == f.snatAddr {
  514. return ErrInvalidRemoteIP //we should never get a packet with our SNAT addr as the destination, or "from" our SNAT addr
  515. }
  516. return nil
  517. } else {
  518. return ErrInvalidRemoteIP
  519. }
  520. default:
  521. return ErrUnknownNetworkType //should never happen
  522. }
  523. }
  524. func (f *Firewall) willingToHandleLocalAddr(incoming bool, fp firewall.Packet, remoteNwType NetworkType) error {
  525. if f.routableNetworks.Contains(fp.LocalAddr) {
  526. return nil //easy, this should handle NetworkTypeVPN in all cases, and NetworkTypeUnsafe on the router side
  527. }
  528. if incoming { //at least for now, reject all traffic other than what we've already decided is locally routable
  529. return ErrInvalidLocalIP
  530. }
  531. //below this line, all traffic is outgoing. Outgoing traffic to NetworkTypeUnsafe is not required to be considered inbound-routable
  532. if remoteNwType == NetworkTypeUnsafe {
  533. return nil
  534. }
  535. return ErrInvalidLocalIP
  536. }
  537. // Drop returns an error if the packet should be dropped, explaining why. It
  538. // returns nil if the packet should not be dropped.
  539. func (f *Firewall) Drop(fp firewall.Packet, pkt []byte, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) error {
  540. table := f.OutRules
  541. if incoming {
  542. table = f.InRules
  543. }
  544. snatmode := fp.IsIPv4() && h.HasOnlyV6Addresses() && f.snatAddr.IsValid()
  545. if snatmode {
  546. //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,
  547. //so it can never be in the localcache, which lacks SNAT data
  548. //nil out the pointer to avoid ever using it
  549. localCache = nil
  550. }
  551. // Check if we spoke to this tuple, if we did then allow this packet
  552. if localCache != nil {
  553. if _, ok := localCache[fp]; ok {
  554. return nil //packet matched the cache, we're not snatting, we can return early
  555. }
  556. }
  557. c := f.inConns(fp, h, caPool, localCache)
  558. if c != nil {
  559. if incoming && snatmode {
  560. return f.applySnat(pkt, &fp, c, h)
  561. }
  562. return nil
  563. }
  564. // Make sure remote address matches nebula certificate, and determine how to treat it
  565. remoteNetworkType := f.identifyRemoteNetworkType(h, fp)
  566. if err := f.allowRemoteNetworkType(remoteNetworkType, fp); err != nil {
  567. f.metrics(incoming).droppedRemoteAddr.Inc(1)
  568. return err
  569. }
  570. // Make sure we are supposed to be handling this local ip address
  571. if err := f.willingToHandleLocalAddr(incoming, fp, remoteNetworkType); err != nil {
  572. f.metrics(incoming).droppedLocalAddr.Inc(1)
  573. return err
  574. }
  575. // We now know which firewall table to check against
  576. if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
  577. f.metrics(incoming).droppedNoRule.Inc(1)
  578. return ErrNoMatchingRule
  579. }
  580. // We always want to conntrack since it is a faster operation
  581. c = f.addConn(fp, incoming)
  582. if incoming && remoteNetworkType == NetworkTypeUncheckedSNATPeer {
  583. return f.applySnat(pkt, &fp, c, h)
  584. } else {
  585. //outgoing snat is handled before this function is called
  586. return nil
  587. }
  588. }
  589. func (f *Firewall) metrics(incoming bool) firewallMetrics {
  590. if incoming {
  591. return f.incomingMetrics
  592. } else {
  593. return f.outgoingMetrics
  594. }
  595. }
  596. // Destroy cleans up any known cyclical references so the object can be freed by GC. This should be called if a new
  597. // firewall object is created
  598. func (f *Firewall) Destroy() {
  599. //TODO: clean references if/when needed
  600. }
  601. func (f *Firewall) EmitStats() {
  602. conntrack := f.Conntrack
  603. conntrack.Lock()
  604. conntrackCount := len(conntrack.Conns)
  605. conntrack.Unlock()
  606. metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
  607. metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
  608. metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
  609. }
  610. func (f *Firewall) peek(fp firewall.Packet) *conn {
  611. conntrack := f.Conntrack
  612. conntrack.Lock()
  613. // Purge every time we test
  614. ep, has := conntrack.TimerWheel.Purge()
  615. if has {
  616. f.evict(ep)
  617. }
  618. c := conntrack.Conns[fp]
  619. conntrack.Unlock()
  620. return c
  621. }
  622. func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) *conn {
  623. conntrack := f.Conntrack
  624. conntrack.Lock()
  625. // Purge every time we test
  626. ep, has := conntrack.TimerWheel.Purge()
  627. if has {
  628. f.evict(ep)
  629. }
  630. c, ok := conntrack.Conns[fp]
  631. if !ok {
  632. conntrack.Unlock()
  633. return nil
  634. }
  635. if c.rulesVersion != f.rulesVersion {
  636. // This conntrack entry was for an older rule set, validate
  637. // it still passes with the current rule set
  638. table := f.OutRules
  639. if c.incoming {
  640. table = f.InRules
  641. }
  642. // We now know which firewall table to check against
  643. if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
  644. if f.l.Level >= logrus.DebugLevel {
  645. h.logger(f.l).
  646. WithField("fwPacket", fp).
  647. WithField("incoming", c.incoming).
  648. WithField("rulesVersion", f.rulesVersion).
  649. WithField("oldRulesVersion", c.rulesVersion).
  650. Debugln("dropping old conntrack entry, does not match new ruleset")
  651. }
  652. delete(conntrack.Conns, fp)
  653. conntrack.Unlock()
  654. return nil
  655. }
  656. if f.l.Level >= logrus.DebugLevel {
  657. h.logger(f.l).
  658. WithField("fwPacket", fp).
  659. WithField("incoming", c.incoming).
  660. WithField("rulesVersion", f.rulesVersion).
  661. WithField("oldRulesVersion", c.rulesVersion).
  662. Debugln("keeping old conntrack entry, does match new ruleset")
  663. }
  664. c.rulesVersion = f.rulesVersion
  665. }
  666. switch fp.Protocol {
  667. case firewall.ProtoTCP:
  668. c.Expires = time.Now().Add(f.TCPTimeout)
  669. case firewall.ProtoUDP:
  670. c.Expires = time.Now().Add(f.UDPTimeout)
  671. default:
  672. c.Expires = time.Now().Add(f.DefaultTimeout)
  673. }
  674. conntrack.Unlock()
  675. if localCache != nil {
  676. localCache[fp] = struct{}{}
  677. }
  678. return c
  679. }
  680. func (f *Firewall) packetTimeout(fp firewall.Packet) time.Duration {
  681. var timeout time.Duration
  682. switch fp.Protocol {
  683. case firewall.ProtoTCP:
  684. timeout = f.TCPTimeout
  685. case firewall.ProtoUDP:
  686. timeout = f.UDPTimeout
  687. default:
  688. timeout = f.DefaultTimeout
  689. }
  690. return timeout
  691. }
  692. func (f *Firewall) addConn(fp firewall.Packet, incoming bool) *conn {
  693. c := &conn{}
  694. timeout := f.packetTimeout(fp)
  695. conntrack := f.Conntrack
  696. conntrack.Lock()
  697. if _, ok := conntrack.Conns[fp]; !ok {
  698. conntrack.TimerWheel.Advance(time.Now())
  699. conntrack.TimerWheel.Add(fp, timeout)
  700. }
  701. // Record which rulesVersion allowed this connection, so we can retest after
  702. // firewall reload
  703. c.incoming = incoming
  704. c.rulesVersion = f.rulesVersion
  705. c.Expires = time.Now().Add(timeout)
  706. conntrack.Conns[fp] = c
  707. conntrack.Unlock()
  708. return c
  709. }
  710. // Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
  711. // Caller must own the connMutex lock!
  712. func (f *Firewall) evict(p firewall.Packet) {
  713. // Are we still tracking this conn?
  714. conntrack := f.Conntrack
  715. t, ok := conntrack.Conns[p]
  716. if !ok {
  717. return
  718. }
  719. newT := t.Expires.Sub(time.Now())
  720. // Timeout is in the future, re-add the timer
  721. if newT > 0 {
  722. conntrack.TimerWheel.Advance(time.Now())
  723. conntrack.TimerWheel.Add(p, newT)
  724. return
  725. }
  726. // This conn is done
  727. delete(conntrack.Conns, p)
  728. }
  729. func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  730. if ft.AnyProto.match(p, incoming, c, caPool) {
  731. return true
  732. }
  733. switch p.Protocol {
  734. case firewall.ProtoTCP:
  735. if ft.TCP.match(p, incoming, c, caPool) {
  736. return true
  737. }
  738. case firewall.ProtoUDP:
  739. if ft.UDP.match(p, incoming, c, caPool) {
  740. return true
  741. }
  742. case firewall.ProtoICMP, firewall.ProtoICMPv6:
  743. if ft.ICMP.match(p, incoming, c, caPool) {
  744. return true
  745. }
  746. }
  747. return false
  748. }
  749. func (fp firewallPort) addRule(f *Firewall, startPort int32, endPort int32, groups []string, host string, cidr, localCidr, caName string, caSha string) error {
  750. if startPort > endPort {
  751. return fmt.Errorf("start port was lower than end port")
  752. }
  753. for i := startPort; i <= endPort; i++ {
  754. if _, ok := fp[i]; !ok {
  755. fp[i] = &FirewallCA{
  756. CANames: make(map[string]*FirewallRule),
  757. CAShas: make(map[string]*FirewallRule),
  758. }
  759. }
  760. if err := fp[i].addRule(f, groups, host, cidr, localCidr, caName, caSha); err != nil {
  761. return err
  762. }
  763. }
  764. return nil
  765. }
  766. func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  767. // We don't have any allowed ports, bail
  768. if fp == nil {
  769. return false
  770. }
  771. // this branch is here to catch traffic from FirewallTable.Any.match and FirewallTable.ICMP.match
  772. if p.Protocol == firewall.ProtoICMP || p.Protocol == firewall.ProtoICMPv6 {
  773. // port numbers are re-used for connection tracking of ICMP,
  774. // but we don't want to actually filter on them.
  775. return fp[firewall.PortAny].match(p, c, caPool)
  776. }
  777. var port int32
  778. if p.Protocol == firewall.ProtoICMP {
  779. // port numbers are re-used for connection tracking and SNAT,
  780. // but we don't want to actually filter on them for ICMP
  781. // ICMP6 is omitted because we don't attempt to parse code/identifier/etc out of ICMP6
  782. return fp[firewall.PortAny].match(p, c, caPool)
  783. }
  784. if p.Fragment {
  785. port = firewall.PortFragment
  786. } else if incoming {
  787. port = int32(p.LocalPort)
  788. } else {
  789. port = int32(p.RemotePort)
  790. }
  791. if fp[port].match(p, c, caPool) {
  792. return true
  793. }
  794. return fp[firewall.PortAny].match(p, c, caPool)
  795. }
  796. func (fc *FirewallCA) addRule(f *Firewall, groups []string, host string, cidr, localCidr, caName, caSha string) error {
  797. fr := func() *FirewallRule {
  798. return &FirewallRule{
  799. Hosts: make(map[string]*firewallLocalCIDR),
  800. Groups: make([]*firewallGroups, 0),
  801. CIDR: new(bart.Table[*firewallLocalCIDR]),
  802. }
  803. }
  804. if caSha == "" && caName == "" {
  805. if fc.Any == nil {
  806. fc.Any = fr()
  807. }
  808. return fc.Any.addRule(f, groups, host, cidr, localCidr)
  809. }
  810. if caSha != "" {
  811. if _, ok := fc.CAShas[caSha]; !ok {
  812. fc.CAShas[caSha] = fr()
  813. }
  814. err := fc.CAShas[caSha].addRule(f, groups, host, cidr, localCidr)
  815. if err != nil {
  816. return err
  817. }
  818. }
  819. if caName != "" {
  820. if _, ok := fc.CANames[caName]; !ok {
  821. fc.CANames[caName] = fr()
  822. }
  823. err := fc.CANames[caName].addRule(f, groups, host, cidr, localCidr)
  824. if err != nil {
  825. return err
  826. }
  827. }
  828. return nil
  829. }
  830. func (fc *FirewallCA) match(p firewall.Packet, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
  831. if fc == nil {
  832. return false
  833. }
  834. if fc.Any.match(p, c) {
  835. return true
  836. }
  837. if t, ok := fc.CAShas[c.Certificate.Issuer()]; ok {
  838. if t.match(p, c) {
  839. return true
  840. }
  841. }
  842. s, err := caPool.GetCAForCert(c.Certificate)
  843. if err != nil {
  844. return false
  845. }
  846. return fc.CANames[s.Certificate.Name()].match(p, c)
  847. }
  848. func (fr *FirewallRule) addRule(f *Firewall, groups []string, host, cidr, localCidr string) error {
  849. flc := func() *firewallLocalCIDR {
  850. return &firewallLocalCIDR{
  851. LocalCIDR: new(bart.Lite),
  852. }
  853. }
  854. if fr.isAny(groups, host, cidr) {
  855. if fr.Any == nil {
  856. fr.Any = flc()
  857. }
  858. return fr.Any.addRule(f, localCidr)
  859. }
  860. if len(groups) > 0 {
  861. nlc := flc()
  862. err := nlc.addRule(f, localCidr)
  863. if err != nil {
  864. return err
  865. }
  866. fr.Groups = append(fr.Groups, &firewallGroups{
  867. Groups: groups,
  868. LocalCIDR: nlc,
  869. })
  870. }
  871. if host != "" {
  872. nlc := fr.Hosts[host]
  873. if nlc == nil {
  874. nlc = flc()
  875. }
  876. err := nlc.addRule(f, localCidr)
  877. if err != nil {
  878. return err
  879. }
  880. fr.Hosts[host] = nlc
  881. }
  882. if cidr != "" {
  883. c, err := netip.ParsePrefix(cidr)
  884. if err != nil {
  885. return err
  886. }
  887. nlc, _ := fr.CIDR.Get(c)
  888. if nlc == nil {
  889. nlc = flc()
  890. }
  891. err = nlc.addRule(f, localCidr)
  892. if err != nil {
  893. return err
  894. }
  895. fr.CIDR.Insert(c, nlc)
  896. }
  897. return nil
  898. }
  899. func (fr *FirewallRule) isAny(groups []string, host string, cidr string) bool {
  900. if len(groups) == 0 && host == "" && cidr == "" {
  901. return true
  902. }
  903. if slices.Contains(groups, "any") {
  904. return true
  905. }
  906. if host == "any" {
  907. return true
  908. }
  909. if cidr == "any" {
  910. return true
  911. }
  912. return false
  913. }
  914. func (fr *FirewallRule) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  915. if fr == nil {
  916. return false
  917. }
  918. // Shortcut path for if groups, hosts, or cidr contained an `any`
  919. if fr.Any.match(p, c) {
  920. return true
  921. }
  922. // Need any of group, host, or cidr to match
  923. for _, sg := range fr.Groups {
  924. found := false
  925. for _, g := range sg.Groups {
  926. if _, ok := c.InvertedGroups[g]; !ok {
  927. found = false
  928. break
  929. }
  930. found = true
  931. }
  932. if found && sg.LocalCIDR.match(p, c) {
  933. return true
  934. }
  935. }
  936. if fr.Hosts != nil {
  937. if flc, ok := fr.Hosts[c.Certificate.Name()]; ok {
  938. if flc.match(p, c) {
  939. return true
  940. }
  941. }
  942. }
  943. for _, v := range fr.CIDR.Supernets(netip.PrefixFrom(p.RemoteAddr, p.RemoteAddr.BitLen())) {
  944. if v.match(p, c) {
  945. return true
  946. }
  947. }
  948. return false
  949. }
  950. func (flc *firewallLocalCIDR) addRule(f *Firewall, localCidr string) error {
  951. if localCidr == "any" {
  952. flc.Any = true
  953. return nil
  954. }
  955. if localCidr == "" {
  956. if !f.hasUnsafeNetworks || f.defaultLocalCIDRAny {
  957. flc.Any = true
  958. return nil
  959. }
  960. for _, network := range f.assignedNetworks {
  961. flc.LocalCIDR.Insert(network)
  962. }
  963. return nil
  964. }
  965. c, err := netip.ParsePrefix(localCidr)
  966. if err != nil {
  967. return err
  968. }
  969. flc.LocalCIDR.Insert(c)
  970. return nil
  971. }
  972. func (flc *firewallLocalCIDR) match(p firewall.Packet, c *cert.CachedCertificate) bool {
  973. if flc == nil {
  974. return false
  975. }
  976. if flc.Any {
  977. return true
  978. }
  979. return flc.LocalCIDR.Contains(p.LocalAddr)
  980. }
  981. type rule struct {
  982. Port string
  983. Code string
  984. Proto string
  985. Host string
  986. Groups []string
  987. Cidr string
  988. LocalCidr string
  989. CAName string
  990. CASha string
  991. }
  992. func convertRule(l *logrus.Logger, p any, table string, i int) (rule, error) {
  993. r := rule{}
  994. m, ok := p.(map[string]any)
  995. if !ok {
  996. return r, errors.New("could not parse rule")
  997. }
  998. toString := func(k string, m map[string]any) string {
  999. v, ok := m[k]
  1000. if !ok {
  1001. return ""
  1002. }
  1003. return fmt.Sprintf("%v", v)
  1004. }
  1005. r.Port = toString("port", m)
  1006. r.Code = toString("code", m)
  1007. r.Proto = toString("proto", m)
  1008. r.Host = toString("host", m)
  1009. r.Cidr = toString("cidr", m)
  1010. r.LocalCidr = toString("local_cidr", m)
  1011. r.CAName = toString("ca_name", m)
  1012. r.CASha = toString("ca_sha", m)
  1013. // Make sure group isn't an array
  1014. if v, ok := m["group"].([]any); ok {
  1015. if len(v) > 1 {
  1016. return r, errors.New("group should contain a single value, an array with more than one entry was provided")
  1017. }
  1018. l.Warnf("%s rule #%v; group was an array with a single value, converting to simple value", table, i)
  1019. m["group"] = v[0]
  1020. }
  1021. singleGroup := toString("group", m)
  1022. if rg, ok := m["groups"]; ok {
  1023. switch reflect.TypeOf(rg).Kind() {
  1024. case reflect.Slice:
  1025. v := reflect.ValueOf(rg)
  1026. r.Groups = make([]string, v.Len())
  1027. for i := 0; i < v.Len(); i++ {
  1028. r.Groups[i] = v.Index(i).Interface().(string)
  1029. }
  1030. case reflect.String:
  1031. r.Groups = []string{rg.(string)}
  1032. default:
  1033. r.Groups = []string{fmt.Sprintf("%v", rg)}
  1034. }
  1035. }
  1036. //flatten group vs groups
  1037. if singleGroup != "" {
  1038. // Check if we have both groups and group provided in the rule config
  1039. if len(r.Groups) > 0 {
  1040. return r, fmt.Errorf("only one of group or groups should be defined, both provided")
  1041. }
  1042. r.Groups = []string{singleGroup}
  1043. }
  1044. return r, nil
  1045. }
  1046. // sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
  1047. // rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
  1048. func (r *rule) sanity() error {
  1049. //port, proto, local_cidr are AND, no need to check here
  1050. //ca_sha and ca_name don't have a wildcard value, no need to check here
  1051. groupsEmpty := len(r.Groups) == 0
  1052. hostEmpty := r.Host == ""
  1053. cidrEmpty := r.Cidr == ""
  1054. if (groupsEmpty && hostEmpty && cidrEmpty) == true {
  1055. return nil //no content!
  1056. }
  1057. groupsHasAny := slices.Contains(r.Groups, "any")
  1058. if groupsHasAny && len(r.Groups) > 1 {
  1059. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the other groups specified", r.Groups)
  1060. }
  1061. if r.Host == "any" {
  1062. if !groupsEmpty {
  1063. return fmt.Errorf("groups specified as %s, but host=any will match any host, regardless of groups", r.Groups)
  1064. }
  1065. if !cidrEmpty {
  1066. return fmt.Errorf("cidr specified as %s, but host=any will match any host, regardless of cidr", r.Cidr)
  1067. }
  1068. }
  1069. if groupsHasAny {
  1070. if !hostEmpty && r.Host != "any" {
  1071. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified host %s", r.Groups, r.Host)
  1072. }
  1073. if !cidrEmpty {
  1074. return fmt.Errorf("groups spec [%s] contains the group '\"any\". This rule will ignore the specified cidr %s", r.Groups, r.Cidr)
  1075. }
  1076. }
  1077. if r.Code != "" {
  1078. 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)
  1079. }
  1080. //todo alert on cidr-any
  1081. return nil
  1082. }
  1083. func parsePort(s string) (int32, int32, error) {
  1084. var err error
  1085. const notAPort int32 = -2
  1086. if s == "any" {
  1087. return firewall.PortAny, firewall.PortAny, nil
  1088. }
  1089. if s == "fragment" {
  1090. return firewall.PortFragment, firewall.PortFragment, nil
  1091. }
  1092. if !strings.Contains(s, `-`) {
  1093. rPort, err := strconv.Atoi(s)
  1094. if err != nil {
  1095. return notAPort, notAPort, fmt.Errorf("was not a number; `%s`", s)
  1096. }
  1097. return int32(rPort), int32(rPort), nil
  1098. }
  1099. sPorts := strings.SplitN(s, `-`, 2)
  1100. for i := range sPorts {
  1101. sPorts[i] = strings.Trim(sPorts[i], " ")
  1102. }
  1103. if len(sPorts) != 2 || sPorts[0] == "" || sPorts[1] == "" {
  1104. return notAPort, notAPort, fmt.Errorf("appears to be a range but could not be parsed; `%s`", s)
  1105. }
  1106. rStartPort, err := strconv.Atoi(sPorts[0])
  1107. if err != nil {
  1108. return notAPort, notAPort, fmt.Errorf("beginning range was not a number; `%s`", sPorts[0])
  1109. }
  1110. rEndPort, err := strconv.Atoi(sPorts[1])
  1111. if err != nil {
  1112. return notAPort, notAPort, fmt.Errorf("ending range was not a number; `%s`", sPorts[1])
  1113. }
  1114. startPort := int32(rStartPort)
  1115. endPort := int32(rEndPort)
  1116. if startPort == firewall.PortAny {
  1117. endPort = firewall.PortAny
  1118. }
  1119. return startPort, endPort, nil
  1120. }