gateway.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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, ipv4, ipv6)
  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. cidrs := []string{}
  123. cidrs = append(cidrs, node.IngressGatewayRange)
  124. cidrs = append(cidrs, node.IngressGatewayRange6)
  125. ipv4, ipv6 := getNetworkProtocols(cidrs)
  126. logger.Log(3, "deleting egress gateway firewall in use is '", node.FirewallInUse, "'")
  127. if node.IsIngressGateway == "yes" { // check if node is still an ingress gateway before completely deleting postdown/up rules
  128. // still have an ingress gateway so preserve it
  129. if node.OS == "linux" {
  130. switch node.FirewallInUse {
  131. case models.FIREWALL_NFTABLES:
  132. // nftables only supported on Linux
  133. // assumes chains eg FORWARD and postrouting already exist
  134. logger.Log(3, "deleting egress gateway nftables is present")
  135. node.PostUp, node.PostDown = firewallNFTCommandsCreateIngress(node.Interface)
  136. default:
  137. logger.Log(3, "deleting egress gateway nftables is not present")
  138. node.PostUp, node.PostDown = firewallIPTablesCommandsCreateIngress(node.Interface, ipv4, ipv6)
  139. }
  140. }
  141. // no need to preserve ingress gateway on FreeBSD as ingress is not supported on that OS
  142. }
  143. node.SetLastModified()
  144. data, err := json.Marshal(&node)
  145. if err != nil {
  146. return models.Node{}, err
  147. }
  148. if err = database.Insert(node.ID, string(data), database.NODES_TABLE_NAME); err != nil {
  149. return models.Node{}, err
  150. }
  151. return node, nil
  152. }
  153. // CreateIngressGateway - creates an ingress gateway
  154. func CreateIngressGateway(netid string, nodeid string) (models.Node, error) {
  155. var postUpCmd, postDownCmd string
  156. node, err := GetNodeByID(nodeid)
  157. if node.OS != "linux" { // add in darwin later
  158. return models.Node{}, errors.New(node.OS + " is unsupported for ingress gateways")
  159. }
  160. if node.OS == "linux" && node.FirewallInUse == models.FIREWALL_NONE {
  161. return models.Node{}, errors.New("firewall is not supported for ingress gateways")
  162. }
  163. if err != nil {
  164. return models.Node{}, err
  165. }
  166. network, err := GetParentNetwork(netid)
  167. if err != nil {
  168. return models.Node{}, err
  169. }
  170. node.IsIngressGateway = "yes"
  171. cidrs := []string{}
  172. cidrs = append(cidrs, network.AddressRange)
  173. cidrs = append(cidrs, network.AddressRange6)
  174. node.IngressGatewayRange = network.AddressRange
  175. node.IngressGatewayRange6 = network.AddressRange6
  176. ipv4, ipv6 := getNetworkProtocols(cidrs)
  177. logger.Log(3, "creating ingress gateway firewall in use is '", node.FirewallInUse, "'")
  178. switch node.FirewallInUse {
  179. case models.FIREWALL_NFTABLES:
  180. // nftables only supported on Linux
  181. // assumes chains eg FORWARD and postrouting already exist
  182. logger.Log(3, "creating ingress gateway nftables is present")
  183. postUpCmd, postDownCmd = firewallNFTCommandsCreateIngress(node.Interface)
  184. default:
  185. logger.Log(3, "creating ingress gateway using nftables is not present")
  186. postUpCmd, postDownCmd = firewallIPTablesCommandsCreateIngress(node.Interface, ipv4, ipv6)
  187. }
  188. if node.PostUp != "" {
  189. if !strings.Contains(node.PostUp, postUpCmd) {
  190. postUpCmd = node.PostUp + " ; " + postUpCmd
  191. }
  192. }
  193. if node.PostDown != "" {
  194. if !strings.Contains(node.PostDown, postDownCmd) {
  195. postDownCmd = node.PostDown + " ; " + postDownCmd
  196. }
  197. }
  198. node.SetLastModified()
  199. node.PostUp = postUpCmd
  200. node.PostDown = postDownCmd
  201. node.UDPHolePunch = "no"
  202. data, err := json.Marshal(&node)
  203. if err != nil {
  204. return models.Node{}, err
  205. }
  206. err = database.Insert(node.ID, string(data), database.NODES_TABLE_NAME)
  207. if err != nil {
  208. return models.Node{}, err
  209. }
  210. err = SetNetworkNodesLastModified(netid)
  211. return node, err
  212. }
  213. // DeleteIngressGateway - deletes an ingress gateway
  214. func DeleteIngressGateway(networkName string, nodeid string) (models.Node, error) {
  215. node, err := GetNodeByID(nodeid)
  216. if err != nil {
  217. return models.Node{}, err
  218. }
  219. network, err := GetParentNetwork(networkName)
  220. if err != nil {
  221. return models.Node{}, err
  222. }
  223. // delete ext clients belonging to ingress gateway
  224. if err = DeleteGatewayExtClients(node.ID, networkName); err != nil {
  225. return models.Node{}, err
  226. }
  227. logger.Log(3, "deleting ingress gateway")
  228. node.UDPHolePunch = network.DefaultUDPHolePunch
  229. node.LastModified = time.Now().Unix()
  230. node.IsIngressGateway = "no"
  231. node.IngressGatewayRange = ""
  232. // default to removing postup and postdown
  233. node.PostUp = ""
  234. node.PostDown = ""
  235. logger.Log(3, "deleting ingress gateway firewall in use is '", node.FirewallInUse, "' and isEgressGateway is", node.IsEgressGateway)
  236. if node.EgressGatewayRequest.NodeID != "" {
  237. _, err := CreateEgressGateway(node.EgressGatewayRequest)
  238. if err != nil {
  239. logger.Log(0, fmt.Sprintf("failed to create egress gateway on node [%s] on network [%s]: %v",
  240. node.EgressGatewayRequest.NodeID, node.EgressGatewayRequest.NetID, err))
  241. }
  242. }
  243. data, err := json.Marshal(&node)
  244. if err != nil {
  245. return models.Node{}, err
  246. }
  247. err = database.Insert(node.ID, string(data), database.NODES_TABLE_NAME)
  248. if err != nil {
  249. return models.Node{}, err
  250. }
  251. err = SetNetworkNodesLastModified(networkName)
  252. return node, err
  253. }
  254. // DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network
  255. func DeleteGatewayExtClients(gatewayID string, networkName string) error {
  256. currentExtClients, err := GetNetworkExtClients(networkName)
  257. if err != nil && !database.IsEmptyRecord(err) {
  258. return err
  259. }
  260. for _, extClient := range currentExtClients {
  261. if extClient.IngressGatewayID == gatewayID {
  262. if err = DeleteExtClient(networkName, extClient.ClientID); err != nil {
  263. logger.Log(1, "failed to remove ext client", extClient.ClientID)
  264. continue
  265. }
  266. }
  267. }
  268. return nil
  269. }
  270. // firewallNFTCommandsCreateIngress - used to centralize firewall command maintenance for creating an ingress gateway using the nftables firewall.
  271. func firewallNFTCommandsCreateIngress(networkInterface string) (string, string) {
  272. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  273. postUp := "nft add table ip filter ; "
  274. postUp += "nft add chain ip filter FORWARD ; "
  275. postUp += "nft add rule ip filter FORWARD iifname " + networkInterface + " counter accept ; "
  276. postUp += "nft add rule ip filter FORWARD oifname " + networkInterface + " counter accept ; "
  277. postUp += "nft add table nat ; "
  278. postUp += "nft add chain nat postrouting ; "
  279. postUp += "nft add rule ip nat postrouting oifname " + networkInterface + " counter masquerade"
  280. // doesn't remove potentially empty tables or chains
  281. postDown := "nft flush table filter ; "
  282. postDown += "nft flush table nat ; "
  283. return postUp, postDown
  284. }
  285. // firewallNFTCommandsCreateEgress - used to centralize firewall command maintenance for creating an egress gateway using the nftables firewall.
  286. func firewallNFTCommandsCreateEgress(networkInterface string, gatewayInterface string, gatewayranges []string, egressNatEnabled string, ipv4, ipv6 bool) (string, string) {
  287. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  288. postUp := ""
  289. postDown := ""
  290. if ipv4 {
  291. postUp += "nft add table ip filter ; "
  292. postUp += "nft add chain ip filter forward ; "
  293. postUp += "nft add rule filter forward ct state related,established accept ; "
  294. postUp += "nft add rule ip filter forward iifname " + networkInterface + " accept ; "
  295. postUp += "nft add rule ip filter forward oifname " + networkInterface + " accept ; "
  296. postUp += "nft add table nat ; "
  297. postUp += "nft 'add chain ip nat prerouting { type nat hook prerouting priority 0 ;}' ; "
  298. postUp += "nft 'add chain ip nat postrouting { type nat hook postrouting priority 0 ;}' ; "
  299. for _, networkCIDR := range gatewayranges {
  300. postUp += "nft add rule nat postrouting iifname " + networkInterface + " oifname " + gatewayInterface + " ip saddr " + networkCIDR + " masquerade ; "
  301. }
  302. postDown += "nft flush table filter ; "
  303. if egressNatEnabled == "yes" {
  304. postUp += "nft add table nat ; "
  305. postUp += "nft add chain nat postrouting ; "
  306. postUp += "nft add rule ip nat postrouting oifname " + gatewayInterface + " counter masquerade ; "
  307. postDown += "nft flush table nat ; "
  308. }
  309. }
  310. if ipv6 {
  311. postUp += "nft add table ip6 filter ; "
  312. postUp += "nft add chain ip6 filter forward ; "
  313. postUp += "nft add rule ip6 filter forward ct state related,established accept ; "
  314. postUp += "nft add rule ip6 filter forward iifname " + networkInterface + " accept ; "
  315. postUp += "nft add rule ip6 filter forward oifname " + networkInterface + " accept ; "
  316. postDown += "nft flush table ip6 filter ; "
  317. if egressNatEnabled == "yes" {
  318. postUp += "nft add table ip6 nat ; "
  319. postUp += "nft 'add chain ip6 nat prerouting { type nat hook prerouting priority 0 ;}' ; "
  320. postUp += "nft 'add chain ip6 nat postrouting { type nat hook postrouting priority 0 ;}' ; "
  321. postUp += "nft add rule ip6 nat postrouting oifname " + gatewayInterface + " masquerade ; "
  322. postDown += "nft flush table ip6 nat ; "
  323. }
  324. }
  325. return postUp, postDown
  326. }
  327. // firewallIPTablesCommandsCreateIngress - used to centralize firewall command maintenance for creating an ingress gateway using the iptables firewall.
  328. func firewallIPTablesCommandsCreateIngress(networkInterface string, ipv4, ipv6 bool) (string, string) {
  329. postUp := ""
  330. postDown := ""
  331. if ipv4 {
  332. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  333. postUp += "iptables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  334. postUp += "iptables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  335. postUp += "iptables -t nat -A POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  336. // doesn't remove potentially empty tables or chains
  337. postDown += "iptables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  338. postDown += "iptables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  339. postDown += "iptables -t nat -D POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  340. }
  341. if ipv6 {
  342. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  343. postUp += "ip6tables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  344. postUp += "ip6tables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  345. postUp += "ip6tables -t nat -A POSTROUTING -o " + networkInterface + " -j MASQUERADE"
  346. // doesn't remove potentially empty tables or chains
  347. postDown += "ip6tables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  348. postDown += "ip6tables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  349. postDown += "ip6tables -t nat -D POSTROUTING -o " + networkInterface + " -j MASQUERADE"
  350. }
  351. return postUp, postDown
  352. }
  353. // firewallIPTablesCommandsCreateEgress - used to centralize firewall command maintenance for creating an egress gateway using the iptables firewall.
  354. func firewallIPTablesCommandsCreateEgress(networkInterface string, gatewayInterface string, egressNatEnabled string, ipv4, ipv6 bool) (string, string) {
  355. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  356. postUp := ""
  357. postDown := ""
  358. if ipv4 {
  359. postUp += "iptables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  360. postUp += "iptables -A FORWARD -o " + networkInterface + " -j ACCEPT"
  361. postDown += "iptables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  362. postDown += "iptables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  363. if egressNatEnabled == "yes" {
  364. postUp += " ; iptables -t nat -A POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  365. postDown += " ; iptables -t nat -D POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  366. }
  367. }
  368. if ipv6 {
  369. postUp += "ip6tables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  370. postUp += "ip6tables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  371. postDown += "ip6tables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  372. postDown += "ip6tables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  373. if egressNatEnabled == "yes" {
  374. postUp += " ; ip6tables -t nat -A postrouting -o " + gatewayInterface + " -j masquerade"
  375. postDown += " ; ip6tables -t nat -D postrouting -o " + gatewayInterface + " -j masquerade"
  376. }
  377. }
  378. return postUp, postDown
  379. }