extpeers.go 28 KB

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