gateway.go 16 KB

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