extpeers.go 29 KB

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