gateway.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/gravitl/netmaker/database"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. )
  13. // CreateEgressGateway - creates an egress gateway
  14. func CreateEgressGateway(gateway models.EgressGatewayRequest) (models.Node, error) {
  15. node, err := GetNodeByID(gateway.NodeID)
  16. if err != nil {
  17. return models.Node{}, err
  18. }
  19. host, err := GetHost(node.HostID.String())
  20. if err != nil {
  21. return models.Node{}, err
  22. }
  23. for i, cidr := range gateway.Ranges {
  24. normalized, err := NormalizeCIDR(cidr)
  25. if err != nil {
  26. return models.Node{}, err
  27. }
  28. gateway.Ranges[i] = normalized
  29. }
  30. if host.OS != "linux" && host.OS != "freebsd" { // add in darwin later
  31. return models.Node{}, errors.New(host.OS + " is unsupported for egress gateways")
  32. }
  33. if host.OS == "linux" && host.FirewallInUse == models.FIREWALL_NONE {
  34. return models.Node{}, errors.New("firewall is not supported for egress gateways")
  35. }
  36. if gateway.NatEnabled == "" {
  37. gateway.NatEnabled = "yes"
  38. }
  39. err = ValidateEgressGateway(gateway)
  40. if err != nil {
  41. return models.Node{}, err
  42. }
  43. node.IsEgressGateway = true
  44. node.EgressGatewayRanges = gateway.Ranges
  45. node.EgressGatewayNatEnabled = models.ParseBool(gateway.NatEnabled)
  46. node.EgressGatewayRequest = gateway // store entire request for use when preserving the egress gateway
  47. postUpCmd := ""
  48. postDownCmd := ""
  49. ipv4, ipv6 := getNetworkProtocols(gateway.Ranges)
  50. logger.Log(3, "creating egress gateway firewall in use is '", host.FirewallInUse, "'")
  51. iface := models.WIREGUARD_INTERFACE
  52. if host.OS == "linux" {
  53. switch host.FirewallInUse {
  54. case models.FIREWALL_NFTABLES:
  55. // nftables only supported on Linux
  56. // assumes chains eg FORWARD and postrouting already exist
  57. logger.Log(3, "creating egress gateway nftables is present")
  58. // down commands don't remove as removal of the rules leaves an empty chain while
  59. // removing the chain with rules in it would remove all rules in that section (not safe
  60. // if there are remaining rules on the host that need to stay). In practice the chain is removed
  61. // when non-empty even though the removal of a non-empty chain should not be possible per nftables wiki.
  62. postUpCmd, postDownCmd = firewallNFTCommandsCreateEgress(iface, gateway.Interface, gateway.Ranges, node.EgressGatewayNatEnabled, ipv4, ipv6)
  63. default: // iptables assumed
  64. logger.Log(3, "creating egress gateway nftables is not present")
  65. postUpCmd, postDownCmd = firewallIPTablesCommandsCreateEgress(iface, gateway.Interface, node.EgressGatewayNatEnabled, ipv4, ipv6)
  66. }
  67. }
  68. if host.OS == "freebsd" {
  69. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  70. postUpCmd = "kldload ipfw ipfw_nat ; "
  71. postUpCmd += "ipfw disable one_pass ; "
  72. postUpCmd += "ipfw nat 1 config if " + gateway.Interface + " same_ports unreg_only reset ; "
  73. postUpCmd += "ipfw add 64000 reass all from any to any in ; "
  74. postUpCmd += "ipfw add 64000 nat 1 ip from any to any in via " + gateway.Interface + " ; "
  75. postUpCmd += "ipfw add 64000 check-state ; "
  76. postUpCmd += "ipfw add 64000 nat 1 ip from any to any out via " + gateway.Interface + " ; "
  77. postUpCmd += "ipfw add 65534 allow ip from any to any ; "
  78. postDownCmd = "ipfw delete 64000 ; "
  79. postDownCmd += "ipfw delete 65534 ; "
  80. postDownCmd += "kldunload ipfw_nat ipfw"
  81. }
  82. if gateway.PostUp != "" {
  83. postUpCmd = gateway.PostUp
  84. }
  85. if gateway.PostDown != "" {
  86. postDownCmd = gateway.PostDown
  87. }
  88. if node.PostUp != "" {
  89. if !strings.Contains(node.PostUp, postUpCmd) {
  90. postUpCmd = node.PostUp + postUpCmd
  91. }
  92. }
  93. if node.PostDown != "" {
  94. if !strings.Contains(node.PostDown, postDownCmd) {
  95. postDownCmd = node.PostDown + postDownCmd
  96. }
  97. }
  98. node.PostUp = postUpCmd
  99. node.PostDown = postDownCmd
  100. node.SetLastModified()
  101. nodeData, err := json.Marshal(&node)
  102. if err != nil {
  103. return node, err
  104. }
  105. if err = database.Insert(node.ID.String(), string(nodeData), database.NODES_TABLE_NAME); err != nil {
  106. return models.Node{}, err
  107. }
  108. return node, nil
  109. }
  110. // ValidateEgressGateway - validates the egress gateway model
  111. func ValidateEgressGateway(gateway models.EgressGatewayRequest) error {
  112. var err error
  113. empty := len(gateway.Ranges) == 0
  114. if empty {
  115. err = errors.New("IP Ranges Cannot Be Empty")
  116. }
  117. empty = gateway.Interface == ""
  118. if empty {
  119. err = errors.New("interface cannot be empty")
  120. }
  121. return err
  122. }
  123. // DeleteEgressGateway - deletes egress from node
  124. func DeleteEgressGateway(network, nodeid string) (models.Node, error) {
  125. node, err := GetNodeByID(nodeid)
  126. if err != nil {
  127. return models.Node{}, err
  128. }
  129. host, err := GetHost(node.HostID.String())
  130. if err != nil {
  131. return models.Node{}, err
  132. }
  133. node.IsEgressGateway = false
  134. node.EgressGatewayRanges = []string{}
  135. node.EgressGatewayRequest = models.EgressGatewayRequest{} // remove preserved request as the egress gateway is gone
  136. // needed in case we don't preserve a gateway (i.e., no ingress to preserve)
  137. node.PostUp = ""
  138. node.PostDown = ""
  139. cidrs := []string{}
  140. cidrs = append(cidrs, node.IngressGatewayRange)
  141. cidrs = append(cidrs, node.IngressGatewayRange6)
  142. ipv4, ipv6 := getNetworkProtocols(cidrs)
  143. logger.Log(3, "deleting egress gateway firewall in use is '", host.FirewallInUse, "'")
  144. if node.IsIngressGateway { // check if node is still an ingress gateway before completely deleting postdown/up rules
  145. // still have an ingress gateway so preserve it
  146. iface := models.WIREGUARD_INTERFACE
  147. if host.OS == "linux" {
  148. switch host.FirewallInUse {
  149. case models.FIREWALL_NFTABLES:
  150. // nftables only supported on Linux
  151. // assumes chains eg FORWARD and postrouting already exist
  152. logger.Log(3, "deleting egress gateway nftables is present")
  153. node.PostUp, node.PostDown = firewallNFTCommandsCreateIngress(iface)
  154. default:
  155. logger.Log(3, "deleting egress gateway nftables is not present")
  156. node.PostUp, node.PostDown = firewallIPTablesCommandsCreateIngress(iface, ipv4, ipv6)
  157. }
  158. }
  159. // no need to preserve ingress gateway on FreeBSD as ingress is not supported on that OS
  160. }
  161. node.SetLastModified()
  162. data, err := json.Marshal(&node)
  163. if err != nil {
  164. return models.Node{}, err
  165. }
  166. if err = database.Insert(node.ID.String(), string(data), database.NODES_TABLE_NAME); err != nil {
  167. return models.Node{}, err
  168. }
  169. return node, nil
  170. }
  171. // CreateIngressGateway - creates an ingress gateway
  172. func CreateIngressGateway(netid string, nodeid string, failover bool) (models.Node, error) {
  173. var postUpCmd, postDownCmd string
  174. node, err := GetNodeByID(nodeid)
  175. if err != nil {
  176. return models.Node{}, err
  177. }
  178. host, err := GetHost(node.HostID.String())
  179. if err != nil {
  180. return models.Node{}, err
  181. }
  182. if host.OS != "linux" {
  183. return models.Node{}, errors.New("ingress can only be created on linux based node")
  184. }
  185. if host.FirewallInUse == models.FIREWALL_NONE {
  186. return models.Node{}, errors.New("firewall is not supported for ingress gateways")
  187. }
  188. network, err := GetParentNetwork(netid)
  189. if err != nil {
  190. return models.Node{}, err
  191. }
  192. node.IsIngressGateway = true
  193. cidrs := []string{}
  194. cidrs = append(cidrs, network.AddressRange)
  195. cidrs = append(cidrs, network.AddressRange6)
  196. node.IngressGatewayRange = network.AddressRange
  197. node.IngressGatewayRange6 = network.AddressRange6
  198. ipv4, ipv6 := getNetworkProtocols(cidrs)
  199. logger.Log(3, "creating ingress gateway firewall in use is '", host.FirewallInUse, "'")
  200. iface := models.WIREGUARD_INTERFACE
  201. switch host.FirewallInUse {
  202. case models.FIREWALL_NFTABLES:
  203. // nftables only supported on Linux
  204. // assumes chains eg FORWARD and postrouting already exist
  205. logger.Log(3, "creating ingress gateway nftables is present")
  206. postUpCmd, postDownCmd = firewallNFTCommandsCreateIngress(iface)
  207. default:
  208. logger.Log(3, "creating ingress gateway using nftables is not present")
  209. postUpCmd, postDownCmd = firewallIPTablesCommandsCreateIngress(iface, ipv4, ipv6)
  210. }
  211. if node.PostUp != "" {
  212. if !strings.Contains(node.PostUp, postUpCmd) {
  213. postUpCmd = node.PostUp + postUpCmd
  214. }
  215. }
  216. if node.PostDown != "" {
  217. if !strings.Contains(node.PostDown, postDownCmd) {
  218. postDownCmd = node.PostDown + postDownCmd
  219. }
  220. }
  221. node.SetLastModified()
  222. node.PostUp = postUpCmd
  223. node.PostDown = postDownCmd
  224. if failover && servercfg.Is_EE {
  225. node.Failover = true
  226. }
  227. data, err := json.Marshal(&node)
  228. if err != nil {
  229. return models.Node{}, err
  230. }
  231. err = database.Insert(node.ID.String(), string(data), database.NODES_TABLE_NAME)
  232. if err != nil {
  233. return models.Node{}, err
  234. }
  235. err = SetNetworkNodesLastModified(netid)
  236. return node, err
  237. }
  238. // DeleteIngressGateway - deletes an ingress gateway
  239. func DeleteIngressGateway(networkName string, nodeid string) (models.Node, bool, error) {
  240. node, err := GetNodeByID(nodeid)
  241. if err != nil {
  242. return models.Node{}, false, err
  243. }
  244. //host, err := GetHost(node.ID.String())
  245. //if err != nil {
  246. //return models.Node{}, false, err
  247. //}
  248. //network, err := GetParentNetwork(networkName)
  249. if err != nil {
  250. return models.Node{}, false, err
  251. }
  252. // delete ext clients belonging to ingress gateway
  253. if err = DeleteGatewayExtClients(node.ID.String(), networkName); err != nil {
  254. return models.Node{}, false, err
  255. }
  256. logger.Log(3, "deleting ingress gateway")
  257. wasFailover := node.Failover
  258. node.LastModified = time.Now()
  259. node.IsIngressGateway = false
  260. node.IngressGatewayRange = ""
  261. node.Failover = false
  262. // default to removing postup and postdown
  263. node.PostUp = ""
  264. node.PostDown = ""
  265. //logger.Log(3, "deleting ingress gateway firewall in use is '", host.FirewallInUse, "' and isEgressGateway is", node.IsEgressGateway)
  266. if node.EgressGatewayRequest.NodeID != "" {
  267. _, err := CreateEgressGateway(node.EgressGatewayRequest)
  268. if err != nil {
  269. logger.Log(0, fmt.Sprintf("failed to create egress gateway on node [%s] on network [%s]: %v",
  270. node.EgressGatewayRequest.NodeID, node.EgressGatewayRequest.NetID, err))
  271. }
  272. }
  273. data, err := json.Marshal(&node)
  274. if err != nil {
  275. return models.Node{}, false, err
  276. }
  277. err = database.Insert(node.ID.String(), string(data), database.NODES_TABLE_NAME)
  278. if err != nil {
  279. return models.Node{}, wasFailover, err
  280. }
  281. err = SetNetworkNodesLastModified(networkName)
  282. return node, wasFailover, err
  283. }
  284. // DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network
  285. func DeleteGatewayExtClients(gatewayID string, networkName string) error {
  286. currentExtClients, err := GetNetworkExtClients(networkName)
  287. if err != nil && !database.IsEmptyRecord(err) {
  288. return err
  289. }
  290. for _, extClient := range currentExtClients {
  291. if extClient.IngressGatewayID == gatewayID {
  292. if err = DeleteExtClient(networkName, extClient.ClientID); err != nil {
  293. logger.Log(1, "failed to remove ext client", extClient.ClientID)
  294. continue
  295. }
  296. }
  297. }
  298. return nil
  299. }
  300. // firewallNFTCommandsCreateIngress - used to centralize firewall command maintenance for creating an ingress gateway using the nftables firewall.
  301. func firewallNFTCommandsCreateIngress(networkInterface string) (string, string) {
  302. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  303. postUp := "nft add table ip filter ; "
  304. postUp += "nft add chain ip filter FORWARD ; "
  305. postUp += "nft add rule ip filter FORWARD iifname " + networkInterface + " counter accept ; "
  306. postUp += "nft add rule ip filter FORWARD oifname " + networkInterface + " counter accept ; "
  307. postUp += "nft add table nat ; "
  308. postUp += "nft add chain nat postrouting ; "
  309. postUp += "nft add rule ip nat postrouting oifname " + networkInterface + " counter masquerade ; "
  310. // doesn't remove potentially empty tables or chains
  311. postDown := "nft flush table filter ; "
  312. postDown += "nft flush table nat ; "
  313. return postUp, postDown
  314. }
  315. // firewallNFTCommandsCreateEgress - used to centralize firewall command maintenance for creating an egress gateway using the nftables firewall.
  316. func firewallNFTCommandsCreateEgress(networkInterface string, gatewayInterface string, gatewayranges []string, egressNatEnabled bool, ipv4, ipv6 bool) (string, string) {
  317. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  318. postUp := ""
  319. postDown := ""
  320. if ipv4 {
  321. postUp += "nft add table ip filter ; "
  322. postUp += "nft add chain ip filter forward ; "
  323. postUp += "nft add rule filter forward ct state related,established accept ; "
  324. postUp += "nft add rule ip filter forward iifname " + networkInterface + " accept ; "
  325. postUp += "nft add rule ip filter forward oifname " + networkInterface + " accept ; "
  326. postUp += "nft add table nat ; "
  327. postUp += "nft 'add chain ip nat prerouting { type nat hook prerouting priority 0 ;}' ; "
  328. postUp += "nft 'add chain ip nat postrouting { type nat hook postrouting priority 0 ;}' ; "
  329. postDown += "nft flush table filter ; "
  330. if egressNatEnabled {
  331. postUp += "nft add table nat ; "
  332. postUp += "nft add chain nat postrouting ; "
  333. postUp += "nft add rule ip nat postrouting oifname " + gatewayInterface + " counter masquerade ; "
  334. postDown += "nft flush table nat ; "
  335. }
  336. }
  337. if ipv6 {
  338. postUp += "nft add table ip6 filter ; "
  339. postUp += "nft add chain ip6 filter forward ; "
  340. postUp += "nft add rule ip6 filter forward ct state related,established accept ; "
  341. postUp += "nft add rule ip6 filter forward iifname " + networkInterface + " accept ; "
  342. postUp += "nft add rule ip6 filter forward oifname " + networkInterface + " accept ; "
  343. postDown += "nft flush table ip6 filter ; "
  344. if egressNatEnabled {
  345. postUp += "nft add table ip6 nat ; "
  346. postUp += "nft 'add chain ip6 nat prerouting { type nat hook prerouting priority 0 ;}' ; "
  347. postUp += "nft 'add chain ip6 nat postrouting { type nat hook postrouting priority 0 ;}' ; "
  348. postUp += "nft add rule ip6 nat postrouting oifname " + gatewayInterface + " masquerade ; "
  349. postDown += "nft flush table ip6 nat ; "
  350. }
  351. }
  352. return postUp, postDown
  353. }
  354. // firewallIPTablesCommandsCreateIngress - used to centralize firewall command maintenance for creating an ingress gateway using the iptables firewall.
  355. func firewallIPTablesCommandsCreateIngress(networkInterface string, ipv4, ipv6 bool) (string, string) {
  356. postUp := ""
  357. postDown := ""
  358. if ipv4 {
  359. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  360. postUp += "iptables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  361. postUp += "iptables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  362. postUp += "iptables -t nat -A POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  363. // doesn't remove potentially empty tables or chains
  364. postDown += "iptables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  365. postDown += "iptables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  366. postDown += "iptables -t nat -D POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  367. }
  368. if ipv6 {
  369. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  370. postUp += "ip6tables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  371. postUp += "ip6tables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  372. postUp += "ip6tables -t nat -A POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  373. // doesn't remove potentially empty tables or chains
  374. postDown += "ip6tables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  375. postDown += "ip6tables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  376. postDown += "ip6tables -t nat -D POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  377. }
  378. return postUp, postDown
  379. }
  380. // firewallIPTablesCommandsCreateEgress - used to centralize firewall command maintenance for creating an egress gateway using the iptables firewall.
  381. func firewallIPTablesCommandsCreateEgress(networkInterface string, gatewayInterface string, egressNatEnabled bool, ipv4, ipv6 bool) (string, string) {
  382. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  383. postUp := ""
  384. postDown := ""
  385. if ipv4 {
  386. postUp += "iptables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  387. postUp += "iptables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  388. postDown += "iptables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  389. postDown += "iptables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  390. if egressNatEnabled {
  391. postUp += "iptables -t nat -A POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  392. postDown += "iptables -t nat -D POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  393. }
  394. }
  395. if ipv6 {
  396. postUp += "ip6tables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  397. postUp += "ip6tables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  398. postDown += "ip6tables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  399. postDown += "ip6tables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  400. if egressNatEnabled {
  401. postUp += "ip6tables -t nat -A POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  402. postDown += "ip6tables -t nat -D POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  403. }
  404. }
  405. return postUp, postDown
  406. }