peers.go 9.7 KB

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