gateway.go 17 KB

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