peers.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. package logic
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/c-robinson/iplib"
  12. proxy_models "github.com/gravitl/netclient/nmproxy/models"
  13. "github.com/gravitl/netmaker/database"
  14. "github.com/gravitl/netmaker/logger"
  15. "github.com/gravitl/netmaker/logic/acls/nodeacls"
  16. "github.com/gravitl/netmaker/models"
  17. "github.com/gravitl/netmaker/netclient/ncutils"
  18. "github.com/gravitl/netmaker/servercfg"
  19. "golang.org/x/exp/slices"
  20. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  21. )
  22. // GetPeersforProxy calculates the peers for a proxy
  23. // TODO ==========================
  24. // TODO ==========================
  25. // TODO ==========================
  26. // TODO ==========================
  27. // TODO ==========================
  28. // revisit this logic with new host/node models.
  29. func GetPeersForProxy(node *models.Node, onlyPeers bool) (proxy_models.ProxyManagerPayload, error) {
  30. proxyPayload := proxy_models.ProxyManagerPayload{}
  31. var peers []wgtypes.PeerConfig
  32. peerConfMap := make(map[string]proxy_models.PeerConf)
  33. var err error
  34. currentPeers, err := GetNetworkNodes(node.Network)
  35. if err != nil {
  36. return proxyPayload, err
  37. }
  38. if !onlyPeers {
  39. if node.IsRelayed {
  40. relayNode := FindRelay(node)
  41. relayHost, err := GetHost(relayNode.HostID.String())
  42. if err != nil {
  43. return proxyPayload, err
  44. }
  45. if relayNode != nil {
  46. host, err := GetHost(relayNode.HostID.String())
  47. if err != nil {
  48. logger.Log(0, "error retrieving host for relay node", relayNode.HostID.String(), err.Error())
  49. }
  50. relayEndpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayHost.EndpointIP, host.LocalListenPort))
  51. if err != nil {
  52. logger.Log(1, "failed to resolve relay node endpoint: ", err.Error())
  53. }
  54. proxyPayload.IsRelayed = true
  55. proxyPayload.RelayedTo = relayEndpoint
  56. } else {
  57. logger.Log(0, "couldn't find relay node for: ", node.ID.String())
  58. }
  59. }
  60. if node.IsRelay {
  61. host, err := GetHost(node.HostID.String())
  62. if err != nil {
  63. logger.Log(0, "error retrieving host for relay node", node.ID.String(), err.Error())
  64. }
  65. relayedNodes, err := GetRelayedNodes(node)
  66. if err != nil {
  67. logger.Log(1, "failed to relayed nodes: ", node.ID.String(), err.Error())
  68. proxyPayload.IsRelay = false
  69. } else {
  70. relayPeersMap := make(map[string]proxy_models.RelayedConf)
  71. for _, relayedNode := range relayedNodes {
  72. payload, err := GetPeersForProxy(&relayedNode, true)
  73. if err == nil {
  74. relayedHost, err := GetHost(relayedNode.HostID.String())
  75. if err != nil {
  76. logger.Log(0, "error retrieving host for relayNode", relayedNode.ID.String(), err.Error())
  77. }
  78. relayedEndpoint, udpErr := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayedHost.EndpointIP, host.LocalListenPort))
  79. if udpErr == nil {
  80. relayPeersMap[host.PublicKey.String()] = proxy_models.RelayedConf{
  81. RelayedPeerEndpoint: relayedEndpoint,
  82. RelayedPeerPubKey: relayedHost.PublicKey.String(),
  83. Peers: payload.Peers,
  84. }
  85. }
  86. }
  87. }
  88. proxyPayload.IsRelay = true
  89. proxyPayload.RelayedPeerConf = relayPeersMap
  90. }
  91. }
  92. }
  93. for _, peer := range currentPeers {
  94. if peer.ID == node.ID {
  95. //skip yourself
  96. continue
  97. }
  98. host, err := GetHost(peer.HostID.String())
  99. if err != nil {
  100. continue
  101. }
  102. proxyStatus := host.ProxyEnabled
  103. listenPort := host.LocalListenPort
  104. if proxyStatus {
  105. listenPort = host.ProxyListenPort
  106. if listenPort == 0 {
  107. listenPort = proxy_models.NmProxyPort
  108. }
  109. } else if listenPort == 0 {
  110. listenPort = host.ListenPort
  111. }
  112. endpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", host.EndpointIP, listenPort))
  113. if err != nil {
  114. logger.Log(1, "failed to resolve udp addr for node: ", peer.ID.String(), host.EndpointIP.String(), err.Error())
  115. continue
  116. }
  117. allowedips := GetAllowedIPs(node, &peer, nil, false)
  118. var keepalive time.Duration
  119. if node.PersistentKeepalive != 0 {
  120. // set_keepalive
  121. keepalive = node.PersistentKeepalive
  122. }
  123. peers = append(peers, wgtypes.PeerConfig{
  124. PublicKey: host.PublicKey,
  125. Endpoint: endpoint,
  126. AllowedIPs: allowedips,
  127. PersistentKeepaliveInterval: &keepalive,
  128. ReplaceAllowedIPs: true,
  129. })
  130. peerConfMap[host.PublicKey.String()] = proxy_models.PeerConf{
  131. Address: net.ParseIP(peer.PrimaryAddress()),
  132. Proxy: proxyStatus,
  133. PublicListenPort: int32(listenPort),
  134. }
  135. if !onlyPeers && peer.IsRelayed {
  136. relayNode := FindRelay(&peer)
  137. if relayNode != nil {
  138. relayHost, err := GetHost(relayNode.HostID.String())
  139. if err != nil {
  140. logger.Log(0, "error retrieving host for relayNode", relayNode.ID.String(), err.Error())
  141. continue
  142. }
  143. relayTo, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayHost.EndpointIP, relayHost.LocalListenPort))
  144. if err == nil {
  145. peerConfMap[host.PublicKey.String()] = proxy_models.PeerConf{
  146. IsRelayed: true,
  147. RelayedTo: relayTo,
  148. Address: net.ParseIP(peer.PrimaryAddress()),
  149. Proxy: proxyStatus,
  150. PublicListenPort: int32(listenPort),
  151. }
  152. }
  153. }
  154. }
  155. }
  156. if node.IsIngressGateway {
  157. var extPeers []wgtypes.PeerConfig
  158. extPeers, peerConfMap, err = getExtPeersForProxy(node, peerConfMap)
  159. if err == nil {
  160. peers = append(peers, extPeers...)
  161. } else if !database.IsEmptyRecord(err) {
  162. logger.Log(1, "error retrieving external clients:", err.Error())
  163. }
  164. }
  165. proxyPayload.IsIngress = node.IsIngressGateway
  166. addr := node.Address
  167. if addr.String() == "" {
  168. addr = node.Address6
  169. }
  170. proxyPayload.WgAddr = addr.String()
  171. proxyPayload.Peers = peers
  172. proxyPayload.PeerMap = peerConfMap
  173. proxyPayload.Network = node.Network
  174. //proxyPayload.InterfaceName = node.Interface
  175. //hardcode or read from host ??
  176. proxyPayload.InterfaceName = models.WIREGUARD_INTERFACE
  177. return proxyPayload, nil
  178. }
  179. func GetPeerUpdateForHost(host *models.Host) (models.HostPeerUpdate, error) {
  180. hostPeerUpdate := models.HostPeerUpdate{
  181. Network: make(map[string]models.NetworkInfo),
  182. PeerIDs: make(models.HostPeerMap),
  183. ServerVersion: servercfg.GetVersion(),
  184. ServerAddrs: []models.ServerAddr{},
  185. }
  186. log.Println("peer update for host ", host.ID.String())
  187. peerIndexMap := make(map[string]int)
  188. for _, nodeID := range host.Nodes {
  189. node, err := GetNodeByID(nodeID)
  190. if err != nil {
  191. continue
  192. }
  193. if !node.Connected {
  194. continue
  195. }
  196. hostPeerUpdate.Network[node.Network] = models.NetworkInfo{
  197. DNS: getPeerDNS(node.Network),
  198. }
  199. currentPeers, err := GetNetworkNodes(node.Network)
  200. if err != nil {
  201. log.Println("no network nodes")
  202. return models.HostPeerUpdate{}, err
  203. }
  204. for _, peer := range currentPeers {
  205. if peer.ID == node.ID {
  206. log.Println("peer update, skipping self")
  207. //skip yourself
  208. continue
  209. }
  210. var peerConfig wgtypes.PeerConfig
  211. peerHost, err := GetHost(peer.HostID.String())
  212. if err != nil {
  213. log.Println("no peer host", err)
  214. return models.HostPeerUpdate{}, err
  215. }
  216. if !peer.Connected {
  217. log.Println("peer update, skipping unconnected node")
  218. //skip unconnected nodes
  219. continue
  220. }
  221. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(peer.ID.String())) {
  222. log.Println("peer update, skipping node for acl")
  223. //skip if not permitted by acl
  224. continue
  225. }
  226. peerConfig.PublicKey = peerHost.PublicKey
  227. peerConfig.PersistentKeepaliveInterval = &peer.PersistentKeepalive
  228. peerConfig.ReplaceAllowedIPs = true
  229. uselocal := false
  230. if host.EndpointIP.String() == peerHost.EndpointIP.String() {
  231. //peer is on same network
  232. // set to localaddress
  233. uselocal = true
  234. if node.LocalAddress.IP == nil {
  235. // use public endpint
  236. uselocal = false
  237. }
  238. if node.LocalAddress.String() == peer.LocalAddress.String() {
  239. uselocal = false
  240. }
  241. }
  242. peerConfig.Endpoint = &net.UDPAddr{
  243. IP: peerHost.EndpointIP,
  244. Port: peerHost.ListenPort,
  245. }
  246. if !host.ProxyEnabled && peerHost.ProxyEnabled {
  247. peerConfig.Endpoint.Port = peerHost.ProxyListenPort
  248. }
  249. if uselocal {
  250. peerConfig.Endpoint.IP = peer.LocalAddress.IP
  251. }
  252. allowedips := getNodeAllowedIPs(&peer, &node)
  253. if peer.IsIngressGateway {
  254. for _, entry := range peer.IngressGatewayRange {
  255. _, cidr, err := net.ParseCIDR(string(entry))
  256. if err == nil {
  257. allowedips = append(allowedips, *cidr)
  258. }
  259. }
  260. }
  261. if peer.IsRelay {
  262. allowedips = append(allowedips, getRelayAllowedIPs(&node, &peer)...)
  263. }
  264. if peer.IsEgressGateway {
  265. allowedips = append(allowedips, getEgressIPs(&node, &peer)...)
  266. }
  267. peerConfig.AllowedIPs = allowedips
  268. if _, ok := hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()]; !ok {
  269. hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()] = make(map[string]models.IDandAddr)
  270. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, peerConfig)
  271. peerIndexMap[peerHost.PublicKey.String()] = len(hostPeerUpdate.Peers) - 1
  272. hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()][peer.ID.String()] = models.IDandAddr{
  273. ID: peer.ID.String(),
  274. Address: peer.PrimaryAddress(),
  275. Name: peerHost.Name,
  276. Network: peer.Network,
  277. }
  278. } else {
  279. peerAllowedIPs := hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs
  280. peerAllowedIPs = append(peerAllowedIPs, allowedips...)
  281. hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs = peerAllowedIPs
  282. hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()][peer.ID.String()] = models.IDandAddr{
  283. ID: peer.ID.String(),
  284. Address: peer.PrimaryAddress(),
  285. Name: peerHost.Name,
  286. Network: peer.Network,
  287. }
  288. }
  289. }
  290. }
  291. return hostPeerUpdate, nil
  292. }
  293. // GetPeerUpdate - gets a wireguard peer config for each peer of a node
  294. func GetPeerUpdate(node *models.Node, host *models.Host) (models.PeerUpdate, error) {
  295. log.Println("peer update for node ", node.ID)
  296. peerUpdate := models.PeerUpdate{
  297. Network: node.Network,
  298. ServerVersion: ncutils.Version,
  299. DNS: getPeerDNS(node.Network),
  300. }
  301. currentPeers, err := GetNetworkNodes(node.Network)
  302. if err != nil {
  303. log.Println("no network nodes")
  304. return models.PeerUpdate{}, err
  305. }
  306. for _, peer := range currentPeers {
  307. var peerConfig wgtypes.PeerConfig
  308. peerHost, err := GetHost(peer.HostID.String())
  309. if err != nil {
  310. log.Println("no peer host", err)
  311. return models.PeerUpdate{}, err
  312. }
  313. if peer.ID == node.ID {
  314. log.Println("peer update, skipping self")
  315. //skip yourself
  316. continue
  317. }
  318. if !peer.Connected {
  319. log.Println("peer update, skipping unconnected node")
  320. //skip unconnected nodes
  321. continue
  322. }
  323. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(peer.ID.String())) {
  324. log.Println("peer update, skipping node for acl")
  325. //skip if not permitted by acl
  326. continue
  327. }
  328. peerConfig.PublicKey = peerHost.PublicKey
  329. peerConfig.PersistentKeepaliveInterval = &peer.PersistentKeepalive
  330. peerConfig.ReplaceAllowedIPs = true
  331. uselocal := false
  332. if host.EndpointIP.String() == peerHost.EndpointIP.String() {
  333. //peer is on same network
  334. // set to localaddress
  335. uselocal = true
  336. if node.LocalAddress.IP == nil {
  337. // use public endpint
  338. uselocal = false
  339. }
  340. if node.LocalAddress.String() == peer.LocalAddress.String() {
  341. uselocal = false
  342. }
  343. }
  344. peerConfig.Endpoint = &net.UDPAddr{
  345. IP: peerHost.EndpointIP,
  346. Port: peerHost.ListenPort,
  347. }
  348. if !host.ProxyEnabled && peerHost.ProxyEnabled {
  349. peerConfig.Endpoint.Port = peerHost.ProxyListenPort
  350. }
  351. if uselocal {
  352. peerConfig.Endpoint.IP = peer.LocalAddress.IP
  353. }
  354. allowedips := getNodeAllowedIPs(&peer, node)
  355. if peer.IsIngressGateway {
  356. for _, entry := range peer.IngressGatewayRange {
  357. _, cidr, err := net.ParseCIDR(string(entry))
  358. if err == nil {
  359. allowedips = append(allowedips, *cidr)
  360. }
  361. }
  362. }
  363. if peer.IsRelay {
  364. allowedips = append(allowedips, getRelayAllowedIPs(node, &peer)...)
  365. }
  366. if peer.IsEgressGateway {
  367. allowedips = append(allowedips, getEgressIPs(node, &peer)...)
  368. }
  369. peerConfig.AllowedIPs = allowedips
  370. peerUpdate.Peers = append(peerUpdate.Peers, peerConfig)
  371. }
  372. return peerUpdate, nil
  373. }
  374. func getRelayAllowedIPs(node, peer *models.Node) []net.IPNet {
  375. var allowedips []net.IPNet
  376. var allowedip net.IPNet
  377. for _, addr := range peer.RelayAddrs {
  378. if node.Address.IP.String() == addr {
  379. continue
  380. }
  381. if node.Address6.IP.String() == addr {
  382. continue
  383. }
  384. allowedip.IP = net.ParseIP(addr)
  385. allowedips = append(allowedips, allowedip)
  386. }
  387. return allowedips
  388. }
  389. // GetPeerUpdateLegacy - gets a wireguard peer config for each peer of a node
  390. func GetPeerUpdateLegacy(node *models.Node) (models.PeerUpdate, error) {
  391. var peerUpdate models.PeerUpdate
  392. var peers []wgtypes.PeerConfig
  393. var serverNodeAddresses = []models.ServerAddr{}
  394. var peerMap = make(models.PeerMap)
  395. var metrics *models.Metrics
  396. if servercfg.Is_EE {
  397. metrics, _ = GetMetrics(node.ID.String())
  398. }
  399. if metrics == nil {
  400. metrics = &models.Metrics{}
  401. }
  402. if metrics.FailoverPeers == nil {
  403. metrics.FailoverPeers = make(map[string]string)
  404. }
  405. // udppeers = the peers parsed from the local interface
  406. // gives us correct port to reach
  407. udppeers, errN := database.GetPeers(node.Network)
  408. if errN != nil {
  409. logger.Log(2, errN.Error())
  410. }
  411. currentPeers, err := GetNetworkNodes(node.Network)
  412. if err != nil {
  413. return models.PeerUpdate{}, err
  414. }
  415. host, err := GetHost(node.HostID.String())
  416. if err != nil {
  417. return peerUpdate, err
  418. }
  419. if node.IsRelayed && !host.ProxyEnabled {
  420. return GetPeerUpdateForRelayedNode(node, udppeers)
  421. }
  422. // #1 Set Keepalive values: set_keepalive
  423. // #2 Set local address: set_local - could be a LOT BETTER and fix some bugs with additional logic
  424. // #3 Set allowedips: set_allowedips
  425. for _, peer := range currentPeers {
  426. peerHost, err := GetHost(peer.HostID.String())
  427. if err != nil {
  428. logger.Log(0, "error retrieving host for peer", node.ID.String(), err.Error())
  429. return models.PeerUpdate{}, err
  430. }
  431. if peer.ID == node.ID {
  432. //skip yourself
  433. continue
  434. }
  435. if node.Connected {
  436. //skip unconnected nodes
  437. continue
  438. }
  439. // if the node is not a server, set the endpoint
  440. var setEndpoint = true
  441. if peer.IsRelayed {
  442. if !peerHost.ProxyEnabled && !(node.IsRelay && ncutils.StringSliceContains(node.RelayAddrs, peer.PrimaryAddress())) {
  443. //skip -- will be added to relay
  444. continue
  445. } else if node.IsRelay && ncutils.StringSliceContains(node.RelayAddrs, peer.PrimaryAddress()) {
  446. // dont set peer endpoint if it's relayed by node
  447. setEndpoint = false
  448. }
  449. }
  450. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(peer.ID.String())) {
  451. //skip if not permitted by acl
  452. continue
  453. }
  454. if len(metrics.FailoverPeers[peer.ID.String()]) > 0 && IsFailoverPresent(node.Network) {
  455. logger.Log(2, "peer", peer.ID.String(), peer.PrimaryAddress(), "was found to be in failover peers list for node", node.ID.String(), node.PrimaryAddress())
  456. continue
  457. }
  458. if err != nil {
  459. return models.PeerUpdate{}, err
  460. }
  461. host, err := GetHost(node.HostID.String())
  462. if err != nil {
  463. logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
  464. return models.PeerUpdate{}, err
  465. }
  466. if host.EndpointIP.String() == peerHost.EndpointIP.String() {
  467. //peer is on same network
  468. // set_local
  469. if node.LocalAddress.String() != peer.LocalAddress.String() && peer.LocalAddress.IP != nil {
  470. peerHost.EndpointIP = peer.LocalAddress.IP
  471. if peerHost.LocalListenPort != 0 {
  472. peerHost.ListenPort = peerHost.LocalListenPort
  473. }
  474. } else {
  475. continue
  476. }
  477. }
  478. // set address if setEndpoint is true
  479. // otherwise, will get inserted as empty value
  480. var address *net.UDPAddr
  481. // Sets ListenPort to UDP Hole Punching Port assuming:
  482. // - UDP Hole Punching is enabled
  483. // - udppeers retrieval did not return an error
  484. // - the endpoint is valid
  485. if setEndpoint {
  486. var setUDPPort = false
  487. if CheckEndpoint(udppeers[peerHost.PublicKey.String()]) {
  488. endpointstring := udppeers[peerHost.PublicKey.String()]
  489. endpointarr := strings.Split(endpointstring, ":")
  490. if len(endpointarr) == 2 {
  491. port, err := strconv.Atoi(endpointarr[1])
  492. if err == nil {
  493. setUDPPort = true
  494. peerHost.ListenPort = port
  495. }
  496. }
  497. }
  498. // if udp hole punching is on, but udp hole punching did not set it, use the LocalListenPort instead
  499. // or, if port is for some reason zero use the LocalListenPort
  500. // but only do this if LocalListenPort is not zero
  501. if ((!setUDPPort) || peerHost.ListenPort == 0) && peerHost.LocalListenPort != 0 {
  502. peerHost.ListenPort = peerHost.LocalListenPort
  503. }
  504. endpoint := peerHost.EndpointIP.String() + ":" + strconv.FormatInt(int64(peerHost.ListenPort), 10)
  505. address, err = net.ResolveUDPAddr("udp", endpoint)
  506. if err != nil {
  507. return models.PeerUpdate{}, err
  508. }
  509. }
  510. fetchRelayedIps := true
  511. if host.ProxyEnabled {
  512. fetchRelayedIps = false
  513. }
  514. allowedips := GetAllowedIPs(node, &peer, metrics, fetchRelayedIps)
  515. var keepalive time.Duration
  516. if node.PersistentKeepalive != 0 {
  517. // set_keepalive
  518. keepalive = node.PersistentKeepalive
  519. }
  520. var peerData = wgtypes.PeerConfig{
  521. PublicKey: peerHost.PublicKey,
  522. Endpoint: address,
  523. ReplaceAllowedIPs: true,
  524. AllowedIPs: allowedips,
  525. PersistentKeepaliveInterval: &keepalive,
  526. }
  527. peers = append(peers, peerData)
  528. peerMap[peerHost.PublicKey.String()] = models.IDandAddr{
  529. Name: peerHost.Name,
  530. ID: peer.ID.String(),
  531. Address: peer.PrimaryAddress(),
  532. IsServer: "no",
  533. }
  534. }
  535. if node.IsIngressGateway {
  536. extPeers, idsAndAddr, err := getExtPeers(node, true)
  537. if err == nil {
  538. peers = append(peers, extPeers...)
  539. for i := range idsAndAddr {
  540. peerMap[idsAndAddr[i].ID] = idsAndAddr[i]
  541. }
  542. } else if !database.IsEmptyRecord(err) {
  543. logger.Log(1, "error retrieving external clients:", err.Error())
  544. }
  545. }
  546. peerUpdate.Network = node.Network
  547. peerUpdate.ServerVersion = servercfg.Version
  548. sort.SliceStable(peers[:], func(i, j int) bool {
  549. return peers[i].PublicKey.String() < peers[j].PublicKey.String()
  550. })
  551. peerUpdate.Peers = peers
  552. peerUpdate.ServerAddrs = serverNodeAddresses
  553. peerUpdate.DNS = getPeerDNS(node.Network)
  554. peerUpdate.PeerIDs = peerMap
  555. return peerUpdate, nil
  556. }
  557. func getExtPeers(node *models.Node, forIngressNode bool) ([]wgtypes.PeerConfig, []models.IDandAddr, error) {
  558. var peers []wgtypes.PeerConfig
  559. var idsAndAddr []models.IDandAddr
  560. extPeers, err := GetNetworkExtClients(node.Network)
  561. if err != nil {
  562. return peers, idsAndAddr, err
  563. }
  564. host, err := GetHost(node.HostID.String())
  565. if err != nil {
  566. return peers, idsAndAddr, err
  567. }
  568. for _, extPeer := range extPeers {
  569. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  570. if err != nil {
  571. logger.Log(1, "error parsing ext pub key:", err.Error())
  572. continue
  573. }
  574. if host.PublicKey.String() == extPeer.PublicKey {
  575. continue
  576. }
  577. var allowedips []net.IPNet
  578. var peer wgtypes.PeerConfig
  579. if forIngressNode && extPeer.Address != "" {
  580. var peeraddr = net.IPNet{
  581. IP: net.ParseIP(extPeer.Address),
  582. Mask: net.CIDRMask(32, 32),
  583. }
  584. if peeraddr.IP != nil && peeraddr.Mask != nil {
  585. allowedips = append(allowedips, peeraddr)
  586. }
  587. }
  588. if forIngressNode && extPeer.Address6 != "" {
  589. var addr6 = net.IPNet{
  590. IP: net.ParseIP(extPeer.Address6),
  591. Mask: net.CIDRMask(128, 128),
  592. }
  593. if addr6.IP != nil && addr6.Mask != nil {
  594. allowedips = append(allowedips, addr6)
  595. }
  596. }
  597. if !forIngressNode {
  598. if extPeer.InternalIPAddr != "" {
  599. peerInternalAddr := net.IPNet{
  600. IP: net.ParseIP(extPeer.InternalIPAddr),
  601. Mask: net.CIDRMask(32, 32),
  602. }
  603. if peerInternalAddr.IP != nil && peerInternalAddr.Mask != nil {
  604. allowedips = append(allowedips, peerInternalAddr)
  605. }
  606. }
  607. if extPeer.InternalIPAddr6 != "" {
  608. peerInternalAddr6 := net.IPNet{
  609. IP: net.ParseIP(extPeer.InternalIPAddr6),
  610. Mask: net.CIDRMask(32, 32),
  611. }
  612. if peerInternalAddr6.IP != nil && peerInternalAddr6.Mask != nil {
  613. allowedips = append(allowedips, peerInternalAddr6)
  614. }
  615. }
  616. }
  617. primaryAddr := extPeer.Address
  618. if primaryAddr == "" {
  619. primaryAddr = extPeer.Address6
  620. }
  621. peer = wgtypes.PeerConfig{
  622. PublicKey: pubkey,
  623. ReplaceAllowedIPs: true,
  624. AllowedIPs: allowedips,
  625. }
  626. peers = append(peers, peer)
  627. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  628. ID: peer.PublicKey.String(),
  629. Address: primaryAddr,
  630. })
  631. }
  632. return peers, idsAndAddr, nil
  633. }
  634. func getExtPeersForProxy(node *models.Node, proxyPeerConf map[string]proxy_models.PeerConf) ([]wgtypes.PeerConfig, map[string]proxy_models.PeerConf, error) {
  635. var peers []wgtypes.PeerConfig
  636. host, err := GetHost(node.HostID.String())
  637. if err != nil {
  638. logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
  639. }
  640. extPeers, err := GetNetworkExtClients(node.Network)
  641. if err != nil {
  642. return peers, proxyPeerConf, err
  643. }
  644. for _, extPeer := range extPeers {
  645. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  646. if err != nil {
  647. logger.Log(1, "error parsing ext pub key:", err.Error())
  648. continue
  649. }
  650. if host.PublicKey.String() == extPeer.PublicKey {
  651. continue
  652. }
  653. var allowedips []net.IPNet
  654. var peer wgtypes.PeerConfig
  655. if extPeer.Address != "" {
  656. var peeraddr = net.IPNet{
  657. IP: net.ParseIP(extPeer.Address),
  658. Mask: net.CIDRMask(32, 32),
  659. }
  660. if peeraddr.IP != nil && peeraddr.Mask != nil {
  661. allowedips = append(allowedips, peeraddr)
  662. }
  663. }
  664. if extPeer.Address6 != "" {
  665. var addr6 = net.IPNet{
  666. IP: net.ParseIP(extPeer.Address6),
  667. Mask: net.CIDRMask(128, 128),
  668. }
  669. if addr6.IP != nil && addr6.Mask != nil {
  670. allowedips = append(allowedips, addr6)
  671. }
  672. }
  673. peer = wgtypes.PeerConfig{
  674. PublicKey: pubkey,
  675. ReplaceAllowedIPs: true,
  676. AllowedIPs: allowedips,
  677. }
  678. extInternalPrimaryAddr := extPeer.InternalIPAddr
  679. if extInternalPrimaryAddr == "" {
  680. extInternalPrimaryAddr = extPeer.InternalIPAddr6
  681. }
  682. extConf := proxy_models.PeerConf{
  683. IsExtClient: true,
  684. Address: net.ParseIP(extPeer.Address),
  685. ExtInternalIp: net.ParseIP(extInternalPrimaryAddr),
  686. }
  687. if extPeer.IngressGatewayID == node.ID.String() {
  688. extConf.IsAttachedExtClient = true
  689. }
  690. ingGatewayUdpAddr, err := net.ResolveUDPAddr("udp", extPeer.IngressGatewayEndpoint)
  691. if err == nil {
  692. extConf.IngressGatewayEndPoint = ingGatewayUdpAddr
  693. }
  694. proxyPeerConf[peer.PublicKey.String()] = extConf
  695. peers = append(peers, peer)
  696. }
  697. return peers, proxyPeerConf, nil
  698. }
  699. // GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
  700. func GetAllowedIPs(node, peer *models.Node, metrics *models.Metrics, fetchRelayedIps bool) []net.IPNet {
  701. var allowedips []net.IPNet
  702. allowedips = getNodeAllowedIPs(peer, node)
  703. // handle ingress gateway peers
  704. if peer.IsIngressGateway {
  705. extPeers, _, err := getExtPeers(peer, false)
  706. if err != nil {
  707. logger.Log(2, "could not retrieve ext peers for ", peer.ID.String(), err.Error())
  708. }
  709. for _, extPeer := range extPeers {
  710. allowedips = append(allowedips, extPeer.AllowedIPs...)
  711. }
  712. // if node is a failover node, add allowed ips from nodes it is handling
  713. if metrics != nil && peer.Failover && metrics.FailoverPeers != nil {
  714. // traverse through nodes that need handling
  715. logger.Log(3, "peer", peer.ID.String(), "was found to be failover for", node.ID.String(), "checking failover peers...")
  716. for k := range metrics.FailoverPeers {
  717. // if FailoverNode is me for this node, add allowedips
  718. if metrics.FailoverPeers[k] == peer.ID.String() {
  719. // get original node so we can traverse the allowed ips
  720. nodeToFailover, err := GetNodeByID(k)
  721. if err == nil {
  722. failoverNodeMetrics, err := GetMetrics(nodeToFailover.ID.String())
  723. if err == nil && failoverNodeMetrics != nil {
  724. if len(failoverNodeMetrics.NodeName) > 0 {
  725. allowedips = append(allowedips, getNodeAllowedIPs(&nodeToFailover, peer)...)
  726. logger.Log(0, "failing over node", nodeToFailover.ID.String(), nodeToFailover.PrimaryAddress(), "to failover node", peer.ID.String())
  727. }
  728. }
  729. }
  730. }
  731. }
  732. }
  733. }
  734. // handle relay gateway peers
  735. if fetchRelayedIps && peer.IsRelay {
  736. for _, ip := range peer.RelayAddrs {
  737. //find node ID of relayed peer
  738. relayedPeer, err := findNode(ip)
  739. if err != nil {
  740. logger.Log(0, "failed to find node for ip ", ip, err.Error())
  741. continue
  742. }
  743. if relayedPeer == nil {
  744. continue
  745. }
  746. if relayedPeer.ID == node.ID {
  747. //skip self
  748. continue
  749. }
  750. //check if acl permits comms
  751. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(relayedPeer.ID.String())) {
  752. continue
  753. }
  754. if iplib.Version(net.ParseIP(ip)) == 4 {
  755. relayAddr := net.IPNet{
  756. IP: net.ParseIP(ip),
  757. Mask: net.CIDRMask(32, 32),
  758. }
  759. allowedips = append(allowedips, relayAddr)
  760. }
  761. if iplib.Version(net.ParseIP(ip)) == 6 {
  762. relayAddr := net.IPNet{
  763. IP: net.ParseIP(ip),
  764. Mask: net.CIDRMask(128, 128),
  765. }
  766. allowedips = append(allowedips, relayAddr)
  767. }
  768. relayedNode, err := findNode(ip)
  769. if err != nil {
  770. logger.Log(1, "unable to find node for relayed address", ip, err.Error())
  771. continue
  772. }
  773. if relayedNode.IsEgressGateway {
  774. extAllowedIPs := getEgressIPs(node, relayedNode)
  775. allowedips = append(allowedips, extAllowedIPs...)
  776. }
  777. if relayedNode.IsIngressGateway {
  778. extPeers, _, err := getExtPeers(relayedNode, false)
  779. if err == nil {
  780. for _, extPeer := range extPeers {
  781. allowedips = append(allowedips, extPeer.AllowedIPs...)
  782. }
  783. } else {
  784. logger.Log(0, "failed to retrieve extclients from relayed ingress", err.Error())
  785. }
  786. }
  787. }
  788. }
  789. return allowedips
  790. }
  791. func getPeerDNS(network string) string {
  792. var dns string
  793. if nodes, err := GetNetworkNodes(network); err == nil {
  794. for i, node := range nodes {
  795. host, err := GetHost(node.HostID.String())
  796. if err != nil {
  797. logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
  798. continue
  799. }
  800. dns = dns + fmt.Sprintf("%s %s.%s\n", nodes[i].Address, host.Name, nodes[i].Network)
  801. }
  802. }
  803. if customDNSEntries, err := GetCustomDNS(network); err == nil {
  804. for _, entry := range customDNSEntries {
  805. // TODO - filter entries based on ACLs / given peers vs nodes in network
  806. dns = dns + fmt.Sprintf("%s %s.%s\n", entry.Address, entry.Name, entry.Network)
  807. }
  808. }
  809. return dns
  810. }
  811. // GetPeerUpdateForRelayedNode - calculates peer update for a relayed node by getting the relay
  812. // copying the relay node's allowed ips and making appropriate substitutions
  813. func GetPeerUpdateForRelayedNode(node *models.Node, udppeers map[string]string) (models.PeerUpdate, error) {
  814. var peerUpdate models.PeerUpdate
  815. var peers []wgtypes.PeerConfig
  816. var serverNodeAddresses = []models.ServerAddr{}
  817. var allowedips []net.IPNet
  818. //find node that is relaying us
  819. relay := FindRelay(node)
  820. if relay == nil {
  821. return models.PeerUpdate{}, errors.New("not found")
  822. }
  823. //add relay to lists of allowed ip
  824. if relay.Address.IP != nil {
  825. relayIP := relay.Address
  826. allowedips = append(allowedips, relayIP)
  827. }
  828. if relay.Address6.IP != nil {
  829. relayIP6 := relay.Address6
  830. allowedips = append(allowedips, relayIP6)
  831. }
  832. //get PeerUpdate for relayed node
  833. relayHost, err := GetHost(relay.HostID.String())
  834. if err != nil {
  835. return models.PeerUpdate{}, err
  836. }
  837. relayPeerUpdate, err := GetPeerUpdate(relay, relayHost)
  838. if err != nil {
  839. return models.PeerUpdate{}, err
  840. }
  841. //add the relays allowed ips from all of the relay's peers
  842. for _, peer := range relayPeerUpdate.Peers {
  843. allowedips = append(allowedips, peer.AllowedIPs...)
  844. }
  845. //delete any ips not permitted by acl
  846. for i := len(allowedips) - 1; i >= 0; i-- {
  847. target, err := findNode(allowedips[i].IP.String())
  848. if err != nil {
  849. logger.Log(0, "failed to find node for ip", allowedips[i].IP.String(), err.Error())
  850. continue
  851. }
  852. if target == nil {
  853. logger.Log(0, "failed to find node for ip", allowedips[i].IP.String())
  854. continue
  855. }
  856. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(target.ID.String())) {
  857. logger.Log(0, "deleting node from relayednode per acl", node.ID.String(), target.ID.String())
  858. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  859. }
  860. }
  861. //delete self from allowed ips
  862. for i := len(allowedips) - 1; i >= 0; i-- {
  863. if allowedips[i].IP.String() == node.Address.IP.String() || allowedips[i].IP.String() == node.Address6.IP.String() {
  864. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  865. }
  866. }
  867. //delete egressrange from allowedip if we are egress gateway
  868. if node.IsEgressGateway {
  869. for i := len(allowedips) - 1; i >= 0; i-- {
  870. if StringSliceContains(node.EgressGatewayRanges, allowedips[i].String()) {
  871. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  872. }
  873. }
  874. }
  875. //delete extclients from allowedip if we are ingress gateway
  876. if node.IsIngressGateway {
  877. for i := len(allowedips) - 1; i >= 0; i-- {
  878. if strings.Contains(node.IngressGatewayRange, allowedips[i].IP.String()) {
  879. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  880. }
  881. }
  882. }
  883. //add egress range if relay is egress
  884. if relay.IsEgressGateway {
  885. var ip *net.IPNet
  886. for _, cidr := range relay.EgressGatewayRanges {
  887. _, ip, err = net.ParseCIDR(cidr)
  888. if err != nil {
  889. continue
  890. }
  891. }
  892. allowedips = append(allowedips, *ip)
  893. }
  894. var setUDPPort = false
  895. var listenPort int
  896. if CheckEndpoint(udppeers[relayHost.PublicKey.String()]) {
  897. endpointstring := udppeers[relayHost.PublicKey.String()]
  898. endpointarr := strings.Split(endpointstring, ":")
  899. if len(endpointarr) == 2 {
  900. port, err := strconv.Atoi(endpointarr[1])
  901. if err == nil {
  902. setUDPPort = true
  903. listenPort = port
  904. }
  905. }
  906. }
  907. // if udp hole punching is on, but udp hole punching did not set it, use the LocalListenPort instead
  908. // or, if port is for some reason zero use the LocalListenPort
  909. // but only do this if LocalListenPort is not zero
  910. if ((!setUDPPort) || relayHost.ListenPort == 0) && relayHost.LocalListenPort != 0 {
  911. listenPort = relayHost.LocalListenPort
  912. }
  913. endpoint := relayHost.EndpointIP.String() + ":" + strconv.FormatInt(int64(listenPort), 10)
  914. address, err := net.ResolveUDPAddr("udp", endpoint)
  915. if err != nil {
  916. return models.PeerUpdate{}, err
  917. }
  918. var keepalive time.Duration
  919. if node.PersistentKeepalive != 0 {
  920. // set_keepalive
  921. keepalive = node.PersistentKeepalive
  922. }
  923. var peerData = wgtypes.PeerConfig{
  924. PublicKey: relayHost.PublicKey,
  925. Endpoint: address,
  926. ReplaceAllowedIPs: true,
  927. AllowedIPs: allowedips,
  928. PersistentKeepaliveInterval: &keepalive,
  929. }
  930. peers = append(peers, peerData)
  931. //if ingress add extclients
  932. if node.IsIngressGateway {
  933. extPeers, _, err := getExtPeers(node, true)
  934. if err == nil {
  935. peers = append(peers, extPeers...)
  936. } else {
  937. logger.Log(2, "could not retrieve ext peers for ", node.ID.String(), err.Error())
  938. }
  939. }
  940. peerUpdate.Network = node.Network
  941. peerUpdate.ServerVersion = servercfg.Version
  942. sort.SliceStable(peers[:], func(i, j int) bool {
  943. return peers[i].PublicKey.String() < peers[j].PublicKey.String()
  944. })
  945. peerUpdate.Peers = peers
  946. peerUpdate.ServerAddrs = serverNodeAddresses
  947. peerUpdate.DNS = getPeerDNS(node.Network)
  948. return peerUpdate, nil
  949. }
  950. func getEgressIPs(node, peer *models.Node) []net.IPNet {
  951. host, err := GetHost(node.HostID.String())
  952. if err != nil {
  953. logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
  954. }
  955. peerHost, err := GetHost(peer.HostID.String())
  956. if err != nil {
  957. logger.Log(0, "error retrieving host for peer", peer.ID.String(), err.Error())
  958. }
  959. //check for internet gateway
  960. internetGateway := false
  961. if slices.Contains(peer.EgressGatewayRanges, "0.0.0.0/0") || slices.Contains(peer.EgressGatewayRanges, "::/0") {
  962. internetGateway = true
  963. }
  964. allowedips := []net.IPNet{}
  965. for _, iprange := range peer.EgressGatewayRanges { // go through each cidr for egress gateway
  966. _, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
  967. if err != nil {
  968. logger.Log(1, "could not parse gateway IP range. Not adding ", iprange)
  969. continue // if can't parse CIDR
  970. }
  971. nodeEndpointArr := strings.Split(peerHost.EndpointIP.String(), ":") // getting the public ip of node
  972. if ipnet.Contains(net.ParseIP(nodeEndpointArr[0])) && !internetGateway { // ensuring egress gateway range does not contain endpoint of node
  973. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", host.EndpointIP.String(), ", omitting")
  974. continue // skip adding egress range if overlaps with node's ip
  975. }
  976. // TODO: Could put in a lot of great logic to avoid conflicts / bad routes
  977. if ipnet.Contains(net.ParseIP(node.LocalAddress.String())) && !internetGateway { // ensuring egress gateway range does not contain public ip of node
  978. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.LocalAddress.String(), ", omitting")
  979. continue // skip adding egress range if overlaps with node's local ip
  980. }
  981. if err != nil {
  982. logger.Log(1, "error encountered when setting egress range", err.Error())
  983. } else {
  984. allowedips = append(allowedips, *ipnet)
  985. }
  986. }
  987. return allowedips
  988. }
  989. func getNodeAllowedIPs(peer, node *models.Node) []net.IPNet {
  990. var allowedips = []net.IPNet{}
  991. if peer.Address.IP != nil {
  992. allowed := net.IPNet{
  993. IP: peer.Address.IP,
  994. Mask: net.CIDRMask(32, 32),
  995. }
  996. allowedips = append(allowedips, allowed)
  997. }
  998. if peer.Address6.IP != nil {
  999. allowed := net.IPNet{
  1000. IP: peer.Address6.IP,
  1001. Mask: net.CIDRMask(128, 128),
  1002. }
  1003. allowedips = append(allowedips, allowed)
  1004. }
  1005. // handle egress gateway peers
  1006. if peer.IsEgressGateway {
  1007. //hasGateway = true
  1008. egressIPs := getEgressIPs(node, peer)
  1009. allowedips = append(allowedips, egressIPs...)
  1010. }
  1011. return allowedips
  1012. }