helpers.go 18 KB

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