peers.go 37 KB

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