extpeers.go 27 KB

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