helpers.go 17 KB

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