helpers.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. //TODO: Consider restructuring this file/folder "github.com/gorilla/handlers"
  2. //It may make more sense to split into different files and not call it "helpers"
  3. package functions
  4. import (
  5. "context"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "math/rand"
  10. "net"
  11. "strings"
  12. "time"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/mongoconn"
  15. "github.com/gravitl/netmaker/servercfg"
  16. "go.mongodb.org/mongo-driver/bson"
  17. "go.mongodb.org/mongo-driver/bson/primitive"
  18. "go.mongodb.org/mongo-driver/mongo"
  19. "go.mongodb.org/mongo-driver/mongo/options"
  20. )
  21. //Takes in an arbitrary field and value for field and checks to see if any other
  22. //node has that value for the same field within the network
  23. func CreateServerToken(netID string) (string, error) {
  24. fmt.Println("Creating token.")
  25. var network models.Network
  26. var accesskey models.AccessKey
  27. network, err := GetParentNetwork(netID)
  28. if err != nil {
  29. return "", err
  30. }
  31. accesskey.Name = GenKeyName()
  32. accesskey.Value = GenKey()
  33. accesskey.Uses = 1
  34. address := "127.0.0.1:" + servercfg.GetGRPCPort()
  35. privAddr := ""
  36. if *network.IsLocal {
  37. privAddr = network.LocalRange
  38. }
  39. accessstringdec := address + "|" + netID + "|" + accesskey.Value + "|" + privAddr
  40. accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
  41. fmt.Println(" access string: " + accesskey.AccessString)
  42. network.AccessKeys = append(network.AccessKeys, accesskey)
  43. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  44. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  45. // Create filter
  46. filter := bson.M{"netid": netID}
  47. // Read update model from body request
  48. fmt.Println("Adding key to " + network.NetID)
  49. // prepare update model.
  50. update := bson.D{
  51. {"$set", bson.D{
  52. {"accesskeys", network.AccessKeys},
  53. }},
  54. }
  55. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  56. defer cancel()
  57. if errN != nil {
  58. return "", errN
  59. }
  60. return accesskey.AccessString, nil
  61. }
  62. func IsFieldUnique(network string, field string, value string) bool {
  63. var node models.Node
  64. isunique := true
  65. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  66. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  67. filter := bson.M{field: value, "network": network}
  68. err := collection.FindOne(ctx, filter).Decode(&node)
  69. defer cancel()
  70. if err != nil {
  71. return isunique
  72. }
  73. if node.Name != "" {
  74. isunique = false
  75. }
  76. return isunique
  77. }
  78. func NetworkExists(name string) (bool, error) {
  79. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  80. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  81. filter := bson.M{"netid": name}
  82. var result bson.M
  83. err := collection.FindOne(ctx, filter).Decode(&result)
  84. defer cancel()
  85. if err != nil {
  86. if err == mongo.ErrNoDocuments {
  87. return false, nil
  88. }
  89. }
  90. return true, err
  91. }
  92. //TODO: This is very inefficient (N-squared). Need to find a better way.
  93. //Takes a list of nodes in a network and iterates through
  94. //for each node, it gets a unique address. That requires checking against all other nodes once more
  95. func UpdateNetworkNodeAddresses(networkName string) error {
  96. //Connection mongoDB with mongoconn class
  97. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  98. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  99. filter := bson.M{"network": networkName}
  100. cur, err := collection.Find(ctx, filter)
  101. if err != nil {
  102. return err
  103. }
  104. defer cancel()
  105. for cur.Next(context.TODO()) {
  106. var node models.Node
  107. err := cur.Decode(&node)
  108. if err != nil {
  109. fmt.Println("error in node address assignment!")
  110. return err
  111. }
  112. ipaddr, iperr := UniqueAddress(networkName)
  113. if iperr != nil {
  114. fmt.Println("error in node address assignment!")
  115. return iperr
  116. }
  117. filter := bson.M{"macaddress": node.MacAddress}
  118. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  119. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  120. defer cancel()
  121. if errN != nil {
  122. return errN
  123. }
  124. }
  125. return err
  126. }
  127. //TODO TODO TODO!!!!!
  128. func UpdateNetworkPrivateAddresses(networkName string) error {
  129. //Connection mongoDB with mongoconn class
  130. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  131. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  132. filter := bson.M{"network": networkName}
  133. cur, err := collection.Find(ctx, filter)
  134. if err != nil {
  135. return err
  136. }
  137. defer cancel()
  138. for cur.Next(context.TODO()) {
  139. var node models.Node
  140. err := cur.Decode(&node)
  141. if err != nil {
  142. fmt.Println("error in node address assignment!")
  143. return err
  144. }
  145. ipaddr, iperr := UniqueAddress(networkName)
  146. if iperr != nil {
  147. fmt.Println("error in node address assignment!")
  148. return iperr
  149. }
  150. filter := bson.M{"macaddress": node.MacAddress}
  151. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  152. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  153. defer cancel()
  154. if errN != nil {
  155. return errN
  156. }
  157. }
  158. return err
  159. }
  160. //Checks to see if any other networks have the same name (id)
  161. func IsNetworkNameUnique(name string) (bool, error) {
  162. isunique := true
  163. dbs, err := ListNetworks()
  164. if err != nil {
  165. return false, err
  166. }
  167. for i := 0; i < len(dbs); i++ {
  168. if name == dbs[i].NetID {
  169. isunique = false
  170. }
  171. }
  172. return isunique, nil
  173. }
  174. func IsNetworkDisplayNameUnique(name string) (bool, error) {
  175. isunique := true
  176. dbs, err := ListNetworks()
  177. if err != nil {
  178. return false, err
  179. }
  180. for i := 0; i < len(dbs); i++ {
  181. if name == dbs[i].DisplayName {
  182. isunique = false
  183. }
  184. }
  185. return isunique, nil
  186. }
  187. func GetNetworkNodeNumber(networkName string) (int, error) {
  188. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  189. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  190. filter := bson.M{"network": networkName}
  191. count, err := collection.CountDocuments(ctx, filter)
  192. returncount := int(count)
  193. //not sure if this is the right way of handling this error...
  194. if err != nil {
  195. return 9999, err
  196. }
  197. defer cancel()
  198. return returncount, err
  199. }
  200. //Kind of a weird name. Should just be GetNetworks I think. Consider changing.
  201. //Anyway, returns all the networks
  202. func ListNetworks() ([]models.Network, error) {
  203. var networks []models.Network
  204. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  205. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  206. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  207. if err != nil {
  208. return networks, err
  209. }
  210. defer cancel()
  211. for cur.Next(context.TODO()) {
  212. var network models.Network
  213. err := cur.Decode(&network)
  214. if err != nil {
  215. return networks, err
  216. }
  217. // add network our array
  218. networks = append(networks, network)
  219. }
  220. if err := cur.Err(); err != nil {
  221. return networks, err
  222. }
  223. return networks, err
  224. }
  225. //Checks to see if access key is valid
  226. //Does so by checking against all keys and seeing if any have the same value
  227. //may want to hash values before comparing...consider this
  228. //TODO: No error handling!!!!
  229. func IsKeyValid(networkname string, keyvalue string) bool {
  230. network, _ := GetParentNetwork(networkname)
  231. var key models.AccessKey
  232. foundkey := false
  233. isvalid := false
  234. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  235. currentkey := network.AccessKeys[i]
  236. if currentkey.Value == keyvalue {
  237. key = currentkey
  238. foundkey = true
  239. }
  240. }
  241. if foundkey {
  242. if key.Uses > 0 {
  243. isvalid = true
  244. }
  245. }
  246. return isvalid
  247. }
  248. //TODO: Contains a fatal error return. Need to change
  249. //This just gets a network object from a network name
  250. //Should probably just be GetNetwork. kind of a dumb name.
  251. //Used in contexts where it's not the Parent network.
  252. func GetParentNetwork(networkname string) (models.Network, error) {
  253. var network models.Network
  254. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  255. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  256. filter := bson.M{"netid": networkname}
  257. err := collection.FindOne(ctx, filter).Decode(&network)
  258. defer cancel()
  259. if err != nil {
  260. return network, err
  261. }
  262. return network, nil
  263. }
  264. func IsIpNet(host string) bool {
  265. return net.ParseIP(host) != nil
  266. }
  267. //Similar to above but checks if Cidr range is valid
  268. //At least this guy's got some print statements
  269. //still not good error handling
  270. func IsIpCIDR(host string) bool {
  271. ip, ipnet, err := net.ParseCIDR(host)
  272. if err != nil {
  273. fmt.Println(err)
  274. fmt.Println("Address Range is not valid!")
  275. return false
  276. }
  277. return ip != nil && ipnet != nil
  278. }
  279. //This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
  280. func IsBase64(s string) bool {
  281. _, err := base64.StdEncoding.DecodeString(s)
  282. return err == nil
  283. }
  284. //This should probably just be called GetNode
  285. //It returns a node based on the ID of the node.
  286. //Why do we need this?
  287. //TODO: Check references. This seems unnecessary.
  288. func GetNodeObj(id primitive.ObjectID) models.Node {
  289. var node models.Node
  290. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  291. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  292. filter := bson.M{"_id": id}
  293. err := collection.FindOne(ctx, filter).Decode(&node)
  294. defer cancel()
  295. if err != nil {
  296. fmt.Println(err)
  297. fmt.Println("Did not get the node...")
  298. return node
  299. }
  300. fmt.Println("Got node " + node.Name)
  301. return node
  302. }
  303. //This checks to make sure a network name is valid.
  304. //Switch to REGEX?
  305. func NameInNetworkCharSet(name string) bool {
  306. charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
  307. for _, char := range name {
  308. if !strings.Contains(charset, strings.ToLower(string(char))) {
  309. return false
  310. }
  311. }
  312. return true
  313. }
  314. func NameInDNSCharSet(name string) bool {
  315. charset := "abcdefghijklmnopqrstuvwxyz1234567890-."
  316. for _, char := range name {
  317. if !strings.Contains(charset, strings.ToLower(string(char))) {
  318. return false
  319. }
  320. }
  321. return true
  322. }
  323. func NameInNodeCharSet(name string) bool {
  324. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  325. for _, char := range name {
  326. if !strings.Contains(charset, strings.ToLower(string(char))) {
  327. return false
  328. }
  329. }
  330. return true
  331. }
  332. //This returns a node based on its mac address.
  333. //The mac address acts as the Unique ID for nodes.
  334. //Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
  335. //It doesn't really provide a tangible benefit over a random ID
  336. func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
  337. var node models.Node
  338. filter := bson.M{"macaddress": macaddress, "network": network}
  339. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  340. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  341. err := collection.FindOne(ctx, filter).Decode(&node)
  342. defer cancel()
  343. if err != nil {
  344. return node, err
  345. }
  346. return node, nil
  347. }
  348. func GetAllExtClients() ([]models.ExtClient, error) {
  349. var extclient models.ExtClient
  350. var extclients []models.ExtClient
  351. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  352. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  353. // Filter out them ID's again
  354. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  355. if err != nil {
  356. return []models.ExtClient{}, err
  357. }
  358. defer cancel()
  359. for cur.Next(context.TODO()) {
  360. err := cur.Decode(&extclient)
  361. if err != nil {
  362. return []models.ExtClient{}, err
  363. }
  364. // add node to our array
  365. extclients = append(extclients, extclient)
  366. }
  367. //TODO: Fatal error
  368. if err := cur.Err(); err != nil {
  369. return []models.ExtClient{}, err
  370. }
  371. return extclients, nil
  372. }
  373. //This returns a unique address for a node to use
  374. //it iterates through the list of IP's in the subnet
  375. //and checks against all nodes to see if it's taken, until it finds one.
  376. //TODO: We do not handle a case where we run out of addresses.
  377. //We will need to handle that eventually
  378. func UniqueAddress(networkName string) (string, error) {
  379. var network models.Network
  380. network, err := GetParentNetwork(networkName)
  381. if err != nil {
  382. fmt.Println("UniqueAddress encountered an error")
  383. return "666", err
  384. }
  385. offset := true
  386. ip, ipnet, err := net.ParseCIDR(network.AddressRange)
  387. if err != nil {
  388. fmt.Println("UniqueAddress encountered an error")
  389. return "666", err
  390. }
  391. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  392. if offset {
  393. offset = false
  394. continue
  395. }
  396. if IsIPUnique(networkName, ip.String()) && IsIPUniqueExtClients(networkName, ip.String()) {
  397. return ip.String(), err
  398. }
  399. }
  400. //TODO
  401. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  402. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  403. }
  404. func UniqueAddress6(networkName string) (string, error) {
  405. var network models.Network
  406. network, err := GetParentNetwork(networkName)
  407. if err != nil {
  408. fmt.Println("Network Not Found")
  409. return "", err
  410. }
  411. if network.IsDualStack == nil || *network.IsDualStack == false {
  412. return "", nil
  413. }
  414. offset := true
  415. ip, ipnet, err := net.ParseCIDR(network.AddressRange6)
  416. if err != nil {
  417. fmt.Println("UniqueAddress6 encountered an error")
  418. return "666", err
  419. }
  420. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  421. if offset {
  422. offset = false
  423. continue
  424. }
  425. if IsIP6Unique(networkName, ip.String()) {
  426. return ip.String(), err
  427. }
  428. }
  429. //TODO
  430. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  431. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  432. }
  433. //generate an access key value
  434. func GenKey() string {
  435. var seededRand *rand.Rand = rand.New(
  436. rand.NewSource(time.Now().UnixNano()))
  437. length := 16
  438. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  439. b := make([]byte, length)
  440. for i := range b {
  441. b[i] = charset[seededRand.Intn(len(charset))]
  442. }
  443. return string(b)
  444. }
  445. //generate a key value
  446. //we should probably just have 1 random string generator
  447. //that can be used across all functions
  448. //have a "base string" a "length" and a "charset"
  449. func GenKeyName() string {
  450. var seededRand *rand.Rand = rand.New(
  451. rand.NewSource(time.Now().UnixNano()))
  452. length := 5
  453. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  454. b := make([]byte, length)
  455. for i := range b {
  456. b[i] = charset[seededRand.Intn(len(charset))]
  457. }
  458. return "key" + string(b)
  459. }
  460. func IsIPUniqueExtClients(network string, ip string) bool {
  461. var extclient models.ExtClient
  462. isunique := true
  463. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  464. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  465. filter := bson.M{"address": ip, "network": network}
  466. err := collection.FindOne(ctx, filter).Decode(&extclient)
  467. defer cancel()
  468. if err != nil {
  469. fmt.Println(err)
  470. return isunique
  471. }
  472. if extclient.Address == ip {
  473. isunique = false
  474. }
  475. return isunique
  476. }
  477. //checks if IP is unique in the address range
  478. //used by UniqueAddress
  479. func IsIPUnique(network string, ip string) bool {
  480. var node models.Node
  481. isunique := true
  482. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  483. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  484. filter := bson.M{"address": ip, "network": network}
  485. err := collection.FindOne(ctx, filter).Decode(&node)
  486. defer cancel()
  487. if err != nil {
  488. fmt.Println(err)
  489. return isunique
  490. }
  491. if node.Address == ip {
  492. isunique = false
  493. }
  494. return isunique
  495. }
  496. //checks if IP is unique in the address range
  497. //used by UniqueAddress
  498. func IsIP6Unique(network string, ip string) bool {
  499. var node models.Node
  500. isunique := true
  501. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  502. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  503. filter := bson.M{"address6": ip, "network": network}
  504. err := collection.FindOne(ctx, filter).Decode(&node)
  505. defer cancel()
  506. if err != nil {
  507. fmt.Println(err)
  508. return isunique
  509. }
  510. if node.Address6 == ip {
  511. isunique = false
  512. }
  513. return isunique
  514. }
  515. //called once key has been used by createNode
  516. //reduces value by one and deletes if necessary
  517. func DecrimentKey(networkName string, keyvalue string) {
  518. var network models.Network
  519. network, err := GetParentNetwork(networkName)
  520. if err != nil {
  521. return
  522. }
  523. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  524. currentkey := network.AccessKeys[i]
  525. if currentkey.Value == keyvalue {
  526. network.AccessKeys[i].Uses--
  527. if network.AccessKeys[i].Uses < 1 {
  528. //this is the part where it will call the delete
  529. //not sure if there's edge cases I'm missing
  530. DeleteKey(network, i)
  531. return
  532. }
  533. }
  534. }
  535. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  536. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  537. filter := bson.M{"netid": network.NetID}
  538. update := bson.D{
  539. {"$set", bson.D{
  540. {"accesskeys", network.AccessKeys},
  541. }},
  542. }
  543. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  544. defer cancel()
  545. if errN != nil {
  546. return
  547. }
  548. }
  549. //takes the logic from controllers.deleteKey
  550. func DeleteKey(network models.Network, i int) {
  551. network.AccessKeys = append(network.AccessKeys[:i],
  552. network.AccessKeys[i+1:]...)
  553. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  554. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  555. // Create filter
  556. filter := bson.M{"netid": network.NetID}
  557. // prepare update model.
  558. update := bson.D{
  559. {"$set", bson.D{
  560. {"accesskeys", network.AccessKeys},
  561. }},
  562. }
  563. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  564. defer cancel()
  565. if errN != nil {
  566. return
  567. }
  568. }
  569. //increments an IP over the previous
  570. func Inc(ip net.IP) {
  571. for j := len(ip) - 1; j >= 0; j-- {
  572. ip[j]++
  573. if ip[j] > 0 {
  574. break
  575. }
  576. }
  577. }
  578. func GetAllNodes() ([]models.ReturnNode, error) {
  579. var node models.ReturnNode
  580. var nodes []models.ReturnNode
  581. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  582. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  583. // Filter out them ID's again
  584. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  585. if err != nil {
  586. return []models.ReturnNode{}, err
  587. }
  588. defer cancel()
  589. for cur.Next(context.TODO()) {
  590. err := cur.Decode(&node)
  591. if err != nil {
  592. return []models.ReturnNode{}, err
  593. }
  594. // add node to our array
  595. nodes = append(nodes, node)
  596. }
  597. //TODO: Fatal error
  598. if err := cur.Err(); err != nil {
  599. return []models.ReturnNode{}, err
  600. }
  601. return nodes, nil
  602. }