gateway.go 17 KB

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