extpeers.go 29 KB

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