gateway.go 15 KB

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