extpeers.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "reflect"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/goombaio/namegenerator"
  13. "github.com/gravitl/netmaker/database"
  14. "github.com/gravitl/netmaker/logger"
  15. "github.com/gravitl/netmaker/logic/acls"
  16. "github.com/gravitl/netmaker/models"
  17. "github.com/gravitl/netmaker/servercfg"
  18. "golang.org/x/exp/slog"
  19. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  20. )
  21. var (
  22. extClientCacheMutex = &sync.RWMutex{}
  23. extClientCacheMap = make(map[string]models.ExtClient)
  24. )
  25. func getAllExtClientsFromCache() (extClients []models.ExtClient) {
  26. extClientCacheMutex.RLock()
  27. for _, extclient := range extClientCacheMap {
  28. if extclient.Mutex == nil {
  29. extclient.Mutex = &sync.Mutex{}
  30. }
  31. extClients = append(extClients, extclient)
  32. }
  33. extClientCacheMutex.RUnlock()
  34. return
  35. }
  36. func deleteExtClientFromCache(key string) {
  37. extClientCacheMutex.Lock()
  38. delete(extClientCacheMap, key)
  39. extClientCacheMutex.Unlock()
  40. }
  41. func getExtClientFromCache(key string) (extclient models.ExtClient, ok bool) {
  42. extClientCacheMutex.RLock()
  43. extclient, ok = extClientCacheMap[key]
  44. if extclient.Mutex == nil {
  45. extclient.Mutex = &sync.Mutex{}
  46. }
  47. extClientCacheMutex.RUnlock()
  48. return
  49. }
  50. func storeExtClientInCache(key string, extclient models.ExtClient) {
  51. extClientCacheMutex.Lock()
  52. if extclient.Mutex == nil {
  53. extclient.Mutex = &sync.Mutex{}
  54. }
  55. extClientCacheMap[key] = extclient
  56. extClientCacheMutex.Unlock()
  57. }
  58. // ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client
  59. func GetEgressRangesOnNetwork(client *models.ExtClient) ([]string, error) {
  60. var result []string
  61. networkNodes, err := GetNetworkNodes(client.Network)
  62. if err != nil {
  63. return []string{}, err
  64. }
  65. for _, currentNode := range networkNodes {
  66. if currentNode.Network != client.Network {
  67. continue
  68. }
  69. if currentNode.IsEgressGateway { // add the egress gateway range(s) to the result
  70. if len(currentNode.EgressGatewayRanges) > 0 {
  71. result = append(result, currentNode.EgressGatewayRanges...)
  72. }
  73. }
  74. }
  75. extclients, _ := GetNetworkExtClients(client.Network)
  76. for _, extclient := range extclients {
  77. if extclient.ClientID == client.ClientID {
  78. continue
  79. }
  80. result = append(result, extclient.ExtraAllowedIPs...)
  81. }
  82. return result, nil
  83. }
  84. // DeleteExtClient - deletes an existing ext client
  85. func DeleteExtClient(network string, clientid string) error {
  86. key, err := GetRecordKey(clientid, network)
  87. if err != nil {
  88. return err
  89. }
  90. extClient, err := GetExtClient(clientid, network)
  91. if err != nil {
  92. return err
  93. }
  94. err = database.DeleteRecord(database.EXT_CLIENT_TABLE_NAME, key)
  95. if err != nil {
  96. return err
  97. }
  98. if servercfg.CacheEnabled() {
  99. // recycle ip address
  100. if extClient.Address != "" {
  101. RemoveIpFromAllocatedIpMap(network, extClient.Address)
  102. }
  103. if extClient.Address6 != "" {
  104. RemoveIpFromAllocatedIpMap(network, extClient.Address6)
  105. }
  106. deleteExtClientFromCache(key)
  107. }
  108. return nil
  109. }
  110. // DeleteExtClientAndCleanup - deletes an existing ext client and update ACLs
  111. func DeleteExtClientAndCleanup(extClient models.ExtClient) error {
  112. //delete extClient record
  113. err := DeleteExtClient(extClient.Network, extClient.ClientID)
  114. if err != nil {
  115. slog.Error("DeleteExtClientAndCleanup-remove extClient record: ", "Error", err.Error())
  116. return err
  117. }
  118. //update ACLs
  119. var networkAcls acls.ACLContainer
  120. networkAcls, err = networkAcls.Get(acls.ContainerID(extClient.Network))
  121. if err != nil {
  122. slog.Error("DeleteExtClientAndCleanup-update network acls: ", "Error", err.Error())
  123. return err
  124. }
  125. for objId := range networkAcls {
  126. delete(networkAcls[objId], acls.AclID(extClient.ClientID))
  127. }
  128. delete(networkAcls, acls.AclID(extClient.ClientID))
  129. if _, err = networkAcls.Save(acls.ContainerID(extClient.Network)); err != nil {
  130. slog.Error("DeleteExtClientAndCleanup-update network acls:", "Error", err.Error())
  131. return err
  132. }
  133. return nil
  134. }
  135. //TODO - enforce extclient-to-extclient on ingress gw
  136. /* 1. fetch all non-user static nodes
  137. a. check against each user node, if allowed add rule
  138. */
  139. // GetNetworkExtClients - gets the ext clients of given network
  140. func GetNetworkExtClients(network string) ([]models.ExtClient, error) {
  141. var extclients []models.ExtClient
  142. if servercfg.CacheEnabled() {
  143. allextclients := getAllExtClientsFromCache()
  144. if len(allextclients) != 0 {
  145. for _, extclient := range allextclients {
  146. if extclient.Network == network {
  147. extclients = append(extclients, extclient)
  148. }
  149. }
  150. return extclients, nil
  151. }
  152. }
  153. records, err := database.FetchRecords(database.EXT_CLIENT_TABLE_NAME)
  154. if err != nil {
  155. if database.IsEmptyRecord(err) {
  156. return extclients, nil
  157. }
  158. return extclients, err
  159. }
  160. for _, value := range records {
  161. var extclient models.ExtClient
  162. err = json.Unmarshal([]byte(value), &extclient)
  163. if err != nil {
  164. continue
  165. }
  166. key, err := GetRecordKey(extclient.ClientID, extclient.Network)
  167. if err == nil {
  168. if servercfg.CacheEnabled() {
  169. storeExtClientInCache(key, extclient)
  170. }
  171. }
  172. if extclient.Network == network {
  173. extclients = append(extclients, extclient)
  174. }
  175. }
  176. return extclients, err
  177. }
  178. // GetExtClient - gets a single ext client on a network
  179. func GetExtClient(clientid string, network string) (models.ExtClient, error) {
  180. var extclient models.ExtClient
  181. key, err := GetRecordKey(clientid, network)
  182. if err != nil {
  183. return extclient, err
  184. }
  185. if servercfg.CacheEnabled() {
  186. if extclient, ok := getExtClientFromCache(key); ok {
  187. return extclient, nil
  188. }
  189. }
  190. data, err := database.FetchRecord(database.EXT_CLIENT_TABLE_NAME, key)
  191. if err != nil {
  192. return extclient, err
  193. }
  194. err = json.Unmarshal([]byte(data), &extclient)
  195. if servercfg.CacheEnabled() {
  196. storeExtClientInCache(key, extclient)
  197. }
  198. return extclient, err
  199. }
  200. // GetGwExtclients - return all ext clients attached to the passed gw id
  201. func GetGwExtclients(nodeID, network string) []models.ExtClient {
  202. gwClients := []models.ExtClient{}
  203. clients, err := GetNetworkExtClients(network)
  204. if err != nil {
  205. return gwClients
  206. }
  207. for _, client := range clients {
  208. if client.IngressGatewayID == nodeID {
  209. gwClients = append(gwClients, client)
  210. }
  211. }
  212. return gwClients
  213. }
  214. // GetExtClient - gets a single ext client on a network
  215. func GetExtClientByPubKey(publicKey string, network string) (*models.ExtClient, error) {
  216. netClients, err := GetNetworkExtClients(network)
  217. if err != nil {
  218. return nil, err
  219. }
  220. for i := range netClients {
  221. ec := netClients[i]
  222. if ec.PublicKey == publicKey {
  223. return &ec, nil
  224. }
  225. }
  226. return nil, fmt.Errorf("no client found")
  227. }
  228. // CreateExtClient - creates and saves an extclient
  229. func CreateExtClient(extclient *models.ExtClient) error {
  230. // lock because we may need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs
  231. addressLock.Lock()
  232. defer addressLock.Unlock()
  233. if len(extclient.PublicKey) == 0 {
  234. privateKey, err := wgtypes.GeneratePrivateKey()
  235. if err != nil {
  236. return err
  237. }
  238. extclient.PrivateKey = privateKey.String()
  239. extclient.PublicKey = privateKey.PublicKey().String()
  240. } else if len(extclient.PrivateKey) == 0 && len(extclient.PublicKey) > 0 {
  241. extclient.PrivateKey = "[ENTER PRIVATE KEY]"
  242. }
  243. if extclient.ExtraAllowedIPs == nil {
  244. extclient.ExtraAllowedIPs = []string{}
  245. }
  246. parentNetwork, err := GetNetwork(extclient.Network)
  247. if err != nil {
  248. return err
  249. }
  250. if extclient.Address == "" {
  251. if parentNetwork.IsIPv4 == "yes" {
  252. newAddress, err := UniqueAddress(extclient.Network, true)
  253. if err != nil {
  254. return err
  255. }
  256. extclient.Address = newAddress.String()
  257. }
  258. }
  259. if extclient.Address6 == "" {
  260. if parentNetwork.IsIPv6 == "yes" {
  261. addr6, err := UniqueAddress6(extclient.Network, true)
  262. if err != nil {
  263. return err
  264. }
  265. extclient.Address6 = addr6.String()
  266. }
  267. }
  268. if extclient.ClientID == "" {
  269. extclient.ClientID, err = GenerateNodeName(extclient.Network)
  270. if err != nil {
  271. return err
  272. }
  273. }
  274. extclient.LastModified = time.Now().Unix()
  275. return SaveExtClient(extclient)
  276. }
  277. // GenerateNodeName - generates a random node name
  278. func GenerateNodeName(network string) (string, error) {
  279. seed := time.Now().UTC().UnixNano()
  280. nameGenerator := namegenerator.NewNameGenerator(seed)
  281. var name string
  282. cnt := 0
  283. for {
  284. if cnt > 10 {
  285. return "", errors.New("couldn't generate random name, try again")
  286. }
  287. cnt += 1
  288. name = nameGenerator.Generate()
  289. if len(name) > 15 {
  290. continue
  291. }
  292. _, err := GetExtClient(name, network)
  293. if err == nil {
  294. // config exists with same name
  295. continue
  296. }
  297. break
  298. }
  299. return name, nil
  300. }
  301. // SaveExtClient - saves an ext client to database
  302. func SaveExtClient(extclient *models.ExtClient) error {
  303. key, err := GetRecordKey(extclient.ClientID, extclient.Network)
  304. if err != nil {
  305. return err
  306. }
  307. data, err := json.Marshal(&extclient)
  308. if err != nil {
  309. return err
  310. }
  311. if err = database.Insert(key, string(data), database.EXT_CLIENT_TABLE_NAME); err != nil {
  312. return err
  313. }
  314. if servercfg.CacheEnabled() {
  315. storeExtClientInCache(key, *extclient)
  316. if _, ok := allocatedIpMap[extclient.Network]; ok {
  317. if extclient.Address != "" {
  318. AddIpToAllocatedIpMap(extclient.Network, net.ParseIP(extclient.Address))
  319. }
  320. if extclient.Address6 != "" {
  321. AddIpToAllocatedIpMap(extclient.Network, net.ParseIP(extclient.Address6))
  322. }
  323. }
  324. }
  325. return SetNetworkNodesLastModified(extclient.Network)
  326. }
  327. // UpdateExtClient - updates an ext client with new values
  328. func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) models.ExtClient {
  329. new := *old
  330. new.ClientID = update.ClientID
  331. if update.PublicKey != "" && old.PublicKey != update.PublicKey {
  332. new.PublicKey = update.PublicKey
  333. }
  334. if update.DNS != old.DNS {
  335. new.DNS = update.DNS
  336. }
  337. if update.Enabled != old.Enabled {
  338. new.Enabled = update.Enabled
  339. }
  340. new.ExtraAllowedIPs = update.ExtraAllowedIPs
  341. if update.DeniedACLs != nil && !reflect.DeepEqual(old.DeniedACLs, update.DeniedACLs) {
  342. new.DeniedACLs = update.DeniedACLs
  343. }
  344. // replace any \r\n with \n in postup and postdown from HTTP request
  345. new.PostUp = strings.Replace(update.PostUp, "\r\n", "\n", -1)
  346. new.PostDown = strings.Replace(update.PostDown, "\r\n", "\n", -1)
  347. new.Tags = update.Tags
  348. return new
  349. }
  350. // GetExtClientsByID - gets the clients of attached gateway
  351. func GetExtClientsByID(nodeid, network string) ([]models.ExtClient, error) {
  352. var result []models.ExtClient
  353. currentClients, err := GetNetworkExtClients(network)
  354. if err != nil {
  355. return result, err
  356. }
  357. for i := range currentClients {
  358. if currentClients[i].IngressGatewayID == nodeid {
  359. result = append(result, currentClients[i])
  360. }
  361. }
  362. return result, nil
  363. }
  364. // GetAllExtClients - gets all ext clients from DB
  365. func GetAllExtClients() ([]models.ExtClient, error) {
  366. var clients = []models.ExtClient{}
  367. currentNetworks, err := GetNetworks()
  368. if err != nil && database.IsEmptyRecord(err) {
  369. return clients, nil
  370. } else if err != nil {
  371. return clients, err
  372. }
  373. for i := range currentNetworks {
  374. netName := currentNetworks[i].NetID
  375. netClients, err := GetNetworkExtClients(netName)
  376. if err != nil {
  377. continue
  378. }
  379. clients = append(clients, netClients...)
  380. }
  381. return clients, nil
  382. }
  383. // GetAllExtClientsWithStatus - returns all external clients with
  384. // given status.
  385. func GetAllExtClientsWithStatus(status models.NodeStatus) ([]models.ExtClient, error) {
  386. extClients, err := GetAllExtClients()
  387. if err != nil {
  388. return nil, err
  389. }
  390. var validExtClients []models.ExtClient
  391. for _, extClient := range extClients {
  392. node := extClient.ConvertToStaticNode()
  393. getNodeStatus(&node, false)
  394. if node.Status == status {
  395. validExtClients = append(validExtClients, extClient)
  396. }
  397. }
  398. return validExtClients, nil
  399. }
  400. // ToggleExtClientConnectivity - enables or disables an ext client
  401. func ToggleExtClientConnectivity(client *models.ExtClient, enable bool) (models.ExtClient, error) {
  402. update := models.CustomExtClient{
  403. Enabled: enable,
  404. ClientID: client.ClientID,
  405. PublicKey: client.PublicKey,
  406. DNS: client.DNS,
  407. ExtraAllowedIPs: client.ExtraAllowedIPs,
  408. DeniedACLs: client.DeniedACLs,
  409. RemoteAccessClientID: client.RemoteAccessClientID,
  410. }
  411. // update in DB
  412. newClient := UpdateExtClient(client, &update)
  413. if err := DeleteExtClient(client.Network, client.ClientID); err != nil {
  414. slog.Error("failed to delete ext client during update", "id", client.ClientID, "network", client.Network, "error", err)
  415. return newClient, err
  416. }
  417. if err := SaveExtClient(&newClient); err != nil {
  418. slog.Error("failed to save updated ext client during update", "id", newClient.ClientID, "network", newClient.Network, "error", err)
  419. return newClient, err
  420. }
  421. return newClient, nil
  422. }
  423. // Sort a slice of net.IP addresses
  424. func sortIPs(ips []net.IP) {
  425. sort.Slice(ips, func(i, j int) bool {
  426. ip1, ip2 := ips[i].To16(), ips[j].To16()
  427. return string(ip1) < string(ip2) // Compare as byte slices
  428. })
  429. }
  430. func GetStaticNodeIps(node models.Node) (ips []net.IP) {
  431. defer func() {
  432. sortIPs(ips)
  433. }()
  434. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  435. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  436. extclients := GetStaticNodesByNetwork(models.NetworkID(node.Network), false)
  437. for _, extclient := range extclients {
  438. if extclient.IsUserNode && defaultUserPolicy.Enabled {
  439. continue
  440. }
  441. if !extclient.IsUserNode && defaultDevicePolicy.Enabled {
  442. continue
  443. }
  444. if extclient.StaticNode.Address != "" {
  445. ips = append(ips, extclient.StaticNode.AddressIPNet4().IP)
  446. }
  447. if extclient.StaticNode.Address6 != "" {
  448. ips = append(ips, extclient.StaticNode.AddressIPNet6().IP)
  449. }
  450. }
  451. return
  452. }
  453. func GetFwRulesOnIngressGateway(node models.Node) (rules []models.FwRule) {
  454. // fetch user access to static clients via policies
  455. defer func() {
  456. sort.Slice(rules, func(i, j int) bool {
  457. if !rules[i].SrcIP.IP.Equal(rules[j].SrcIP.IP) {
  458. return string(rules[i].SrcIP.IP.To16()) < string(rules[j].SrcIP.IP.To16())
  459. }
  460. return string(rules[i].DstIP.IP.To16()) < string(rules[j].DstIP.IP.To16())
  461. })
  462. }()
  463. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  464. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  465. nodes, _ := GetNetworkNodes(node.Network)
  466. nodes = append(nodes, GetStaticNodesByNetwork(models.NetworkID(node.Network), true)...)
  467. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(node.Network))
  468. for _, userNodeI := range userNodes {
  469. for _, peer := range nodes {
  470. if peer.IsUserNode {
  471. continue
  472. }
  473. if ok, allowedPolicies := IsUserAllowedToCommunicate(userNodeI.StaticNode.OwnerID, peer); ok {
  474. if peer.IsStatic {
  475. if userNodeI.StaticNode.Address != "" {
  476. if !defaultUserPolicy.Enabled {
  477. for _, policy := range allowedPolicies {
  478. rules = append(rules, models.FwRule{
  479. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  480. DstIP: peer.StaticNode.AddressIPNet4(),
  481. AllowedProtocol: policy.Proto,
  482. AllowedPorts: policy.Port,
  483. Allow: true,
  484. })
  485. rules = append(rules, models.FwRule{
  486. SrcIP: peer.StaticNode.AddressIPNet4(),
  487. DstIP: userNodeI.StaticNode.AddressIPNet4(),
  488. AllowedProtocol: policy.Proto,
  489. AllowedPorts: policy.Port,
  490. Allow: true,
  491. })
  492. }
  493. }
  494. }
  495. if userNodeI.StaticNode.Address6 != "" {
  496. if !defaultUserPolicy.Enabled {
  497. for _, policy := range allowedPolicies {
  498. rules = append(rules, models.FwRule{
  499. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  500. DstIP: peer.StaticNode.AddressIPNet6(),
  501. Allow: true,
  502. AllowedProtocol: policy.Proto,
  503. AllowedPorts: policy.Port,
  504. })
  505. rules = append(rules, models.FwRule{
  506. SrcIP: peer.StaticNode.AddressIPNet6(),
  507. DstIP: userNodeI.StaticNode.AddressIPNet6(),
  508. AllowedProtocol: policy.Proto,
  509. AllowedPorts: policy.Port,
  510. Allow: true,
  511. })
  512. }
  513. }
  514. }
  515. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  516. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  517. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  518. if err != nil {
  519. continue
  520. }
  521. if ipNet.IP.To4() != nil {
  522. rules = append(rules, models.FwRule{
  523. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  524. DstIP: *ipNet,
  525. Allow: true,
  526. })
  527. } else {
  528. rules = append(rules, models.FwRule{
  529. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  530. DstIP: *ipNet,
  531. Allow: true,
  532. })
  533. }
  534. }
  535. }
  536. } else {
  537. if userNodeI.StaticNode.Address != "" {
  538. if !defaultUserPolicy.Enabled {
  539. for _, policy := range allowedPolicies {
  540. rules = append(rules, models.FwRule{
  541. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  542. DstIP: net.IPNet{
  543. IP: peer.Address.IP,
  544. Mask: net.CIDRMask(32, 32),
  545. },
  546. AllowedProtocol: policy.Proto,
  547. AllowedPorts: policy.Port,
  548. Allow: true,
  549. })
  550. }
  551. }
  552. }
  553. if userNodeI.StaticNode.Address6 != "" {
  554. if !defaultUserPolicy.Enabled {
  555. for _, policy := range allowedPolicies {
  556. rules = append(rules, models.FwRule{
  557. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  558. DstIP: net.IPNet{
  559. IP: peer.Address6.IP,
  560. Mask: net.CIDRMask(128, 128),
  561. },
  562. AllowedProtocol: policy.Proto,
  563. AllowedPorts: policy.Port,
  564. Allow: true,
  565. })
  566. }
  567. }
  568. }
  569. }
  570. }
  571. }
  572. }
  573. if defaultDevicePolicy.Enabled {
  574. return
  575. }
  576. for _, nodeI := range nodes {
  577. if !nodeI.IsStatic || nodeI.IsUserNode {
  578. continue
  579. }
  580. for _, peer := range nodes {
  581. if peer.StaticNode.ClientID == nodeI.StaticNode.ClientID || peer.IsUserNode {
  582. continue
  583. }
  584. if ok, allowedPolicies := IsNodeAllowedToCommunicate(nodeI, peer, true); ok {
  585. if peer.IsStatic {
  586. if nodeI.StaticNode.Address != "" {
  587. for _, policy := range allowedPolicies {
  588. rules = append(rules, models.FwRule{
  589. SrcIP: nodeI.StaticNode.AddressIPNet4(),
  590. DstIP: peer.StaticNode.AddressIPNet4(),
  591. AllowedProtocol: policy.Proto,
  592. AllowedPorts: policy.Port,
  593. Allow: true,
  594. })
  595. if policy.AllowedDirection == models.TrafficDirectionBi {
  596. rules = append(rules, models.FwRule{
  597. SrcIP: peer.StaticNode.AddressIPNet4(),
  598. DstIP: nodeI.StaticNode.AddressIPNet4(),
  599. AllowedProtocol: policy.Proto,
  600. AllowedPorts: policy.Port,
  601. Allow: true,
  602. })
  603. }
  604. }
  605. }
  606. if nodeI.StaticNode.Address6 != "" {
  607. for _, policy := range allowedPolicies {
  608. rules = append(rules, models.FwRule{
  609. SrcIP: nodeI.StaticNode.AddressIPNet6(),
  610. DstIP: peer.StaticNode.AddressIPNet6(),
  611. AllowedProtocol: policy.Proto,
  612. AllowedPorts: policy.Port,
  613. Allow: true,
  614. })
  615. if policy.AllowedDirection == models.TrafficDirectionBi {
  616. rules = append(rules, models.FwRule{
  617. SrcIP: peer.StaticNode.AddressIPNet6(),
  618. DstIP: nodeI.StaticNode.AddressIPNet6(),
  619. AllowedProtocol: policy.Proto,
  620. AllowedPorts: policy.Port,
  621. Allow: true,
  622. })
  623. }
  624. }
  625. }
  626. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  627. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  628. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  629. if err != nil {
  630. continue
  631. }
  632. if ipNet.IP.To4() != nil {
  633. rules = append(rules, models.FwRule{
  634. SrcIP: nodeI.StaticNode.AddressIPNet4(),
  635. DstIP: *ipNet,
  636. Allow: true,
  637. })
  638. } else {
  639. rules = append(rules, models.FwRule{
  640. SrcIP: nodeI.StaticNode.AddressIPNet6(),
  641. DstIP: *ipNet,
  642. Allow: true,
  643. })
  644. }
  645. }
  646. }
  647. } else {
  648. if nodeI.StaticNode.Address != "" {
  649. for _, policy := range allowedPolicies {
  650. rules = append(rules, models.FwRule{
  651. SrcIP: nodeI.StaticNode.AddressIPNet4(),
  652. DstIP: net.IPNet{
  653. IP: peer.Address.IP,
  654. Mask: net.CIDRMask(32, 32),
  655. },
  656. AllowedProtocol: policy.Proto,
  657. AllowedPorts: policy.Port,
  658. Allow: true,
  659. })
  660. if policy.AllowedDirection == models.TrafficDirectionBi {
  661. rules = append(rules, models.FwRule{
  662. SrcIP: net.IPNet{
  663. IP: peer.Address.IP,
  664. Mask: net.CIDRMask(32, 32),
  665. },
  666. DstIP: nodeI.StaticNode.AddressIPNet4(),
  667. AllowedProtocol: policy.Proto,
  668. AllowedPorts: policy.Port,
  669. Allow: true,
  670. })
  671. }
  672. }
  673. }
  674. if nodeI.StaticNode.Address6 != "" {
  675. for _, policy := range allowedPolicies {
  676. rules = append(rules, models.FwRule{
  677. SrcIP: nodeI.StaticNode.AddressIPNet6(),
  678. DstIP: net.IPNet{
  679. IP: peer.Address6.IP,
  680. Mask: net.CIDRMask(128, 128),
  681. },
  682. AllowedProtocol: policy.Proto,
  683. AllowedPorts: policy.Port,
  684. Allow: true,
  685. })
  686. if policy.AllowedDirection == models.TrafficDirectionBi {
  687. rules = append(rules, models.FwRule{
  688. SrcIP: net.IPNet{
  689. IP: peer.Address6.IP,
  690. Mask: net.CIDRMask(128, 128),
  691. },
  692. DstIP: nodeI.StaticNode.AddressIPNet6(),
  693. AllowedProtocol: policy.Proto,
  694. AllowedPorts: policy.Port,
  695. Allow: true,
  696. })
  697. }
  698. }
  699. }
  700. }
  701. }
  702. }
  703. }
  704. return
  705. }
  706. func GetExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error) {
  707. var peers []wgtypes.PeerConfig
  708. var idsAndAddr []models.IDandAddr
  709. var egressRoutes []models.EgressNetworkRoutes
  710. extPeers, err := GetNetworkExtClients(node.Network)
  711. if err != nil {
  712. return peers, idsAndAddr, egressRoutes, err
  713. }
  714. host, err := GetHost(node.HostID.String())
  715. if err != nil {
  716. return peers, idsAndAddr, egressRoutes, err
  717. }
  718. for _, extPeer := range extPeers {
  719. extPeer := extPeer
  720. if !IsClientNodeAllowed(&extPeer, peer.ID.String()) {
  721. continue
  722. }
  723. if extPeer.RemoteAccessClientID == "" {
  724. if ok := IsPeerAllowed(extPeer.ConvertToStaticNode(), *peer, true); !ok {
  725. continue
  726. }
  727. } else {
  728. if ok, _ := IsUserAllowedToCommunicate(extPeer.OwnerID, *peer); !ok {
  729. continue
  730. }
  731. }
  732. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  733. if err != nil {
  734. logger.Log(1, "error parsing ext pub key:", err.Error())
  735. continue
  736. }
  737. if host.PublicKey.String() == extPeer.PublicKey ||
  738. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  739. continue
  740. }
  741. var allowedips []net.IPNet
  742. var peer wgtypes.PeerConfig
  743. if extPeer.Address != "" {
  744. var peeraddr = net.IPNet{
  745. IP: net.ParseIP(extPeer.Address),
  746. Mask: net.CIDRMask(32, 32),
  747. }
  748. if peeraddr.IP != nil && peeraddr.Mask != nil {
  749. allowedips = append(allowedips, peeraddr)
  750. }
  751. }
  752. if extPeer.Address6 != "" {
  753. var addr6 = net.IPNet{
  754. IP: net.ParseIP(extPeer.Address6),
  755. Mask: net.CIDRMask(128, 128),
  756. }
  757. if addr6.IP != nil && addr6.Mask != nil {
  758. allowedips = append(allowedips, addr6)
  759. }
  760. }
  761. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  762. _, cidr, err := net.ParseCIDR(extraAllowedIP)
  763. if err == nil {
  764. allowedips = append(allowedips, *cidr)
  765. }
  766. }
  767. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(*node, extPeer)...)
  768. primaryAddr := extPeer.Address
  769. if primaryAddr == "" {
  770. primaryAddr = extPeer.Address6
  771. }
  772. peer = wgtypes.PeerConfig{
  773. PublicKey: pubkey,
  774. ReplaceAllowedIPs: true,
  775. AllowedIPs: allowedips,
  776. }
  777. peers = append(peers, peer)
  778. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  779. ID: peer.PublicKey.String(),
  780. Name: extPeer.ClientID,
  781. Address: primaryAddr,
  782. IsExtClient: true,
  783. })
  784. }
  785. return peers, idsAndAddr, egressRoutes, nil
  786. }
  787. func getExtPeerEgressRoute(node models.Node, extPeer models.ExtClient) (egressRoutes []models.EgressNetworkRoutes) {
  788. egressRoutes = append(egressRoutes, models.EgressNetworkRoutes{
  789. EgressGwAddr: extPeer.AddressIPNet4(),
  790. EgressGwAddr6: extPeer.AddressIPNet6(),
  791. NodeAddr: node.Address,
  792. NodeAddr6: node.Address6,
  793. EgressRanges: extPeer.ExtraAllowedIPs,
  794. })
  795. return
  796. }
  797. func getExtpeerEgressRanges(node models.Node) (ranges, ranges6 []net.IPNet) {
  798. extPeers, err := GetNetworkExtClients(node.Network)
  799. if err != nil {
  800. return
  801. }
  802. for _, extPeer := range extPeers {
  803. if len(extPeer.ExtraAllowedIPs) == 0 {
  804. continue
  805. }
  806. if ok, _ := IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), node, true); !ok {
  807. continue
  808. }
  809. for _, allowedRange := range extPeer.ExtraAllowedIPs {
  810. _, ipnet, err := net.ParseCIDR(allowedRange)
  811. if err == nil {
  812. if ipnet.IP.To4() != nil {
  813. ranges = append(ranges, *ipnet)
  814. } else {
  815. ranges6 = append(ranges6, *ipnet)
  816. }
  817. }
  818. }
  819. }
  820. return
  821. }
  822. func getExtpeersExtraRoutes(node models.Node) (egressRoutes []models.EgressNetworkRoutes) {
  823. extPeers, err := GetNetworkExtClients(node.Network)
  824. if err != nil {
  825. return
  826. }
  827. for _, extPeer := range extPeers {
  828. if len(extPeer.ExtraAllowedIPs) == 0 {
  829. continue
  830. }
  831. if ok, _ := IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), node, true); !ok {
  832. continue
  833. }
  834. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(node, extPeer)...)
  835. }
  836. return
  837. }
  838. func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string) {
  839. gwnode, err := GetNodeByID(client.IngressGatewayID)
  840. if err != nil {
  841. logger.Log(0,
  842. fmt.Sprintf("failed to get ingress gateway node [%s] info: %v", client.IngressGatewayID, err))
  843. return
  844. }
  845. network, err := GetParentNetwork(client.Network)
  846. if err != nil {
  847. logger.Log(1, "Could not retrieve Ingress Gateway Network", client.Network)
  848. return
  849. }
  850. if IsInternetGw(gwnode) {
  851. egressrange := "0.0.0.0/0"
  852. if gwnode.Address6.IP != nil && client.Address6 != "" {
  853. egressrange += "," + "::/0"
  854. }
  855. allowedIPs = []string{egressrange}
  856. } else {
  857. allowedIPs = []string{network.AddressRange}
  858. if network.AddressRange6 != "" {
  859. allowedIPs = append(allowedIPs, network.AddressRange6)
  860. }
  861. if egressGatewayRanges, err := GetEgressRangesOnNetwork(&client); err == nil {
  862. allowedIPs = append(allowedIPs, egressGatewayRanges...)
  863. }
  864. }
  865. return
  866. }
  867. func GetStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node) {
  868. extClients, err := GetAllExtClients()
  869. if err != nil {
  870. return
  871. }
  872. for _, extI := range extClients {
  873. if extI.Network == network.String() {
  874. if extI.RemoteAccessClientID != "" {
  875. n := models.Node{
  876. IsStatic: true,
  877. StaticNode: extI,
  878. IsUserNode: extI.RemoteAccessClientID != "",
  879. }
  880. staticNode = append(staticNode, n)
  881. }
  882. }
  883. }
  884. return
  885. }
  886. func GetStaticNodesByNetwork(network models.NetworkID, onlyWg bool) (staticNode []models.Node) {
  887. extClients, err := GetAllExtClients()
  888. if err != nil {
  889. return
  890. }
  891. SortExtClient(extClients[:])
  892. for _, extI := range extClients {
  893. if extI.Network == network.String() {
  894. if onlyWg && extI.RemoteAccessClientID != "" {
  895. continue
  896. }
  897. n := models.Node{
  898. IsStatic: true,
  899. StaticNode: extI,
  900. IsUserNode: extI.RemoteAccessClientID != "",
  901. }
  902. staticNode = append(staticNode, n)
  903. }
  904. }
  905. return
  906. }
  907. func GetStaticNodesByGw(gwNode models.Node) (staticNode []models.Node) {
  908. extClients, err := GetAllExtClients()
  909. if err != nil {
  910. return
  911. }
  912. for _, extI := range extClients {
  913. if extI.IngressGatewayID == gwNode.ID.String() {
  914. n := models.Node{
  915. IsStatic: true,
  916. StaticNode: extI,
  917. IsUserNode: extI.RemoteAccessClientID != "",
  918. }
  919. staticNode = append(staticNode, n)
  920. }
  921. }
  922. return
  923. }