extpeers.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "reflect"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/goombaio/namegenerator"
  12. "github.com/gravitl/netmaker/database"
  13. "github.com/gravitl/netmaker/logger"
  14. "github.com/gravitl/netmaker/logic/acls"
  15. "github.com/gravitl/netmaker/models"
  16. "github.com/gravitl/netmaker/servercfg"
  17. "golang.org/x/exp/slog"
  18. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  19. )
  20. var (
  21. extClientCacheMutex = &sync.RWMutex{}
  22. extClientCacheMap = make(map[string]models.ExtClient)
  23. )
  24. func getAllExtClientsFromCache() (extClients []models.ExtClient) {
  25. extClientCacheMutex.RLock()
  26. for _, extclient := range extClientCacheMap {
  27. if extclient.Mutex == nil {
  28. extclient.Mutex = &sync.Mutex{}
  29. }
  30. extClients = append(extClients, extclient)
  31. }
  32. extClientCacheMutex.RUnlock()
  33. return
  34. }
  35. func deleteExtClientFromCache(key string) {
  36. extClientCacheMutex.Lock()
  37. delete(extClientCacheMap, key)
  38. extClientCacheMutex.Unlock()
  39. }
  40. func getExtClientFromCache(key string) (extclient models.ExtClient, ok bool) {
  41. extClientCacheMutex.RLock()
  42. extclient, ok = extClientCacheMap[key]
  43. if extclient.Mutex == nil {
  44. extclient.Mutex = &sync.Mutex{}
  45. }
  46. extClientCacheMutex.RUnlock()
  47. return
  48. }
  49. func storeExtClientInCache(key string, extclient models.ExtClient) {
  50. extClientCacheMutex.Lock()
  51. if extclient.Mutex == nil {
  52. extclient.Mutex = &sync.Mutex{}
  53. }
  54. extClientCacheMap[key] = extclient
  55. extClientCacheMutex.Unlock()
  56. }
  57. // ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client
  58. func GetEgressRangesOnNetwork(client *models.ExtClient) ([]string, error) {
  59. var result []string
  60. networkNodes, err := GetNetworkNodes(client.Network)
  61. if err != nil {
  62. return []string{}, err
  63. }
  64. for _, currentNode := range networkNodes {
  65. if currentNode.Network != client.Network {
  66. continue
  67. }
  68. if currentNode.IsEgressGateway { // add the egress gateway range(s) to the result
  69. if len(currentNode.EgressGatewayRanges) > 0 {
  70. result = append(result, currentNode.EgressGatewayRanges...)
  71. }
  72. }
  73. }
  74. extclients, _ := GetNetworkExtClients(client.Network)
  75. for _, extclient := range extclients {
  76. if extclient.ClientID == client.ClientID {
  77. continue
  78. }
  79. result = append(result, extclient.ExtraAllowedIPs...)
  80. }
  81. return result, nil
  82. }
  83. // DeleteExtClient - deletes an existing ext client
  84. func DeleteExtClient(network string, clientid string) error {
  85. key, err := GetRecordKey(clientid, network)
  86. if err != nil {
  87. return err
  88. }
  89. extClient, err := GetExtClient(clientid, network)
  90. if err != nil {
  91. return err
  92. }
  93. err = database.DeleteRecord(database.EXT_CLIENT_TABLE_NAME, key)
  94. if err != nil {
  95. return err
  96. }
  97. if servercfg.CacheEnabled() {
  98. // recycle ip address
  99. if extClient.Address != "" {
  100. RemoveIpFromAllocatedIpMap(network, extClient.Address)
  101. }
  102. if extClient.Address6 != "" {
  103. RemoveIpFromAllocatedIpMap(network, extClient.Address6)
  104. }
  105. deleteExtClientFromCache(key)
  106. }
  107. go RemoveNodeFromAclPolicy(extClient.ConvertToStaticNode())
  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. // ToggleExtClientConnectivity - enables or disables an ext client
  384. func ToggleExtClientConnectivity(client *models.ExtClient, enable bool) (models.ExtClient, error) {
  385. update := models.CustomExtClient{
  386. Enabled: enable,
  387. ClientID: client.ClientID,
  388. PublicKey: client.PublicKey,
  389. DNS: client.DNS,
  390. ExtraAllowedIPs: client.ExtraAllowedIPs,
  391. DeniedACLs: client.DeniedACLs,
  392. RemoteAccessClientID: client.RemoteAccessClientID,
  393. }
  394. // update in DB
  395. newClient := UpdateExtClient(client, &update)
  396. if err := DeleteExtClient(client.Network, client.ClientID); err != nil {
  397. slog.Error("failed to delete ext client during update", "id", client.ClientID, "network", client.Network, "error", err)
  398. return newClient, err
  399. }
  400. if err := SaveExtClient(&newClient); err != nil {
  401. slog.Error("failed to save updated ext client during update", "id", newClient.ClientID, "network", newClient.Network, "error", err)
  402. return newClient, err
  403. }
  404. return newClient, nil
  405. }
  406. func GetStaticNodeIps(node models.Node) (ips []net.IP) {
  407. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  408. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  409. extclients := GetStaticNodesByNetwork(models.NetworkID(node.Network), false)
  410. for _, extclient := range extclients {
  411. if extclient.IsUserNode && defaultUserPolicy.Enabled {
  412. continue
  413. }
  414. if !extclient.IsUserNode && defaultDevicePolicy.Enabled {
  415. continue
  416. }
  417. if extclient.StaticNode.Address != "" {
  418. ips = append(ips, extclient.StaticNode.AddressIPNet4().IP)
  419. }
  420. if extclient.StaticNode.Address6 != "" {
  421. ips = append(ips, extclient.StaticNode.AddressIPNet6().IP)
  422. }
  423. }
  424. return
  425. }
  426. func getFwRulesForNodeAndPeerOnGw(node, peer models.Node, allowedPolicies []models.Acl) (rules []models.FwRule) {
  427. for _, policy := range allowedPolicies {
  428. // if static peer dst rule not for ingress node -> skip
  429. if node.Address.IP != nil {
  430. rules = append(rules, models.FwRule{
  431. SrcIP: net.IPNet{
  432. IP: node.Address.IP,
  433. Mask: net.CIDRMask(32, 32),
  434. },
  435. DstIP: net.IPNet{
  436. IP: peer.Address.IP,
  437. Mask: net.CIDRMask(32, 32),
  438. },
  439. AllowedProtocol: policy.Proto,
  440. AllowedPorts: policy.Port,
  441. Allow: true,
  442. })
  443. }
  444. if node.Address6.IP != nil {
  445. rules = append(rules, models.FwRule{
  446. SrcIP: net.IPNet{
  447. IP: node.Address6.IP,
  448. Mask: net.CIDRMask(128, 128),
  449. },
  450. DstIP: net.IPNet{
  451. IP: peer.Address6.IP,
  452. Mask: net.CIDRMask(128, 128),
  453. },
  454. AllowedProtocol: policy.Proto,
  455. AllowedPorts: policy.Port,
  456. Allow: true,
  457. })
  458. }
  459. if policy.AllowedDirection == models.TrafficDirectionBi {
  460. if node.Address.IP != nil {
  461. rules = append(rules, models.FwRule{
  462. SrcIP: net.IPNet{
  463. IP: peer.Address.IP,
  464. Mask: net.CIDRMask(32, 32),
  465. },
  466. DstIP: net.IPNet{
  467. IP: node.Address.IP,
  468. Mask: net.CIDRMask(32, 32),
  469. },
  470. AllowedProtocol: policy.Proto,
  471. AllowedPorts: policy.Port,
  472. Allow: true,
  473. })
  474. }
  475. if node.Address6.IP != nil {
  476. rules = append(rules, models.FwRule{
  477. SrcIP: net.IPNet{
  478. IP: peer.Address6.IP,
  479. Mask: net.CIDRMask(128, 128),
  480. },
  481. DstIP: net.IPNet{
  482. IP: node.Address6.IP,
  483. Mask: net.CIDRMask(128, 128),
  484. },
  485. AllowedProtocol: policy.Proto,
  486. AllowedPorts: policy.Port,
  487. Allow: true,
  488. })
  489. }
  490. }
  491. if len(node.StaticNode.ExtraAllowedIPs) > 0 {
  492. for _, additionalAllowedIPNet := range node.StaticNode.ExtraAllowedIPs {
  493. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  494. if err != nil {
  495. continue
  496. }
  497. if ipNet.IP.To4() != nil && peer.Address.IP != nil {
  498. rules = append(rules, models.FwRule{
  499. SrcIP: net.IPNet{
  500. IP: peer.Address.IP,
  501. Mask: net.CIDRMask(32, 32),
  502. },
  503. DstIP: *ipNet,
  504. Allow: true,
  505. })
  506. } else if peer.Address6.IP != nil {
  507. rules = append(rules, models.FwRule{
  508. SrcIP: net.IPNet{
  509. IP: peer.Address6.IP,
  510. Mask: net.CIDRMask(128, 128),
  511. },
  512. DstIP: *ipNet,
  513. Allow: true,
  514. })
  515. }
  516. }
  517. }
  518. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  519. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  520. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  521. if err != nil {
  522. continue
  523. }
  524. if ipNet.IP.To4() != nil && node.Address.IP != nil {
  525. rules = append(rules, models.FwRule{
  526. SrcIP: net.IPNet{
  527. IP: node.Address.IP,
  528. Mask: net.CIDRMask(32, 32),
  529. },
  530. DstIP: *ipNet,
  531. Allow: true,
  532. })
  533. } else if node.Address6.IP != nil {
  534. rules = append(rules, models.FwRule{
  535. SrcIP: net.IPNet{
  536. IP: node.Address6.IP,
  537. Mask: net.CIDRMask(128, 128),
  538. },
  539. DstIP: *ipNet,
  540. Allow: true,
  541. })
  542. }
  543. }
  544. }
  545. // add egress range rules
  546. for _, dstI := range policy.Dst {
  547. if dstI.ID == models.EgressRange {
  548. ip, cidr, err := net.ParseCIDR(dstI.Value)
  549. if err == nil {
  550. if ip.To4() != nil {
  551. if node.Address.IP != nil {
  552. rules = append(rules, models.FwRule{
  553. SrcIP: net.IPNet{
  554. IP: node.Address.IP,
  555. Mask: net.CIDRMask(32, 32),
  556. },
  557. DstIP: *cidr,
  558. AllowedProtocol: policy.Proto,
  559. AllowedPorts: policy.Port,
  560. Allow: true,
  561. })
  562. }
  563. } else {
  564. if node.Address6.IP != nil {
  565. rules = append(rules, models.FwRule{
  566. SrcIP: net.IPNet{
  567. IP: node.Address6.IP,
  568. Mask: net.CIDRMask(128, 128),
  569. },
  570. DstIP: *cidr,
  571. AllowedProtocol: policy.Proto,
  572. AllowedPorts: policy.Port,
  573. Allow: true,
  574. })
  575. }
  576. }
  577. }
  578. }
  579. }
  580. }
  581. return
  582. }
  583. func getFwRulesForUserNodesOnGw(node models.Node, nodes []models.Node) (rules []models.FwRule) {
  584. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  585. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(node.Network))
  586. for _, userNodeI := range userNodes {
  587. for _, peer := range nodes {
  588. if peer.IsUserNode {
  589. continue
  590. }
  591. if ok, allowedPolicies := IsUserAllowedToCommunicate(userNodeI.StaticNode.OwnerID, peer); ok {
  592. if peer.IsStatic {
  593. peer = peer.StaticNode.ConvertToStaticNode()
  594. }
  595. if !defaultUserPolicy.Enabled {
  596. for _, policy := range allowedPolicies {
  597. if userNodeI.StaticNode.Address != "" {
  598. rules = append(rules, models.FwRule{
  599. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  600. DstIP: net.IPNet{
  601. IP: peer.Address.IP,
  602. Mask: net.CIDRMask(32, 32),
  603. },
  604. AllowedProtocol: policy.Proto,
  605. AllowedPorts: policy.Port,
  606. Allow: true,
  607. })
  608. }
  609. if userNodeI.StaticNode.Address6 != "" {
  610. rules = append(rules, models.FwRule{
  611. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  612. DstIP: net.IPNet{
  613. IP: peer.Address6.IP,
  614. Mask: net.CIDRMask(128, 128),
  615. },
  616. AllowedProtocol: policy.Proto,
  617. AllowedPorts: policy.Port,
  618. Allow: true,
  619. })
  620. }
  621. // add egress ranges
  622. for _, dstI := range policy.Dst {
  623. if dstI.ID == models.EgressRange {
  624. ip, cidr, err := net.ParseCIDR(dstI.Value)
  625. if err == nil {
  626. if ip.To4() != nil && userNodeI.StaticNode.Address != "" {
  627. rules = append(rules, models.FwRule{
  628. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  629. DstIP: *cidr,
  630. AllowedProtocol: policy.Proto,
  631. AllowedPorts: policy.Port,
  632. Allow: true,
  633. })
  634. } else if ip.To16() != nil && userNodeI.StaticNode.Address6 != "" {
  635. rules = append(rules, models.FwRule{
  636. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  637. DstIP: *cidr,
  638. AllowedProtocol: policy.Proto,
  639. AllowedPorts: policy.Port,
  640. Allow: true,
  641. })
  642. }
  643. }
  644. }
  645. }
  646. }
  647. }
  648. }
  649. }
  650. }
  651. return
  652. }
  653. func GetFwRulesOnIngressGateway(node models.Node) (rules []models.FwRule) {
  654. // fetch user access to static clients via policies
  655. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  656. nodes, _ := GetNetworkNodes(node.Network)
  657. nodes = append(nodes, GetStaticNodesByNetwork(models.NetworkID(node.Network), true)...)
  658. rules = getFwRulesForUserNodesOnGw(node, nodes)
  659. if defaultDevicePolicy.Enabled {
  660. return
  661. }
  662. for _, nodeI := range nodes {
  663. if !nodeI.IsStatic || nodeI.IsUserNode {
  664. continue
  665. }
  666. // if nodeI.StaticNode.IngressGatewayID != node.ID.String() {
  667. // continue
  668. // }
  669. for _, peer := range nodes {
  670. if peer.StaticNode.ClientID == nodeI.StaticNode.ClientID || peer.IsUserNode {
  671. continue
  672. }
  673. if nodeI.StaticNode.IngressGatewayID != node.ID.String() &&
  674. ((!peer.IsStatic && peer.ID.String() != node.ID.String()) ||
  675. (peer.IsStatic && peer.StaticNode.IngressGatewayID != node.ID.String())) {
  676. continue
  677. }
  678. if peer.IsStatic {
  679. peer = peer.StaticNode.ConvertToStaticNode()
  680. }
  681. var allowedPolicies1 []models.Acl
  682. var ok bool
  683. if ok, allowedPolicies1 = IsNodeAllowedToCommunicateV1(nodeI.StaticNode.ConvertToStaticNode(), peer, true); ok {
  684. rules = append(rules, getFwRulesForNodeAndPeerOnGw(nodeI.StaticNode.ConvertToStaticNode(), peer, allowedPolicies1)...)
  685. }
  686. if ok, allowedPolicies2 := IsNodeAllowedToCommunicateV1(peer, nodeI.StaticNode.ConvertToStaticNode(), true); ok {
  687. rules = append(rules,
  688. getFwRulesForNodeAndPeerOnGw(peer, nodeI.StaticNode.ConvertToStaticNode(),
  689. GetUniquePolicies(allowedPolicies1, allowedPolicies2))...)
  690. }
  691. }
  692. }
  693. return
  694. }
  695. func GetUniquePolicies(policies1, policies2 []models.Acl) []models.Acl {
  696. policies1Map := make(map[string]struct{})
  697. for _, policy1I := range policies1 {
  698. policies1Map[policy1I.ID] = struct{}{}
  699. }
  700. for i := len(policies2) - 1; i >= 0; i-- {
  701. if _, ok := policies1Map[policies2[i].ID]; ok {
  702. policies2 = append(policies2[:i], policies2[i+1:]...)
  703. }
  704. }
  705. return policies2
  706. }
  707. func GetExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error) {
  708. var peers []wgtypes.PeerConfig
  709. var idsAndAddr []models.IDandAddr
  710. var egressRoutes []models.EgressNetworkRoutes
  711. extPeers, err := GetNetworkExtClients(node.Network)
  712. if err != nil {
  713. return peers, idsAndAddr, egressRoutes, err
  714. }
  715. host, err := GetHost(node.HostID.String())
  716. if err != nil {
  717. return peers, idsAndAddr, egressRoutes, err
  718. }
  719. for _, extPeer := range extPeers {
  720. extPeer := extPeer
  721. if !IsClientNodeAllowed(&extPeer, peer.ID.String()) {
  722. continue
  723. }
  724. if extPeer.RemoteAccessClientID == "" {
  725. if ok := IsPeerAllowed(extPeer.ConvertToStaticNode(), *peer, true); !ok {
  726. continue
  727. }
  728. } else {
  729. if ok, _ := IsUserAllowedToCommunicate(extPeer.OwnerID, *peer); !ok {
  730. continue
  731. }
  732. }
  733. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  734. if err != nil {
  735. logger.Log(1, "error parsing ext pub key:", err.Error())
  736. continue
  737. }
  738. if host.PublicKey.String() == extPeer.PublicKey ||
  739. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  740. continue
  741. }
  742. var allowedips []net.IPNet
  743. var peer wgtypes.PeerConfig
  744. if extPeer.Address != "" {
  745. var peeraddr = net.IPNet{
  746. IP: net.ParseIP(extPeer.Address),
  747. Mask: net.CIDRMask(32, 32),
  748. }
  749. if peeraddr.IP != nil && peeraddr.Mask != nil {
  750. allowedips = append(allowedips, peeraddr)
  751. }
  752. }
  753. if extPeer.Address6 != "" {
  754. var addr6 = net.IPNet{
  755. IP: net.ParseIP(extPeer.Address6),
  756. Mask: net.CIDRMask(128, 128),
  757. }
  758. if addr6.IP != nil && addr6.Mask != nil {
  759. allowedips = append(allowedips, addr6)
  760. }
  761. }
  762. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  763. _, cidr, err := net.ParseCIDR(extraAllowedIP)
  764. if err == nil {
  765. allowedips = append(allowedips, *cidr)
  766. }
  767. }
  768. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(*node, extPeer)...)
  769. primaryAddr := extPeer.Address
  770. if primaryAddr == "" {
  771. primaryAddr = extPeer.Address6
  772. }
  773. peer = wgtypes.PeerConfig{
  774. PublicKey: pubkey,
  775. ReplaceAllowedIPs: true,
  776. AllowedIPs: allowedips,
  777. }
  778. peers = append(peers, peer)
  779. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  780. ID: peer.PublicKey.String(),
  781. Name: extPeer.ClientID,
  782. Address: primaryAddr,
  783. IsExtClient: true,
  784. })
  785. }
  786. return peers, idsAndAddr, egressRoutes, nil
  787. }
  788. func getExtPeerEgressRoute(node models.Node, extPeer models.ExtClient) (egressRoutes []models.EgressNetworkRoutes) {
  789. egressRoutes = append(egressRoutes, models.EgressNetworkRoutes{
  790. EgressGwAddr: extPeer.AddressIPNet4(),
  791. EgressGwAddr6: extPeer.AddressIPNet6(),
  792. NodeAddr: node.Address,
  793. NodeAddr6: node.Address6,
  794. EgressRanges: extPeer.ExtraAllowedIPs,
  795. })
  796. return
  797. }
  798. func getExtpeerEgressRanges(node models.Node) (ranges, ranges6 []net.IPNet) {
  799. extPeers, err := GetNetworkExtClients(node.Network)
  800. if err != nil {
  801. return
  802. }
  803. for _, extPeer := range extPeers {
  804. if len(extPeer.ExtraAllowedIPs) == 0 {
  805. continue
  806. }
  807. if ok, _ := IsNodeAllowedToCommunicateV1(extPeer.ConvertToStaticNode(), node, true); !ok {
  808. continue
  809. }
  810. for _, allowedRange := range extPeer.ExtraAllowedIPs {
  811. _, ipnet, err := net.ParseCIDR(allowedRange)
  812. if err == nil {
  813. if ipnet.IP.To4() != nil {
  814. ranges = append(ranges, *ipnet)
  815. } else {
  816. ranges6 = append(ranges6, *ipnet)
  817. }
  818. }
  819. }
  820. }
  821. return
  822. }
  823. func getExtpeersExtraRoutes(node models.Node) (egressRoutes []models.EgressNetworkRoutes) {
  824. extPeers, err := GetNetworkExtClients(node.Network)
  825. if err != nil {
  826. return
  827. }
  828. for _, extPeer := range extPeers {
  829. if len(extPeer.ExtraAllowedIPs) == 0 {
  830. continue
  831. }
  832. if ok, _ := IsNodeAllowedToCommunicateV1(extPeer.ConvertToStaticNode(), node, true); !ok {
  833. continue
  834. }
  835. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(node, extPeer)...)
  836. }
  837. return
  838. }
  839. func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string) {
  840. gwnode, err := GetNodeByID(client.IngressGatewayID)
  841. if err != nil {
  842. logger.Log(0,
  843. fmt.Sprintf("failed to get ingress gateway node [%s] info: %v", client.IngressGatewayID, err))
  844. return
  845. }
  846. network, err := GetParentNetwork(client.Network)
  847. if err != nil {
  848. logger.Log(1, "Could not retrieve Ingress Gateway Network", client.Network)
  849. return
  850. }
  851. if IsInternetGw(gwnode) {
  852. egressrange := "0.0.0.0/0"
  853. if gwnode.Address6.IP != nil && client.Address6 != "" {
  854. egressrange += "," + "::/0"
  855. }
  856. allowedIPs = []string{egressrange}
  857. } else {
  858. allowedIPs = []string{network.AddressRange}
  859. if network.AddressRange6 != "" {
  860. allowedIPs = append(allowedIPs, network.AddressRange6)
  861. }
  862. if egressGatewayRanges, err := GetEgressRangesOnNetwork(&client); err == nil {
  863. allowedIPs = append(allowedIPs, egressGatewayRanges...)
  864. }
  865. }
  866. return
  867. }
  868. func GetStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node) {
  869. extClients, err := GetAllExtClients()
  870. if err != nil {
  871. return
  872. }
  873. for _, extI := range extClients {
  874. if extI.Network == network.String() {
  875. if extI.RemoteAccessClientID != "" {
  876. n := extI.ConvertToStaticNode()
  877. staticNode = append(staticNode, n)
  878. }
  879. }
  880. }
  881. return
  882. }
  883. func GetStaticNodesByNetwork(network models.NetworkID, onlyWg bool) (staticNode []models.Node) {
  884. extClients, err := GetAllExtClients()
  885. if err != nil {
  886. return
  887. }
  888. SortExtClient(extClients[:])
  889. for _, extI := range extClients {
  890. if extI.Network == network.String() {
  891. if onlyWg && extI.RemoteAccessClientID != "" {
  892. continue
  893. }
  894. n := models.Node{
  895. IsStatic: true,
  896. StaticNode: extI,
  897. IsUserNode: extI.RemoteAccessClientID != "",
  898. }
  899. staticNode = append(staticNode, n)
  900. }
  901. }
  902. return
  903. }
  904. func GetStaticNodesByGw(gwNode models.Node) (staticNode []models.Node) {
  905. extClients, err := GetAllExtClients()
  906. if err != nil {
  907. return
  908. }
  909. for _, extI := range extClients {
  910. if extI.IngressGatewayID == gwNode.ID.String() {
  911. n := models.Node{
  912. IsStatic: true,
  913. StaticNode: extI,
  914. IsUserNode: extI.RemoteAccessClientID != "",
  915. }
  916. staticNode = append(staticNode, n)
  917. }
  918. }
  919. return
  920. }