2
0

extpeers.go 27 KB

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