extpeers.go 27 KB

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