helpers.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. //This returns a unique address for a node to use
  349. //it iterates through the list of IP's in the subnet
  350. //and checks against all nodes to see if it's taken, until it finds one.
  351. //TODO: We do not handle a case where we run out of addresses.
  352. //We will need to handle that eventually
  353. func UniqueAddress(networkName string) (string, error) {
  354. var network models.Network
  355. network, err := GetParentNetwork(networkName)
  356. if err != nil {
  357. fmt.Println("UniqueAddress encountered an error")
  358. return "666", err
  359. }
  360. offset := true
  361. ip, ipnet, err := net.ParseCIDR(network.AddressRange)
  362. if err != nil {
  363. fmt.Println("UniqueAddress encountered an error")
  364. return "666", err
  365. }
  366. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  367. if offset {
  368. offset = false
  369. continue
  370. }
  371. if IsIPUnique(networkName, ip.String()) {
  372. return ip.String(), err
  373. }
  374. }
  375. //TODO
  376. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  377. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  378. }
  379. func UniqueAddress6(networkName string) (string, error) {
  380. var network models.Network
  381. network, err := GetParentNetwork(networkName)
  382. if err != nil {
  383. fmt.Println("Network Not Found")
  384. return "", err
  385. }
  386. if network.IsDualStack == nil || *network.IsDualStack == false {
  387. return "", nil
  388. }
  389. offset := true
  390. ip, ipnet, err := net.ParseCIDR(network.AddressRange6)
  391. if err != nil {
  392. fmt.Println("UniqueAddress6 encountered an error")
  393. return "666", err
  394. }
  395. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  396. if offset {
  397. offset = false
  398. continue
  399. }
  400. if IsIP6Unique(networkName, ip.String()) {
  401. return ip.String(), err
  402. }
  403. }
  404. //TODO
  405. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  406. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  407. }
  408. //generate an access key value
  409. func GenKey() string {
  410. var seededRand *rand.Rand = rand.New(
  411. rand.NewSource(time.Now().UnixNano()))
  412. length := 16
  413. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  414. b := make([]byte, length)
  415. for i := range b {
  416. b[i] = charset[seededRand.Intn(len(charset))]
  417. }
  418. return string(b)
  419. }
  420. //generate a key value
  421. //we should probably just have 1 random string generator
  422. //that can be used across all functions
  423. //have a "base string" a "length" and a "charset"
  424. func GenKeyName() string {
  425. var seededRand *rand.Rand = rand.New(
  426. rand.NewSource(time.Now().UnixNano()))
  427. length := 5
  428. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  429. b := make([]byte, length)
  430. for i := range b {
  431. b[i] = charset[seededRand.Intn(len(charset))]
  432. }
  433. return "key-" + string(b)
  434. }
  435. //checks if IP is unique in the address range
  436. //used by UniqueAddress
  437. func IsIPUnique(network string, ip string) bool {
  438. var node models.Node
  439. isunique := true
  440. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  441. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  442. filter := bson.M{"address": ip, "network": network}
  443. err := collection.FindOne(ctx, filter).Decode(&node)
  444. defer cancel()
  445. if err != nil {
  446. fmt.Println(err)
  447. return isunique
  448. }
  449. if node.Address == ip {
  450. isunique = false
  451. }
  452. return isunique
  453. }
  454. //checks if IP is unique in the address range
  455. //used by UniqueAddress
  456. func IsIP6Unique(network string, ip string) bool {
  457. var node models.Node
  458. isunique := true
  459. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  460. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  461. filter := bson.M{"address6": ip, "network": network}
  462. err := collection.FindOne(ctx, filter).Decode(&node)
  463. defer cancel()
  464. if err != nil {
  465. fmt.Println(err)
  466. return isunique
  467. }
  468. if node.Address6 == ip {
  469. isunique = false
  470. }
  471. return isunique
  472. }
  473. //called once key has been used by createNode
  474. //reduces value by one and deletes if necessary
  475. func DecrimentKey(networkName string, keyvalue string) {
  476. var network models.Network
  477. network, err := GetParentNetwork(networkName)
  478. if err != nil {
  479. return
  480. }
  481. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  482. currentkey := network.AccessKeys[i]
  483. if currentkey.Value == keyvalue {
  484. network.AccessKeys[i].Uses--
  485. if network.AccessKeys[i].Uses < 1 {
  486. //this is the part where it will call the delete
  487. //not sure if there's edge cases I'm missing
  488. DeleteKey(network, i)
  489. return
  490. }
  491. }
  492. }
  493. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  494. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  495. filter := bson.M{"netid": network.NetID}
  496. update := bson.D{
  497. {"$set", bson.D{
  498. {"accesskeys", network.AccessKeys},
  499. }},
  500. }
  501. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  502. defer cancel()
  503. if errN != nil {
  504. return
  505. }
  506. }
  507. //takes the logic from controllers.deleteKey
  508. func DeleteKey(network models.Network, i int) {
  509. network.AccessKeys = append(network.AccessKeys[:i],
  510. network.AccessKeys[i+1:]...)
  511. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  512. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  513. // Create filter
  514. filter := bson.M{"netid": network.NetID}
  515. // prepare update model.
  516. update := bson.D{
  517. {"$set", bson.D{
  518. {"accesskeys", network.AccessKeys},
  519. }},
  520. }
  521. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  522. defer cancel()
  523. if errN != nil {
  524. return
  525. }
  526. }
  527. //increments an IP over the previous
  528. func Inc(ip net.IP) {
  529. for j := len(ip) - 1; j >= 0; j-- {
  530. ip[j]++
  531. if ip[j] > 0 {
  532. break
  533. }
  534. }
  535. }