gateway.go 14 KB

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