extpeers.go 27 KB

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