extpeers.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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. // 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. GetNodeCheckInStatus(&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. func GetStaticNodeIps(node models.Node) (ips []net.IP) {
  424. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  425. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  426. extclients := GetStaticNodesByNetwork(models.NetworkID(node.Network), false)
  427. for _, extclient := range extclients {
  428. if extclient.IsUserNode && defaultUserPolicy.Enabled {
  429. continue
  430. }
  431. if !extclient.IsUserNode && defaultDevicePolicy.Enabled {
  432. continue
  433. }
  434. if extclient.StaticNode.Address != "" {
  435. ips = append(ips, extclient.StaticNode.AddressIPNet4().IP)
  436. }
  437. if extclient.StaticNode.Address6 != "" {
  438. ips = append(ips, extclient.StaticNode.AddressIPNet6().IP)
  439. }
  440. }
  441. return
  442. }
  443. func getFwRulesForNodeAndPeerOnGw(node, peer models.Node, allowedPolicies []models.Acl) (rules []models.FwRule) {
  444. for _, policy := range allowedPolicies {
  445. // if static peer dst rule not for ingress node -> skip
  446. if node.Address.IP != nil {
  447. rules = append(rules, models.FwRule{
  448. SrcIP: net.IPNet{
  449. IP: node.Address.IP,
  450. Mask: net.CIDRMask(32, 32),
  451. },
  452. DstIP: net.IPNet{
  453. IP: peer.Address.IP,
  454. Mask: net.CIDRMask(32, 32),
  455. },
  456. AllowedProtocol: policy.Proto,
  457. AllowedPorts: policy.Port,
  458. Allow: true,
  459. })
  460. }
  461. if node.Address6.IP != nil {
  462. rules = append(rules, models.FwRule{
  463. SrcIP: net.IPNet{
  464. IP: node.Address6.IP,
  465. Mask: net.CIDRMask(128, 128),
  466. },
  467. DstIP: net.IPNet{
  468. IP: peer.Address6.IP,
  469. Mask: net.CIDRMask(128, 128),
  470. },
  471. AllowedProtocol: policy.Proto,
  472. AllowedPorts: policy.Port,
  473. Allow: true,
  474. })
  475. }
  476. if policy.AllowedDirection == models.TrafficDirectionBi {
  477. if node.Address.IP != nil {
  478. rules = append(rules, models.FwRule{
  479. SrcIP: net.IPNet{
  480. IP: peer.Address.IP,
  481. Mask: net.CIDRMask(32, 32),
  482. },
  483. DstIP: net.IPNet{
  484. IP: node.Address.IP,
  485. Mask: net.CIDRMask(32, 32),
  486. },
  487. AllowedProtocol: policy.Proto,
  488. AllowedPorts: policy.Port,
  489. Allow: true,
  490. })
  491. }
  492. if node.Address6.IP != nil {
  493. rules = append(rules, models.FwRule{
  494. SrcIP: net.IPNet{
  495. IP: peer.Address6.IP,
  496. Mask: net.CIDRMask(128, 128),
  497. },
  498. DstIP: net.IPNet{
  499. IP: node.Address6.IP,
  500. Mask: net.CIDRMask(128, 128),
  501. },
  502. AllowedProtocol: policy.Proto,
  503. AllowedPorts: policy.Port,
  504. Allow: true,
  505. })
  506. }
  507. }
  508. if len(node.StaticNode.ExtraAllowedIPs) > 0 {
  509. for _, additionalAllowedIPNet := range node.StaticNode.ExtraAllowedIPs {
  510. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  511. if err != nil {
  512. continue
  513. }
  514. if ipNet.IP.To4() != nil && peer.Address.IP != nil {
  515. rules = append(rules, models.FwRule{
  516. SrcIP: net.IPNet{
  517. IP: peer.Address.IP,
  518. Mask: net.CIDRMask(32, 32),
  519. },
  520. DstIP: *ipNet,
  521. Allow: true,
  522. })
  523. } else if peer.Address6.IP != nil {
  524. rules = append(rules, models.FwRule{
  525. SrcIP: net.IPNet{
  526. IP: peer.Address6.IP,
  527. Mask: net.CIDRMask(128, 128),
  528. },
  529. DstIP: *ipNet,
  530. Allow: true,
  531. })
  532. }
  533. }
  534. }
  535. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  536. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  537. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  538. if err != nil {
  539. continue
  540. }
  541. if ipNet.IP.To4() != nil && node.Address.IP != nil {
  542. rules = append(rules, models.FwRule{
  543. SrcIP: net.IPNet{
  544. IP: node.Address.IP,
  545. Mask: net.CIDRMask(32, 32),
  546. },
  547. DstIP: *ipNet,
  548. Allow: true,
  549. })
  550. } else if node.Address6.IP != nil {
  551. rules = append(rules, models.FwRule{
  552. SrcIP: net.IPNet{
  553. IP: node.Address6.IP,
  554. Mask: net.CIDRMask(128, 128),
  555. },
  556. DstIP: *ipNet,
  557. Allow: true,
  558. })
  559. }
  560. }
  561. }
  562. // add egress range rules
  563. for _, dstI := range policy.Dst {
  564. if dstI.ID == models.EgressRange {
  565. ip, cidr, err := net.ParseCIDR(dstI.Value)
  566. if err == nil {
  567. if ip.To4() != nil {
  568. if node.Address.IP != nil {
  569. rules = append(rules, models.FwRule{
  570. SrcIP: net.IPNet{
  571. IP: node.Address.IP,
  572. Mask: net.CIDRMask(32, 32),
  573. },
  574. DstIP: *cidr,
  575. AllowedProtocol: policy.Proto,
  576. AllowedPorts: policy.Port,
  577. Allow: true,
  578. })
  579. }
  580. } else {
  581. if node.Address6.IP != nil {
  582. rules = append(rules, models.FwRule{
  583. SrcIP: net.IPNet{
  584. IP: node.Address6.IP,
  585. Mask: net.CIDRMask(128, 128),
  586. },
  587. DstIP: *cidr,
  588. AllowedProtocol: policy.Proto,
  589. AllowedPorts: policy.Port,
  590. Allow: true,
  591. })
  592. }
  593. }
  594. }
  595. }
  596. }
  597. }
  598. return
  599. }
  600. func getFwRulesForUserNodesOnGw(node models.Node, nodes []models.Node) (rules []models.FwRule) {
  601. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  602. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(node.Network))
  603. for _, userNodeI := range userNodes {
  604. for _, peer := range nodes {
  605. if peer.IsUserNode {
  606. continue
  607. }
  608. if ok, allowedPolicies := IsUserAllowedToCommunicate(userNodeI.StaticNode.OwnerID, peer); ok {
  609. if peer.IsStatic {
  610. peer = peer.StaticNode.ConvertToStaticNode()
  611. }
  612. if !defaultUserPolicy.Enabled {
  613. for _, policy := range allowedPolicies {
  614. if userNodeI.StaticNode.Address != "" {
  615. rules = append(rules, models.FwRule{
  616. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  617. DstIP: net.IPNet{
  618. IP: peer.Address.IP,
  619. Mask: net.CIDRMask(32, 32),
  620. },
  621. AllowedProtocol: policy.Proto,
  622. AllowedPorts: policy.Port,
  623. Allow: true,
  624. })
  625. }
  626. if userNodeI.StaticNode.Address6 != "" {
  627. rules = append(rules, models.FwRule{
  628. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  629. DstIP: net.IPNet{
  630. IP: peer.Address6.IP,
  631. Mask: net.CIDRMask(128, 128),
  632. },
  633. AllowedProtocol: policy.Proto,
  634. AllowedPorts: policy.Port,
  635. Allow: true,
  636. })
  637. }
  638. // add egress ranges
  639. for _, dstI := range policy.Dst {
  640. if dstI.ID == models.EgressRange {
  641. ip, cidr, err := net.ParseCIDR(dstI.Value)
  642. if err == nil {
  643. if ip.To4() != nil && userNodeI.StaticNode.Address != "" {
  644. rules = append(rules, models.FwRule{
  645. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  646. DstIP: *cidr,
  647. AllowedProtocol: policy.Proto,
  648. AllowedPorts: policy.Port,
  649. Allow: true,
  650. })
  651. } else if ip.To16() != nil && userNodeI.StaticNode.Address6 != "" {
  652. rules = append(rules, models.FwRule{
  653. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  654. DstIP: *cidr,
  655. AllowedProtocol: policy.Proto,
  656. AllowedPorts: policy.Port,
  657. Allow: true,
  658. })
  659. }
  660. }
  661. }
  662. }
  663. }
  664. }
  665. }
  666. }
  667. }
  668. return
  669. }
  670. func GetFwRulesOnIngressGateway(node models.Node) (rules []models.FwRule) {
  671. // fetch user access to static clients via policies
  672. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  673. nodes, _ := GetNetworkNodes(node.Network)
  674. nodes = append(nodes, GetStaticNodesByNetwork(models.NetworkID(node.Network), true)...)
  675. rules = getFwRulesForUserNodesOnGw(node, nodes)
  676. if defaultDevicePolicy.Enabled {
  677. return
  678. }
  679. for _, nodeI := range nodes {
  680. if !nodeI.IsStatic || nodeI.IsUserNode {
  681. continue
  682. }
  683. // if nodeI.StaticNode.IngressGatewayID != node.ID.String() {
  684. // continue
  685. // }
  686. for _, peer := range nodes {
  687. if peer.StaticNode.ClientID == nodeI.StaticNode.ClientID || peer.IsUserNode {
  688. continue
  689. }
  690. if nodeI.StaticNode.IngressGatewayID != node.ID.String() &&
  691. ((!peer.IsStatic && peer.ID.String() != node.ID.String()) ||
  692. (peer.IsStatic && peer.StaticNode.IngressGatewayID != node.ID.String())) {
  693. continue
  694. }
  695. if peer.IsStatic {
  696. peer = peer.StaticNode.ConvertToStaticNode()
  697. }
  698. var allowedPolicies1 []models.Acl
  699. var ok bool
  700. if ok, allowedPolicies1 = IsNodeAllowedToCommunicateV1(nodeI.StaticNode.ConvertToStaticNode(), peer, true); ok {
  701. rules = append(rules, getFwRulesForNodeAndPeerOnGw(nodeI.StaticNode.ConvertToStaticNode(), peer, allowedPolicies1)...)
  702. }
  703. if ok, allowedPolicies2 := IsNodeAllowedToCommunicateV1(peer, nodeI.StaticNode.ConvertToStaticNode(), true); ok {
  704. rules = append(rules,
  705. getFwRulesForNodeAndPeerOnGw(peer, nodeI.StaticNode.ConvertToStaticNode(),
  706. GetUniquePolicies(allowedPolicies1, allowedPolicies2))...)
  707. }
  708. }
  709. }
  710. return
  711. }
  712. func GetUniquePolicies(policies1, policies2 []models.Acl) []models.Acl {
  713. policies1Map := make(map[string]struct{})
  714. for _, policy1I := range policies1 {
  715. policies1Map[policy1I.ID] = struct{}{}
  716. }
  717. for i := len(policies2) - 1; i >= 0; i-- {
  718. if _, ok := policies1Map[policies2[i].ID]; ok {
  719. policies2 = append(policies2[:i], policies2[i+1:]...)
  720. }
  721. }
  722. return policies2
  723. }
  724. func GetExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error) {
  725. var peers []wgtypes.PeerConfig
  726. var idsAndAddr []models.IDandAddr
  727. var egressRoutes []models.EgressNetworkRoutes
  728. extPeers, err := GetNetworkExtClients(node.Network)
  729. if err != nil {
  730. return peers, idsAndAddr, egressRoutes, err
  731. }
  732. host, err := GetHost(node.HostID.String())
  733. if err != nil {
  734. return peers, idsAndAddr, egressRoutes, err
  735. }
  736. for _, extPeer := range extPeers {
  737. extPeer := extPeer
  738. if !IsClientNodeAllowed(&extPeer, peer.ID.String()) {
  739. continue
  740. }
  741. if extPeer.RemoteAccessClientID == "" {
  742. if ok := IsPeerAllowed(extPeer.ConvertToStaticNode(), *peer, true); !ok {
  743. continue
  744. }
  745. } else {
  746. if ok, _ := IsUserAllowedToCommunicate(extPeer.OwnerID, *peer); !ok {
  747. continue
  748. }
  749. }
  750. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  751. if err != nil {
  752. logger.Log(1, "error parsing ext pub key:", err.Error())
  753. continue
  754. }
  755. if host.PublicKey.String() == extPeer.PublicKey ||
  756. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  757. continue
  758. }
  759. var allowedips []net.IPNet
  760. var peer wgtypes.PeerConfig
  761. if extPeer.Address != "" {
  762. var peeraddr = net.IPNet{
  763. IP: net.ParseIP(extPeer.Address),
  764. Mask: net.CIDRMask(32, 32),
  765. }
  766. if peeraddr.IP != nil && peeraddr.Mask != nil {
  767. allowedips = append(allowedips, peeraddr)
  768. }
  769. }
  770. if extPeer.Address6 != "" {
  771. var addr6 = net.IPNet{
  772. IP: net.ParseIP(extPeer.Address6),
  773. Mask: net.CIDRMask(128, 128),
  774. }
  775. if addr6.IP != nil && addr6.Mask != nil {
  776. allowedips = append(allowedips, addr6)
  777. }
  778. }
  779. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  780. _, cidr, err := net.ParseCIDR(extraAllowedIP)
  781. if err == nil {
  782. allowedips = append(allowedips, *cidr)
  783. }
  784. }
  785. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(*node, extPeer)...)
  786. primaryAddr := extPeer.Address
  787. if primaryAddr == "" {
  788. primaryAddr = extPeer.Address6
  789. }
  790. peer = wgtypes.PeerConfig{
  791. PublicKey: pubkey,
  792. ReplaceAllowedIPs: true,
  793. AllowedIPs: allowedips,
  794. }
  795. peers = append(peers, peer)
  796. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  797. ID: peer.PublicKey.String(),
  798. Name: extPeer.ClientID,
  799. Address: primaryAddr,
  800. IsExtClient: true,
  801. })
  802. }
  803. return peers, idsAndAddr, egressRoutes, nil
  804. }
  805. func getExtPeerEgressRoute(node models.Node, extPeer models.ExtClient) (egressRoutes []models.EgressNetworkRoutes) {
  806. r := models.EgressNetworkRoutes{
  807. PeerKey: extPeer.PublicKey,
  808. EgressGwAddr: extPeer.AddressIPNet4(),
  809. EgressGwAddr6: extPeer.AddressIPNet6(),
  810. NodeAddr: node.Address,
  811. NodeAddr6: node.Address6,
  812. EgressRanges: extPeer.ExtraAllowedIPs,
  813. }
  814. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  815. r.EgressRangesWithMetric = append(r.EgressRangesWithMetric, models.EgressRangeMetric{
  816. Network: extraAllowedIP,
  817. RouteMetric: 256,
  818. })
  819. }
  820. egressRoutes = append(egressRoutes, r)
  821. return
  822. }
  823. func getExtpeerEgressRanges(node models.Node) (ranges, ranges6 []net.IPNet) {
  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. for _, allowedRange := range extPeer.ExtraAllowedIPs {
  836. _, ipnet, err := net.ParseCIDR(allowedRange)
  837. if err == nil {
  838. if ipnet.IP.To4() != nil {
  839. ranges = append(ranges, *ipnet)
  840. } else {
  841. ranges6 = append(ranges6, *ipnet)
  842. }
  843. }
  844. }
  845. }
  846. return
  847. }
  848. func getExtpeersExtraRoutes(node models.Node) (egressRoutes []models.EgressNetworkRoutes) {
  849. extPeers, err := GetNetworkExtClients(node.Network)
  850. if err != nil {
  851. return
  852. }
  853. for _, extPeer := range extPeers {
  854. if len(extPeer.ExtraAllowedIPs) == 0 {
  855. continue
  856. }
  857. if ok, _ := IsNodeAllowedToCommunicateV1(extPeer.ConvertToStaticNode(), node, true); !ok {
  858. continue
  859. }
  860. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(node, extPeer)...)
  861. }
  862. return
  863. }
  864. func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string) {
  865. gwnode, err := GetNodeByID(client.IngressGatewayID)
  866. if err != nil {
  867. logger.Log(0,
  868. fmt.Sprintf("failed to get ingress gateway node [%s] info: %v", client.IngressGatewayID, err))
  869. return
  870. }
  871. network, err := GetParentNetwork(client.Network)
  872. if err != nil {
  873. logger.Log(1, "Could not retrieve Ingress Gateway Network", client.Network)
  874. return
  875. }
  876. if IsInternetGw(gwnode) {
  877. egressrange := "0.0.0.0/0"
  878. if gwnode.Address6.IP != nil && client.Address6 != "" {
  879. egressrange += "," + "::/0"
  880. }
  881. allowedIPs = []string{egressrange}
  882. } else {
  883. allowedIPs = []string{network.AddressRange}
  884. if network.AddressRange6 != "" {
  885. allowedIPs = append(allowedIPs, network.AddressRange6)
  886. }
  887. if egressGatewayRanges, err := GetEgressRangesOnNetwork(&client); err == nil {
  888. allowedIPs = append(allowedIPs, egressGatewayRanges...)
  889. }
  890. }
  891. return
  892. }
  893. func GetStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node) {
  894. extClients, err := GetAllExtClients()
  895. if err != nil {
  896. return
  897. }
  898. for _, extI := range extClients {
  899. if extI.Network == network.String() {
  900. if extI.RemoteAccessClientID != "" {
  901. n := extI.ConvertToStaticNode()
  902. staticNode = append(staticNode, n)
  903. }
  904. }
  905. }
  906. return
  907. }
  908. func GetStaticNodesByNetwork(network models.NetworkID, onlyWg bool) (staticNode []models.Node) {
  909. extClients, err := GetAllExtClients()
  910. if err != nil {
  911. return
  912. }
  913. SortExtClient(extClients[:])
  914. for _, extI := range extClients {
  915. if extI.Network == network.String() {
  916. if onlyWg && extI.RemoteAccessClientID != "" {
  917. continue
  918. }
  919. n := models.Node{
  920. IsStatic: true,
  921. StaticNode: extI,
  922. IsUserNode: extI.RemoteAccessClientID != "",
  923. }
  924. staticNode = append(staticNode, n)
  925. }
  926. }
  927. return
  928. }
  929. func GetStaticNodesByGw(gwNode models.Node) (staticNode []models.Node) {
  930. extClients, err := GetAllExtClients()
  931. if err != nil {
  932. return
  933. }
  934. for _, extI := range extClients {
  935. if extI.IngressGatewayID == gwNode.ID.String() {
  936. n := models.Node{
  937. IsStatic: true,
  938. StaticNode: extI,
  939. IsUserNode: extI.RemoteAccessClientID != "",
  940. }
  941. staticNode = append(staticNode, n)
  942. }
  943. }
  944. return
  945. }