peers.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. if !isP2S || peerNode.IsHub == "yes" {
  127. peers = append(peers, peerNode)
  128. }
  129. }
  130. }
  131. return peers, err
  132. }
  133. // GetPeerUpdate - gets a wireguard peer config for each peer of a node
  134. func GetPeerUpdate(node *models.Node) (models.PeerUpdate, error) {
  135. var peerUpdate models.PeerUpdate
  136. var peers []wgtypes.PeerConfig
  137. var serverNodeAddresses = []models.ServerAddr{}
  138. currentPeers, err := GetPeers(node)
  139. if err != nil {
  140. return models.PeerUpdate{}, err
  141. }
  142. // begin translating netclient logic
  143. /*
  144. Go through netclient code and put below
  145. */
  146. // #1 Set Keepalive values: set_keepalive
  147. // #2 Set local address: set_local - could be a LOT BETTER and fix some bugs with additional logic
  148. // #3 Set allowedips: set_allowedips
  149. for _, peer := range currentPeers {
  150. if peer.ID == node.ID {
  151. //skip yourself
  152. continue
  153. }
  154. pubkey, err := wgtypes.ParseKey(peer.PublicKey)
  155. if err != nil {
  156. return models.PeerUpdate{}, err
  157. }
  158. if node.Endpoint == peer.Endpoint {
  159. //peer is on same network
  160. // set_local
  161. if node.LocalAddress != peer.LocalAddress && peer.LocalAddress != "" {
  162. peer.Endpoint = peer.LocalAddress
  163. } else {
  164. continue
  165. }
  166. }
  167. endpoint := peer.Endpoint + ":" + strconv.FormatInt(int64(peer.ListenPort), 10)
  168. address, err := net.ResolveUDPAddr("udp", endpoint)
  169. if err != nil {
  170. return models.PeerUpdate{}, err
  171. }
  172. // set_allowedips
  173. allowedips := GetAllowedIPs(node, &peer)
  174. var keepalive time.Duration
  175. if node.PersistentKeepalive != 0 {
  176. // set_keepalive
  177. keepalive, _ = time.ParseDuration(strconv.FormatInt(int64(node.PersistentKeepalive), 10) + "s")
  178. }
  179. var peerData = wgtypes.PeerConfig{
  180. PublicKey: pubkey,
  181. Endpoint: address,
  182. ReplaceAllowedIPs: true,
  183. AllowedIPs: allowedips,
  184. PersistentKeepaliveInterval: &keepalive,
  185. }
  186. peers = append(peers, peerData)
  187. if peer.IsServer == "yes" {
  188. serverNodeAddresses = append(serverNodeAddresses, models.ServerAddr{IsLeader: IsLeader(&peer), Address: peer.Address})
  189. }
  190. }
  191. if node.IsIngressGateway == "yes" {
  192. extPeers, err := getExtPeers(node)
  193. if err == nil {
  194. peers = append(peers, extPeers...)
  195. } else {
  196. log.Println("ERROR RETRIEVING EXTERNAL PEERS", err)
  197. }
  198. }
  199. peerUpdate.Network = node.Network
  200. peerUpdate.Peers = peers
  201. peerUpdate.ServerAddrs = serverNodeAddresses
  202. /*
  203. End translation of netclient code
  204. */
  205. return peerUpdate, nil
  206. }
  207. func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, error) {
  208. var peers []wgtypes.PeerConfig
  209. extPeers, err := GetExtPeersList(node)
  210. if err != nil {
  211. return peers, err
  212. }
  213. for _, extPeer := range extPeers {
  214. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  215. if err != nil {
  216. logger.Log(1, "error parsing ext pub key:", err.Error())
  217. continue
  218. }
  219. if node.PublicKey == extPeer.PublicKey {
  220. continue
  221. }
  222. var peer wgtypes.PeerConfig
  223. var peeraddr = net.IPNet{
  224. IP: net.ParseIP(extPeer.Address),
  225. Mask: net.CIDRMask(32, 32),
  226. }
  227. var allowedips []net.IPNet
  228. allowedips = append(allowedips, peeraddr)
  229. if extPeer.Address6 != "" {
  230. var addr6 = net.IPNet{
  231. IP: net.ParseIP(extPeer.Address6),
  232. Mask: net.CIDRMask(128, 128),
  233. }
  234. allowedips = append(allowedips, addr6)
  235. }
  236. peer = wgtypes.PeerConfig{
  237. PublicKey: pubkey,
  238. ReplaceAllowedIPs: true,
  239. AllowedIPs: allowedips,
  240. }
  241. peers = append(peers, peer)
  242. }
  243. return peers, nil
  244. }
  245. // GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
  246. func GetAllowedIPs(node, peer *models.Node) []net.IPNet {
  247. var allowedips []net.IPNet
  248. var peeraddr = net.IPNet{
  249. IP: net.ParseIP(peer.Address),
  250. Mask: net.CIDRMask(32, 32),
  251. }
  252. dualstack := false
  253. allowedips = append(allowedips, peeraddr)
  254. // handle manually set peers
  255. for _, allowedIp := range peer.AllowedIPs {
  256. if _, ipnet, err := net.ParseCIDR(allowedIp); err == nil {
  257. nodeEndpointArr := strings.Split(node.Endpoint, ":")
  258. if !ipnet.Contains(net.IP(nodeEndpointArr[0])) && ipnet.IP.String() != peer.Address { // don't need to add an allowed ip that already exists..
  259. allowedips = append(allowedips, *ipnet)
  260. }
  261. } else if appendip := net.ParseIP(allowedIp); appendip != nil && allowedIp != peer.Address {
  262. ipnet := net.IPNet{
  263. IP: net.ParseIP(allowedIp),
  264. Mask: net.CIDRMask(32, 32),
  265. }
  266. allowedips = append(allowedips, ipnet)
  267. }
  268. }
  269. // handle egress gateway peers
  270. if peer.IsEgressGateway == "yes" {
  271. //hasGateway = true
  272. ranges := peer.EgressGatewayRanges
  273. for _, iprange := range ranges { // go through each cidr for egress gateway
  274. _, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
  275. if err != nil {
  276. ncutils.PrintLog("could not parse gateway IP range. Not adding "+iprange, 1)
  277. continue // if can't parse CIDR
  278. }
  279. nodeEndpointArr := strings.Split(peer.Endpoint, ":") // getting the public ip of node
  280. if ipnet.Contains(net.ParseIP(nodeEndpointArr[0])) { // ensuring egress gateway range does not contain endpoint of node
  281. ncutils.PrintLog("egress IP range of "+iprange+" overlaps with "+node.Endpoint+", omitting", 2)
  282. continue // skip adding egress range if overlaps with node's ip
  283. }
  284. // TODO: Could put in a lot of great logic to avoid conflicts / bad routes
  285. if ipnet.Contains(net.ParseIP(node.LocalAddress)) { // ensuring egress gateway range does not contain public ip of node
  286. ncutils.PrintLog("egress IP range of "+iprange+" overlaps with "+node.LocalAddress+", omitting", 2)
  287. continue // skip adding egress range if overlaps with node's local ip
  288. }
  289. if err != nil {
  290. log.Println("ERROR ENCOUNTERED SETTING GATEWAY")
  291. } else {
  292. allowedips = append(allowedips, *ipnet)
  293. }
  294. }
  295. }
  296. if peer.Address6 != "" && dualstack {
  297. var addr6 = net.IPNet{
  298. IP: net.ParseIP(peer.Address6),
  299. Mask: net.CIDRMask(128, 128),
  300. }
  301. allowedips = append(allowedips, addr6)
  302. }
  303. return allowedips
  304. }