peers.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package logic
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/logic/acls"
  12. "github.com/gravitl/netmaker/logic/acls/nodeacls"
  13. "github.com/gravitl/netmaker/models"
  14. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  15. )
  16. // GetHubPeer - in HubAndSpoke networks, if not the hub, return the hub
  17. /*
  18. func GetHubPeer(networkName string) []models.Node {
  19. var hubpeer = make([]models.Node, 0)
  20. servernodes, err := GetNetworkNodes(networkName)
  21. if err != nil {
  22. return hubpeer
  23. }
  24. for i := range servernodes {
  25. if servernodes[i].IsHub == "yes" {
  26. return []models.Node{servernodes[i]}
  27. }
  28. }
  29. return hubpeer
  30. }
  31. */
  32. // GetNodePeers - fetches peers for a given node
  33. func GetNodePeers(networkName, nodeid string, excludeRelayed bool, isP2S bool) ([]models.Node, error) {
  34. var peers []models.Node
  35. var networkNodes, egressNetworkNodes, err = getNetworkEgressAndNodes(networkName)
  36. if err != nil {
  37. return peers, nil
  38. }
  39. udppeers, errN := database.GetPeers(networkName)
  40. if errN != nil {
  41. logger.Log(2, errN.Error())
  42. }
  43. currentNetworkACLs, aclErr := nodeacls.FetchAllACLs(nodeacls.NetworkID(networkName))
  44. if aclErr != nil {
  45. return peers, aclErr
  46. }
  47. for _, node := range networkNodes {
  48. if !currentNetworkACLs.IsAllowed(acls.AclID(nodeid), acls.AclID(node.ID)) {
  49. continue
  50. }
  51. var peer = models.Node{}
  52. if node.IsEgressGateway == "yes" { // handle egress stuff
  53. peer.EgressGatewayRanges = node.EgressGatewayRanges
  54. peer.IsEgressGateway = node.IsEgressGateway
  55. }
  56. peer.IsIngressGateway = node.IsIngressGateway
  57. isDualStack := node.IsDualStack == "yes"
  58. allow := node.IsRelayed != "yes" || !excludeRelayed
  59. if node.Network == networkName && node.IsPending != "yes" && allow {
  60. peer = setPeerInfo(&node)
  61. if node.UDPHolePunch == "yes" && errN == nil && CheckEndpoint(udppeers[node.PublicKey]) {
  62. endpointstring := udppeers[node.PublicKey]
  63. endpointarr := strings.Split(endpointstring, ":")
  64. if len(endpointarr) == 2 {
  65. port, err := strconv.Atoi(endpointarr[1])
  66. if err == nil {
  67. // peer.Endpoint = endpointarr[0]
  68. peer.ListenPort = int32(port)
  69. }
  70. }
  71. }
  72. // if udp hole punching is on, but port is still set to default (e.g. 51821), use the LocalListenPort
  73. if node.UDPHolePunch == "yes" && node.IsStatic != "yes" && peer.ListenPort == node.ListenPort {
  74. peer.ListenPort = node.LocalListenPort
  75. }
  76. if node.IsRelay == "yes" {
  77. network, err := GetNetwork(networkName)
  78. if err == nil {
  79. peer.AllowedIPs = append(peer.AllowedIPs, network.AddressRange)
  80. } else {
  81. peer.AllowedIPs = append(peer.AllowedIPs, node.RelayAddrs...)
  82. }
  83. for _, egressNode := range egressNetworkNodes {
  84. if egressNode.IsRelayed == "yes" && StringSliceContains(node.RelayAddrs, egressNode.Address) {
  85. peer.AllowedIPs = append(peer.AllowedIPs, egressNode.EgressGatewayRanges...)
  86. }
  87. }
  88. }
  89. if peer.IsIngressGateway == "yes" { // handle ingress stuff
  90. if currentExtClients, err := GetExtPeersList(&node); err == nil {
  91. for i := range currentExtClients {
  92. peer.AllowedIPs = append(peer.AllowedIPs, currentExtClients[i].Address)
  93. if isDualStack {
  94. peer.AllowedIPs = append(peer.AllowedIPs, currentExtClients[i].Address6)
  95. }
  96. }
  97. }
  98. }
  99. if (!isP2S || peer.IsHub == "yes") && currentNetworkACLs.IsAllowed(acls.AclID(nodeid), acls.AclID(node.ID)) {
  100. peers = append(peers, peer)
  101. }
  102. }
  103. }
  104. return peers, err
  105. }
  106. // GetPeersList - gets the peers of a given network
  107. func GetPeersList(refnode *models.Node) ([]models.Node, error) {
  108. var peers []models.Node
  109. var err error
  110. var isP2S bool
  111. var networkName = refnode.Network
  112. var excludeRelayed = refnode.IsRelay != "yes"
  113. var relayedNodeAddr string
  114. if refnode.IsRelayed == "yes" {
  115. relayedNodeAddr = refnode.Address
  116. }
  117. network, err := GetNetwork(networkName)
  118. if err != nil {
  119. return peers, err
  120. } else if network.IsPointToSite == "yes" && refnode.IsHub != "yes" {
  121. isP2S = true
  122. }
  123. if relayedNodeAddr == "" {
  124. peers, err = GetNodePeers(networkName, refnode.ID, excludeRelayed, isP2S)
  125. } else {
  126. var relayNode models.Node
  127. relayNode, err = GetNodeRelay(networkName, relayedNodeAddr)
  128. if relayNode.Address != "" {
  129. var peerNode = setPeerInfo(&relayNode)
  130. network, err := GetNetwork(networkName)
  131. if err == nil {
  132. peerNode.AllowedIPs = append(peerNode.AllowedIPs, network.AddressRange)
  133. var _, egressNetworkNodes, err = getNetworkEgressAndNodes(networkName)
  134. if err == nil {
  135. for _, egress := range egressNetworkNodes {
  136. if egress.Address != relayedNodeAddr {
  137. peerNode.AllowedIPs = append(peerNode.AllowedIPs, egress.EgressGatewayRanges...)
  138. }
  139. }
  140. }
  141. } else {
  142. peerNode.AllowedIPs = append(peerNode.AllowedIPs, peerNode.RelayAddrs...)
  143. }
  144. nodepeers, err := GetNodePeers(networkName, refnode.ID, false, isP2S)
  145. if err == nil && peerNode.UDPHolePunch == "yes" {
  146. for _, nodepeer := range nodepeers {
  147. if nodepeer.Address == peerNode.Address {
  148. // peerNode.Endpoint = nodepeer.Endpoint
  149. peerNode.ListenPort = nodepeer.ListenPort
  150. }
  151. }
  152. }
  153. if !isP2S || peerNode.IsHub == "yes" {
  154. peers = append(peers, peerNode)
  155. }
  156. }
  157. }
  158. return peers, err
  159. }
  160. // GetPeerUpdate - gets a wireguard peer config for each peer of a node
  161. func GetPeerUpdate(node *models.Node) (models.PeerUpdate, error) {
  162. var peerUpdate models.PeerUpdate
  163. var peers []wgtypes.PeerConfig
  164. var serverNodeAddresses = []models.ServerAddr{}
  165. currentPeers, err := GetPeers(node)
  166. if err != nil {
  167. return models.PeerUpdate{}, err
  168. }
  169. // begin translating netclient logic
  170. /*
  171. Go through netclient code and put below
  172. */
  173. // #1 Set Keepalive values: set_keepalive
  174. // #2 Set local address: set_local - could be a LOT BETTER and fix some bugs with additional logic
  175. // #3 Set allowedips: set_allowedips
  176. var dns string
  177. for _, peer := range currentPeers {
  178. if peer.ID == node.ID {
  179. //skip yourself
  180. continue
  181. }
  182. dns = dns + fmt.Sprintf("%s %s.%s\n", peer.Address, peer.Name, peer.Network)
  183. pubkey, err := wgtypes.ParseKey(peer.PublicKey)
  184. if err != nil {
  185. return models.PeerUpdate{}, err
  186. }
  187. if node.Endpoint == peer.Endpoint {
  188. //peer is on same network
  189. // set_local
  190. if node.LocalAddress != peer.LocalAddress && peer.LocalAddress != "" {
  191. peer.Endpoint = peer.LocalAddress
  192. } else {
  193. continue
  194. }
  195. if node.LocalListenPort != peer.LocalListenPort && peer.LocalListenPort != 0 {
  196. peer.ListenPort = peer.LocalListenPort
  197. } else {
  198. continue
  199. }
  200. }
  201. endpoint := peer.Endpoint + ":" + strconv.FormatInt(int64(peer.ListenPort), 10)
  202. address, err := net.ResolveUDPAddr("udp", endpoint)
  203. if err != nil {
  204. return models.PeerUpdate{}, err
  205. }
  206. // set_allowedips
  207. allowedips := GetAllowedIPs(node, &peer)
  208. var keepalive time.Duration
  209. if node.PersistentKeepalive != 0 {
  210. // set_keepalive
  211. keepalive, _ = time.ParseDuration(strconv.FormatInt(int64(node.PersistentKeepalive), 10) + "s")
  212. }
  213. var peerData = wgtypes.PeerConfig{
  214. PublicKey: pubkey,
  215. Endpoint: address,
  216. ReplaceAllowedIPs: true,
  217. AllowedIPs: allowedips,
  218. PersistentKeepaliveInterval: &keepalive,
  219. }
  220. peers = append(peers, peerData)
  221. if peer.IsServer == "yes" {
  222. serverNodeAddresses = append(serverNodeAddresses, models.ServerAddr{IsLeader: IsLeader(&peer), Address: peer.Address})
  223. }
  224. }
  225. if node.IsIngressGateway == "yes" {
  226. extPeers, err := getExtPeers(node)
  227. if err == nil {
  228. peers = append(peers, extPeers...)
  229. } else {
  230. log.Println("ERROR RETRIEVING EXTERNAL PEERS", err)
  231. }
  232. }
  233. peerUpdate.Network = node.Network
  234. peerUpdate.Peers = peers
  235. peerUpdate.ServerAddrs = serverNodeAddresses
  236. /*
  237. End translation of netclient code
  238. */
  239. if customDNSEntries, err := GetCustomDNS(peerUpdate.Network); err == nil {
  240. for _, entry := range customDNSEntries {
  241. // TODO - filter entries based on ACLs / given peers vs nodes in network
  242. dns = dns + fmt.Sprintf("%s %s.%s\n", entry.Address, entry.Name, entry.Network)
  243. }
  244. }
  245. peerUpdate.DNS = dns
  246. return peerUpdate, nil
  247. }
  248. func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, error) {
  249. var peers []wgtypes.PeerConfig
  250. extPeers, err := GetExtPeersList(node)
  251. if err != nil {
  252. return peers, err
  253. }
  254. for _, extPeer := range extPeers {
  255. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  256. if err != nil {
  257. logger.Log(1, "error parsing ext pub key:", err.Error())
  258. continue
  259. }
  260. if node.PublicKey == extPeer.PublicKey {
  261. continue
  262. }
  263. var peer wgtypes.PeerConfig
  264. var peeraddr = net.IPNet{
  265. IP: net.ParseIP(extPeer.Address),
  266. Mask: net.CIDRMask(32, 32),
  267. }
  268. var allowedips []net.IPNet
  269. allowedips = append(allowedips, peeraddr)
  270. if extPeer.Address6 != "" {
  271. var addr6 = net.IPNet{
  272. IP: net.ParseIP(extPeer.Address6),
  273. Mask: net.CIDRMask(128, 128),
  274. }
  275. allowedips = append(allowedips, addr6)
  276. }
  277. peer = wgtypes.PeerConfig{
  278. PublicKey: pubkey,
  279. ReplaceAllowedIPs: true,
  280. AllowedIPs: allowedips,
  281. }
  282. peers = append(peers, peer)
  283. }
  284. return peers, nil
  285. }
  286. // GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
  287. func GetAllowedIPs(node, peer *models.Node) []net.IPNet {
  288. var allowedips []net.IPNet
  289. var peeraddr = net.IPNet{
  290. IP: net.ParseIP(peer.Address),
  291. Mask: net.CIDRMask(32, 32),
  292. }
  293. dualstack := false
  294. allowedips = append(allowedips, peeraddr)
  295. // handle manually set peers
  296. for _, allowedIp := range peer.AllowedIPs {
  297. if _, ipnet, err := net.ParseCIDR(allowedIp); err == nil {
  298. nodeEndpointArr := strings.Split(node.Endpoint, ":")
  299. if !ipnet.Contains(net.IP(nodeEndpointArr[0])) && ipnet.IP.String() != peer.Address { // don't need to add an allowed ip that already exists..
  300. allowedips = append(allowedips, *ipnet)
  301. }
  302. } else if appendip := net.ParseIP(allowedIp); appendip != nil && allowedIp != peer.Address {
  303. ipnet := net.IPNet{
  304. IP: net.ParseIP(allowedIp),
  305. Mask: net.CIDRMask(32, 32),
  306. }
  307. allowedips = append(allowedips, ipnet)
  308. }
  309. }
  310. // handle egress gateway peers
  311. if peer.IsEgressGateway == "yes" {
  312. //hasGateway = true
  313. ranges := peer.EgressGatewayRanges
  314. for _, iprange := range ranges { // go through each cidr for egress gateway
  315. _, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
  316. if err != nil {
  317. logger.Log(1, "could not parse gateway IP range. Not adding ", iprange)
  318. continue // if can't parse CIDR
  319. }
  320. nodeEndpointArr := strings.Split(peer.Endpoint, ":") // getting the public ip of node
  321. if ipnet.Contains(net.ParseIP(nodeEndpointArr[0])) { // ensuring egress gateway range does not contain endpoint of node
  322. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.Endpoint, ", omitting")
  323. continue // skip adding egress range if overlaps with node's ip
  324. }
  325. // TODO: Could put in a lot of great logic to avoid conflicts / bad routes
  326. if ipnet.Contains(net.ParseIP(node.LocalAddress)) { // ensuring egress gateway range does not contain public ip of node
  327. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.LocalAddress, ", omitting")
  328. continue // skip adding egress range if overlaps with node's local ip
  329. }
  330. if err != nil {
  331. log.Println("ERROR ENCOUNTERED SETTING GATEWAY")
  332. } else {
  333. allowedips = append(allowedips, *ipnet)
  334. }
  335. }
  336. }
  337. if peer.Address6 != "" && dualstack {
  338. var addr6 = net.IPNet{
  339. IP: net.ParseIP(peer.Address6),
  340. Mask: net.CIDRMask(128, 128),
  341. }
  342. allowedips = append(allowedips, addr6)
  343. }
  344. return allowedips
  345. }