gateway.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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) (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. data, err := json.Marshal(&node)
  210. if err != nil {
  211. return models.Node{}, err
  212. }
  213. err = database.Insert(node.ID, string(data), database.NODES_TABLE_NAME)
  214. if err != nil {
  215. return models.Node{}, err
  216. }
  217. err = SetNetworkNodesLastModified(netid)
  218. return node, err
  219. }
  220. // DeleteIngressGateway - deletes an ingress gateway
  221. func DeleteIngressGateway(networkName string, nodeid string) (models.Node, error) {
  222. node, err := GetNodeByID(nodeid)
  223. if err != nil {
  224. return models.Node{}, err
  225. }
  226. network, err := GetParentNetwork(networkName)
  227. if err != nil {
  228. return models.Node{}, err
  229. }
  230. // delete ext clients belonging to ingress gateway
  231. if err = DeleteGatewayExtClients(node.ID, networkName); err != nil {
  232. return models.Node{}, err
  233. }
  234. logger.Log(3, "deleting ingress gateway")
  235. node.UDPHolePunch = network.DefaultUDPHolePunch
  236. node.LastModified = time.Now().Unix()
  237. node.IsIngressGateway = "no"
  238. node.IngressGatewayRange = ""
  239. // default to removing postup and postdown
  240. node.PostUp = ""
  241. node.PostDown = ""
  242. logger.Log(3, "deleting ingress gateway firewall in use is '", node.FirewallInUse, "' and isEgressGateway is", node.IsEgressGateway)
  243. if node.EgressGatewayRequest.NodeID != "" {
  244. _, err := CreateEgressGateway(node.EgressGatewayRequest)
  245. if err != nil {
  246. logger.Log(0, fmt.Sprintf("failed to create egress gateway on node [%s] on network [%s]: %v",
  247. node.EgressGatewayRequest.NodeID, node.EgressGatewayRequest.NetID, err))
  248. }
  249. }
  250. data, err := json.Marshal(&node)
  251. if err != nil {
  252. return models.Node{}, err
  253. }
  254. err = database.Insert(node.ID, string(data), database.NODES_TABLE_NAME)
  255. if err != nil {
  256. return models.Node{}, err
  257. }
  258. err = SetNetworkNodesLastModified(networkName)
  259. return node, err
  260. }
  261. // DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network
  262. func DeleteGatewayExtClients(gatewayID string, networkName string) error {
  263. currentExtClients, err := GetNetworkExtClients(networkName)
  264. if err != nil && !database.IsEmptyRecord(err) {
  265. return err
  266. }
  267. for _, extClient := range currentExtClients {
  268. if extClient.IngressGatewayID == gatewayID {
  269. if err = DeleteExtClient(networkName, extClient.ClientID); err != nil {
  270. logger.Log(1, "failed to remove ext client", extClient.ClientID)
  271. continue
  272. }
  273. }
  274. }
  275. return nil
  276. }
  277. // firewallNFTCommandsCreateIngress - used to centralize firewall command maintenance for creating an ingress gateway using the nftables firewall.
  278. func firewallNFTCommandsCreateIngress(networkInterface string) (string, string) {
  279. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  280. postUp := "nft add table ip filter ; "
  281. postUp += "nft add chain ip filter FORWARD ; "
  282. postUp += "nft add rule ip filter FORWARD iifname " + networkInterface + " counter accept ; "
  283. postUp += "nft add rule ip filter FORWARD oifname " + networkInterface + " counter accept ; "
  284. postUp += "nft add table nat ; "
  285. postUp += "nft add chain nat postrouting ; "
  286. postUp += "nft add rule ip nat postrouting oifname " + networkInterface + " counter masquerade"
  287. // doesn't remove potentially empty tables or chains
  288. postDown := "nft flush table filter ; "
  289. postDown += "nft flush table nat ; "
  290. return postUp, postDown
  291. }
  292. // firewallNFTCommandsCreateEgress - used to centralize firewall command maintenance for creating an egress gateway using the nftables firewall.
  293. func firewallNFTCommandsCreateEgress(networkInterface string, gatewayInterface string, gatewayranges []string, egressNatEnabled string, ipv4, ipv6 bool) (string, string) {
  294. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  295. postUp := ""
  296. postDown := ""
  297. if ipv4 {
  298. postUp += "nft add table ip filter ; "
  299. postUp += "nft add chain ip filter forward ; "
  300. postUp += "nft add rule filter forward ct state related,established accept ; "
  301. postUp += "nft add rule ip filter forward iifname " + networkInterface + " accept ; "
  302. postUp += "nft add rule ip filter forward oifname " + networkInterface + " accept ; "
  303. postUp += "nft add table nat ; "
  304. postUp += "nft 'add chain ip nat prerouting { type nat hook prerouting priority 0 ;}' ; "
  305. postUp += "nft 'add chain ip nat postrouting { type nat hook postrouting priority 0 ;}' ; "
  306. postDown += "nft flush table filter ; "
  307. if egressNatEnabled == "yes" {
  308. postUp += "nft add table nat ; "
  309. postUp += "nft add chain nat postrouting ; "
  310. postUp += "nft add rule ip nat postrouting oifname " + gatewayInterface + " counter masquerade ; "
  311. postDown += "nft flush table nat ; "
  312. }
  313. }
  314. if ipv6 {
  315. postUp += "nft add table ip6 filter ; "
  316. postUp += "nft add chain ip6 filter forward ; "
  317. postUp += "nft add rule ip6 filter forward ct state related,established accept ; "
  318. postUp += "nft add rule ip6 filter forward iifname " + networkInterface + " accept ; "
  319. postUp += "nft add rule ip6 filter forward oifname " + networkInterface + " accept ; "
  320. postDown += "nft flush table ip6 filter ; "
  321. if egressNatEnabled == "yes" {
  322. postUp += "nft add table ip6 nat ; "
  323. postUp += "nft 'add chain ip6 nat prerouting { type nat hook prerouting priority 0 ;}' ; "
  324. postUp += "nft 'add chain ip6 nat postrouting { type nat hook postrouting priority 0 ;}' ; "
  325. postUp += "nft add rule ip6 nat postrouting oifname " + gatewayInterface + " masquerade ; "
  326. postDown += "nft flush table ip6 nat ; "
  327. }
  328. }
  329. return postUp, postDown
  330. }
  331. // firewallIPTablesCommandsCreateIngress - used to centralize firewall command maintenance for creating an ingress gateway using the iptables firewall.
  332. func firewallIPTablesCommandsCreateIngress(networkInterface string, ipv4, ipv6 bool) (string, string) {
  333. postUp := ""
  334. postDown := ""
  335. if ipv4 {
  336. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  337. postUp += "iptables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  338. postUp += "iptables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  339. postUp += "iptables -t nat -A POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  340. // doesn't remove potentially empty tables or chains
  341. postDown += "iptables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  342. postDown += "iptables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  343. postDown += "iptables -t nat -D POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  344. }
  345. if ipv6 {
  346. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  347. postUp += "ip6tables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  348. postUp += "ip6tables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  349. postUp += "ip6tables -t nat -A POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  350. // doesn't remove potentially empty tables or chains
  351. postDown += "ip6tables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  352. postDown += "ip6tables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  353. postDown += "ip6tables -t nat -D POSTROUTING -o " + networkInterface + " -j MASQUERADE ; "
  354. }
  355. return postUp, postDown
  356. }
  357. // firewallIPTablesCommandsCreateEgress - used to centralize firewall command maintenance for creating an egress gateway using the iptables firewall.
  358. func firewallIPTablesCommandsCreateEgress(networkInterface string, gatewayInterface string, egressNatEnabled string, ipv4, ipv6 bool) (string, string) {
  359. // spacing around ; is important for later parsing of postup/postdown in wireguard/common.go
  360. postUp := ""
  361. postDown := ""
  362. if ipv4 {
  363. postUp += "iptables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  364. postUp += "iptables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  365. postDown += "iptables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  366. postDown += "iptables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  367. if egressNatEnabled == "yes" {
  368. postUp += "iptables -t nat -A POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  369. postDown += "iptables -t nat -D POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  370. }
  371. }
  372. if ipv6 {
  373. postUp += "ip6tables -A FORWARD -i " + networkInterface + " -j ACCEPT ; "
  374. postUp += "ip6tables -A FORWARD -o " + networkInterface + " -j ACCEPT ; "
  375. postDown += "ip6tables -D FORWARD -i " + networkInterface + " -j ACCEPT ; "
  376. postDown += "ip6tables -D FORWARD -o " + networkInterface + " -j ACCEPT ; "
  377. if egressNatEnabled == "yes" {
  378. postUp += "ip6tables -t nat -A POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  379. postDown += "ip6tables -t nat -D POSTROUTING -o " + gatewayInterface + " -j MASQUERADE ; "
  380. }
  381. }
  382. return postUp, postDown
  383. }