extpeers.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package logic
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "reflect"
  7. "sync"
  8. "time"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/models"
  12. "golang.org/x/exp/slog"
  13. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  14. )
  15. var (
  16. extClientCacheMutex = &sync.RWMutex{}
  17. extClientCacheMap = make(map[string]models.ExtClient)
  18. )
  19. func getAllExtClientsFromCache() (extClients []models.ExtClient) {
  20. extClientCacheMutex.RLock()
  21. for _, extclient := range extClientCacheMap {
  22. extClients = append(extClients, extclient)
  23. }
  24. extClientCacheMutex.RUnlock()
  25. return
  26. }
  27. func deleteExtClientFromCache(key string) {
  28. extClientCacheMutex.Lock()
  29. delete(extClientCacheMap, key)
  30. extClientCacheMutex.Unlock()
  31. }
  32. func getExtClientFromCache(key string) (extclient models.ExtClient, ok bool) {
  33. extClientCacheMutex.RLock()
  34. extclient, ok = extClientCacheMap[key]
  35. extClientCacheMutex.RUnlock()
  36. return
  37. }
  38. func storeExtClientInCache(key string, extclient models.ExtClient) {
  39. extClientCacheMutex.Lock()
  40. extClientCacheMap[key] = extclient
  41. extClientCacheMutex.Unlock()
  42. }
  43. // ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client
  44. func GetEgressRangesOnNetwork(client *models.ExtClient) ([]string, error) {
  45. var result []string
  46. networkNodes, err := GetNetworkNodes(client.Network)
  47. if err != nil {
  48. return []string{}, err
  49. }
  50. for _, currentNode := range networkNodes {
  51. if currentNode.Network != client.Network {
  52. continue
  53. }
  54. if currentNode.IsEgressGateway { // add the egress gateway range(s) to the result
  55. if len(currentNode.EgressGatewayRanges) > 0 {
  56. result = append(result, currentNode.EgressGatewayRanges...)
  57. }
  58. }
  59. }
  60. return result, nil
  61. }
  62. // DeleteExtClient - deletes an existing ext client
  63. func DeleteExtClient(network string, clientid string) error {
  64. key, err := GetRecordKey(clientid, network)
  65. if err != nil {
  66. return err
  67. }
  68. err = database.DeleteRecord(database.EXT_CLIENT_TABLE_NAME, key)
  69. if err != nil {
  70. return err
  71. }
  72. deleteExtClientFromCache(key)
  73. return nil
  74. }
  75. // GetNetworkExtClients - gets the ext clients of given network
  76. func GetNetworkExtClients(network string) ([]models.ExtClient, error) {
  77. var extclients []models.ExtClient
  78. allextclients := getAllExtClientsFromCache()
  79. if len(allextclients) != 0 {
  80. for _, extclient := range allextclients {
  81. if extclient.Network == network {
  82. extclients = append(extclients, extclient)
  83. }
  84. }
  85. return extclients, nil
  86. }
  87. records, err := database.FetchRecords(database.EXT_CLIENT_TABLE_NAME)
  88. if err != nil {
  89. if database.IsEmptyRecord(err) {
  90. return extclients, nil
  91. }
  92. return extclients, err
  93. }
  94. for _, value := range records {
  95. var extclient models.ExtClient
  96. err = json.Unmarshal([]byte(value), &extclient)
  97. if err != nil {
  98. continue
  99. }
  100. key, err := GetRecordKey(extclient.ClientID, extclient.Network)
  101. if err == nil {
  102. storeExtClientInCache(key, extclient)
  103. }
  104. if extclient.Network == network {
  105. extclients = append(extclients, extclient)
  106. }
  107. }
  108. return extclients, err
  109. }
  110. // GetExtClient - gets a single ext client on a network
  111. func GetExtClient(clientid string, network string) (models.ExtClient, error) {
  112. var extclient models.ExtClient
  113. key, err := GetRecordKey(clientid, network)
  114. if err != nil {
  115. return extclient, err
  116. }
  117. if extclient, ok := getExtClientFromCache(key); ok {
  118. return extclient, nil
  119. }
  120. data, err := database.FetchRecord(database.EXT_CLIENT_TABLE_NAME, key)
  121. if err != nil {
  122. return extclient, err
  123. }
  124. err = json.Unmarshal([]byte(data), &extclient)
  125. storeExtClientInCache(key, extclient)
  126. return extclient, err
  127. }
  128. // GetGwExtclients - return all ext clients attached to the passed gw id
  129. func GetGwExtclients(nodeID, network string) []models.ExtClient {
  130. gwClients := []models.ExtClient{}
  131. clients, err := GetNetworkExtClients(network)
  132. if err != nil {
  133. return gwClients
  134. }
  135. for _, client := range clients {
  136. if client.IngressGatewayID == nodeID {
  137. gwClients = append(gwClients, client)
  138. }
  139. }
  140. return gwClients
  141. }
  142. // GetExtClient - gets a single ext client on a network
  143. func GetExtClientByPubKey(publicKey string, network string) (*models.ExtClient, error) {
  144. netClients, err := GetNetworkExtClients(network)
  145. if err != nil {
  146. return nil, err
  147. }
  148. for i := range netClients {
  149. ec := netClients[i]
  150. if ec.PublicKey == publicKey {
  151. return &ec, nil
  152. }
  153. }
  154. return nil, fmt.Errorf("no client found")
  155. }
  156. // CreateExtClient - creates and saves an extclient
  157. func CreateExtClient(extclient *models.ExtClient) error {
  158. // lock because we may need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs
  159. addressLock.Lock()
  160. defer addressLock.Unlock()
  161. if len(extclient.PublicKey) == 0 {
  162. privateKey, err := wgtypes.GeneratePrivateKey()
  163. if err != nil {
  164. return err
  165. }
  166. extclient.PrivateKey = privateKey.String()
  167. extclient.PublicKey = privateKey.PublicKey().String()
  168. } else if len(extclient.PrivateKey) == 0 && len(extclient.PublicKey) > 0 {
  169. extclient.PrivateKey = "[ENTER PRIVATE KEY]"
  170. }
  171. if extclient.ExtraAllowedIPs == nil {
  172. extclient.ExtraAllowedIPs = []string{}
  173. }
  174. parentNetwork, err := GetNetwork(extclient.Network)
  175. if err != nil {
  176. return err
  177. }
  178. if extclient.Address == "" {
  179. if parentNetwork.IsIPv4 == "yes" {
  180. newAddress, err := UniqueAddress(extclient.Network, true)
  181. if err != nil {
  182. return err
  183. }
  184. extclient.Address = newAddress.String()
  185. }
  186. }
  187. if extclient.Address6 == "" {
  188. if parentNetwork.IsIPv6 == "yes" {
  189. addr6, err := UniqueAddress6(extclient.Network, true)
  190. if err != nil {
  191. return err
  192. }
  193. extclient.Address6 = addr6.String()
  194. }
  195. }
  196. if extclient.ClientID == "" {
  197. extclient.ClientID = models.GenerateNodeName()
  198. }
  199. extclient.LastModified = time.Now().Unix()
  200. return SaveExtClient(extclient)
  201. }
  202. // SaveExtClient - saves an ext client to database
  203. func SaveExtClient(extclient *models.ExtClient) error {
  204. key, err := GetRecordKey(extclient.ClientID, extclient.Network)
  205. if err != nil {
  206. return err
  207. }
  208. data, err := json.Marshal(&extclient)
  209. if err != nil {
  210. return err
  211. }
  212. if err = database.Insert(key, string(data), database.EXT_CLIENT_TABLE_NAME); err != nil {
  213. return err
  214. }
  215. storeExtClientInCache(key, *extclient)
  216. return SetNetworkNodesLastModified(extclient.Network)
  217. }
  218. // UpdateExtClient - updates an ext client with new values
  219. func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) models.ExtClient {
  220. new := *old
  221. new.ClientID = update.ClientID
  222. if update.PublicKey != "" && old.PublicKey != update.PublicKey {
  223. new.PublicKey = update.PublicKey
  224. }
  225. if update.DNS != old.DNS {
  226. new.DNS = update.DNS
  227. }
  228. if update.Enabled != old.Enabled {
  229. new.Enabled = update.Enabled
  230. }
  231. new.ExtraAllowedIPs = update.ExtraAllowedIPs
  232. if update.DeniedACLs != nil && !reflect.DeepEqual(old.DeniedACLs, update.DeniedACLs) {
  233. new.DeniedACLs = update.DeniedACLs
  234. }
  235. return new
  236. }
  237. // GetExtClientsByID - gets the clients of attached gateway
  238. func GetExtClientsByID(nodeid, network string) ([]models.ExtClient, error) {
  239. var result []models.ExtClient
  240. currentClients, err := GetNetworkExtClients(network)
  241. if err != nil {
  242. return result, err
  243. }
  244. for i := range currentClients {
  245. if currentClients[i].IngressGatewayID == nodeid {
  246. result = append(result, currentClients[i])
  247. }
  248. }
  249. return result, nil
  250. }
  251. // GetAllExtClients - gets all ext clients from DB
  252. func GetAllExtClients() ([]models.ExtClient, error) {
  253. var clients = []models.ExtClient{}
  254. currentNetworks, err := GetNetworks()
  255. if err != nil && database.IsEmptyRecord(err) {
  256. return clients, nil
  257. } else if err != nil {
  258. return clients, err
  259. }
  260. for i := range currentNetworks {
  261. netName := currentNetworks[i].NetID
  262. netClients, err := GetNetworkExtClients(netName)
  263. if err != nil {
  264. continue
  265. }
  266. clients = append(clients, netClients...)
  267. }
  268. return clients, nil
  269. }
  270. // ToggleExtClientConnectivity - enables or disables an ext client
  271. func ToggleExtClientConnectivity(client *models.ExtClient, enable bool) (models.ExtClient, error) {
  272. update := models.CustomExtClient{
  273. Enabled: enable,
  274. ClientID: client.ClientID,
  275. PublicKey: client.PublicKey,
  276. DNS: client.DNS,
  277. ExtraAllowedIPs: client.ExtraAllowedIPs,
  278. DeniedACLs: client.DeniedACLs,
  279. RemoteAccessClientID: client.RemoteAccessClientID,
  280. }
  281. // update in DB
  282. newClient := UpdateExtClient(client, &update)
  283. if err := DeleteExtClient(client.Network, client.ClientID); err != nil {
  284. slog.Error("failed to delete ext client during update", "id", client.ClientID, "network", client.Network, "error", err)
  285. return newClient, err
  286. }
  287. if err := SaveExtClient(&newClient); err != nil {
  288. slog.Error("failed to save updated ext client during update", "id", newClient.ClientID, "network", newClient.Network, "error", err)
  289. return newClient, err
  290. }
  291. return newClient, nil
  292. }
  293. func getExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error) {
  294. var peers []wgtypes.PeerConfig
  295. var idsAndAddr []models.IDandAddr
  296. var egressRoutes []models.EgressNetworkRoutes
  297. extPeers, err := GetNetworkExtClients(node.Network)
  298. if err != nil {
  299. return peers, idsAndAddr, egressRoutes, err
  300. }
  301. host, err := GetHost(node.HostID.String())
  302. if err != nil {
  303. return peers, idsAndAddr, egressRoutes, err
  304. }
  305. for _, extPeer := range extPeers {
  306. extPeer := extPeer
  307. if !IsClientNodeAllowed(&extPeer, peer.ID.String()) {
  308. continue
  309. }
  310. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  311. if err != nil {
  312. logger.Log(1, "error parsing ext pub key:", err.Error())
  313. continue
  314. }
  315. if host.PublicKey.String() == extPeer.PublicKey ||
  316. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  317. continue
  318. }
  319. var allowedips []net.IPNet
  320. var peer wgtypes.PeerConfig
  321. if extPeer.Address != "" {
  322. var peeraddr = net.IPNet{
  323. IP: net.ParseIP(extPeer.Address),
  324. Mask: net.CIDRMask(32, 32),
  325. }
  326. if peeraddr.IP != nil && peeraddr.Mask != nil {
  327. allowedips = append(allowedips, peeraddr)
  328. }
  329. }
  330. if extPeer.Address6 != "" {
  331. var addr6 = net.IPNet{
  332. IP: net.ParseIP(extPeer.Address6),
  333. Mask: net.CIDRMask(128, 128),
  334. }
  335. if addr6.IP != nil && addr6.Mask != nil {
  336. allowedips = append(allowedips, addr6)
  337. }
  338. }
  339. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  340. _, cidr, err := net.ParseCIDR(extraAllowedIP)
  341. if err == nil {
  342. allowedips = append(allowedips, *cidr)
  343. }
  344. }
  345. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(extPeer)...)
  346. primaryAddr := extPeer.Address
  347. if primaryAddr == "" {
  348. primaryAddr = extPeer.Address6
  349. }
  350. peer = wgtypes.PeerConfig{
  351. PublicKey: pubkey,
  352. ReplaceAllowedIPs: true,
  353. AllowedIPs: allowedips,
  354. }
  355. peers = append(peers, peer)
  356. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  357. ID: peer.PublicKey.String(),
  358. Name: extPeer.ClientID,
  359. Address: primaryAddr,
  360. IsExtClient: true,
  361. })
  362. }
  363. return peers, idsAndAddr, egressRoutes, nil
  364. }
  365. func getExtPeerEgressRoute(extPeer models.ExtClient) (egressRoutes []models.EgressNetworkRoutes) {
  366. if extPeer.Address != "" {
  367. egressRoutes = append(egressRoutes, models.EgressNetworkRoutes{
  368. NodeAddr: extPeer.AddressIPNet4(),
  369. EgressRanges: extPeer.ExtraAllowedIPs,
  370. })
  371. }
  372. if extPeer.Address6 != "" {
  373. egressRoutes = append(egressRoutes, models.EgressNetworkRoutes{
  374. NodeAddr: extPeer.AddressIPNet6(),
  375. EgressRanges: extPeer.ExtraAllowedIPs,
  376. })
  377. }
  378. return
  379. }
  380. func getExtpeersExtraRoutes(network string) (egressRoutes []models.EgressNetworkRoutes) {
  381. extPeers, err := GetNetworkExtClients(network)
  382. if err != nil {
  383. return
  384. }
  385. for _, extPeer := range extPeers {
  386. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(extPeer)...)
  387. }
  388. return
  389. }