peers.go 10 KB

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