accesskeys.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package logic
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "math/big"
  8. "strings"
  9. "sync"
  10. "github.com/go-playground/validator/v10"
  11. "github.com/gravitl/netmaker/database"
  12. "github.com/gravitl/netmaker/logger"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/servercfg"
  15. )
  16. const (
  17. charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  18. )
  19. // CreateAccessKey - create access key
  20. func CreateAccessKey(accesskey models.AccessKey, network models.Network) (models.AccessKey, error) {
  21. if accesskey.Name == "" {
  22. accesskey.Name = genKeyName()
  23. }
  24. if accesskey.Value == "" {
  25. accesskey.Value = GenKey()
  26. }
  27. if accesskey.Uses == 0 {
  28. accesskey.Uses = 1
  29. }
  30. checkkeys, err := GetKeys(network.NetID)
  31. if err != nil {
  32. return models.AccessKey{}, errors.New("could not retrieve network keys")
  33. }
  34. for _, key := range checkkeys {
  35. if key.Name == accesskey.Name {
  36. return models.AccessKey{}, errors.New("duplicate AccessKey Name")
  37. }
  38. }
  39. privAddr := ""
  40. if network.IsLocal != "" {
  41. privAddr = network.LocalRange
  42. }
  43. netID := network.NetID
  44. var accessToken models.AccessToken
  45. s := servercfg.GetServerConfig()
  46. servervals := models.ServerConfig{
  47. GRPCConnString: s.GRPCConnString,
  48. GRPCSSL: s.GRPCSSL,
  49. Server: s.Server,
  50. APIConnString: s.APIConnString,
  51. }
  52. accessToken.ServerConfig = servervals
  53. accessToken.ClientConfig.Network = netID
  54. accessToken.ClientConfig.Key = accesskey.Value
  55. accessToken.ClientConfig.LocalRange = privAddr
  56. tokenjson, err := json.Marshal(accessToken)
  57. if err != nil {
  58. return accesskey, err
  59. }
  60. accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(tokenjson))
  61. //validate accesskey
  62. v := validator.New()
  63. err = v.Struct(accesskey)
  64. if err != nil {
  65. for _, e := range err.(validator.ValidationErrors) {
  66. logger.Log(1, "validator", e.Error())
  67. }
  68. return models.AccessKey{}, err
  69. }
  70. network.AccessKeys = append(network.AccessKeys, accesskey)
  71. data, err := json.Marshal(&network)
  72. if err != nil {
  73. return models.AccessKey{}, err
  74. }
  75. if err = database.Insert(network.NetID, string(data), database.NETWORKS_TABLE_NAME); err != nil {
  76. return models.AccessKey{}, err
  77. }
  78. return accesskey, nil
  79. }
  80. // DeleteKey - deletes a key
  81. func DeleteKey(keyname, netname string) error {
  82. network, err := GetParentNetwork(netname)
  83. if err != nil {
  84. return err
  85. }
  86. //basically, turn the list of access keys into the list of access keys before and after the item
  87. //have not done any error handling for if there's like...1 item. I think it works? need to test.
  88. found := false
  89. var updatedKeys []models.AccessKey
  90. for _, currentkey := range network.AccessKeys {
  91. if currentkey.Name == keyname {
  92. found = true
  93. } else {
  94. updatedKeys = append(updatedKeys, currentkey)
  95. }
  96. }
  97. if !found {
  98. return errors.New("key " + keyname + " does not exist")
  99. }
  100. network.AccessKeys = updatedKeys
  101. data, err := json.Marshal(&network)
  102. if err != nil {
  103. return err
  104. }
  105. if err := database.Insert(network.NetID, string(data), database.NETWORKS_TABLE_NAME); err != nil {
  106. return err
  107. }
  108. return nil
  109. }
  110. // GetKeys - fetches keys for network
  111. func GetKeys(net string) ([]models.AccessKey, error) {
  112. record, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, net)
  113. if err != nil {
  114. return []models.AccessKey{}, err
  115. }
  116. network, err := ParseNetwork(record)
  117. if err != nil {
  118. return []models.AccessKey{}, err
  119. }
  120. return network.AccessKeys, nil
  121. }
  122. // DecrimentKey - decriments key uses
  123. func DecrimentKey(networkName string, keyvalue string) {
  124. var network models.Network
  125. network, err := GetParentNetwork(networkName)
  126. if err != nil || network.IsComms == "yes" {
  127. return
  128. }
  129. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  130. currentkey := network.AccessKeys[i]
  131. if currentkey.Value == keyvalue {
  132. network.AccessKeys[i].Uses--
  133. if network.AccessKeys[i].Uses < 1 {
  134. network.AccessKeys = append(network.AccessKeys[:i],
  135. network.AccessKeys[i+1:]...)
  136. break
  137. }
  138. }
  139. }
  140. if newNetworkData, err := json.Marshal(&network); err != nil {
  141. logger.Log(2, "failed to decrement key")
  142. return
  143. } else {
  144. database.Insert(network.NetID, string(newNetworkData), database.NETWORKS_TABLE_NAME)
  145. }
  146. }
  147. // IsKeyValid - check if key is valid
  148. func IsKeyValid(networkname string, keyvalue string) bool {
  149. network, err := GetParentNetwork(networkname)
  150. if err != nil {
  151. return false
  152. }
  153. accesskeys := network.AccessKeys
  154. if network.IsComms == "yes" {
  155. accesskeys = getAllAccessKeys()
  156. }
  157. var key models.AccessKey
  158. foundkey := false
  159. isvalid := false
  160. for i := len(accesskeys) - 1; i >= 0; i-- {
  161. currentkey := accesskeys[i]
  162. if currentkey.Value == keyvalue {
  163. key = currentkey
  164. foundkey = true
  165. }
  166. }
  167. if foundkey {
  168. if key.Uses > 0 {
  169. isvalid = true
  170. }
  171. }
  172. return isvalid
  173. }
  174. // RemoveKeySensitiveInfo - remove sensitive key info
  175. func RemoveKeySensitiveInfo(keys []models.AccessKey) []models.AccessKey {
  176. var returnKeys []models.AccessKey
  177. for _, key := range keys {
  178. key.Value = models.PLACEHOLDER_KEY_TEXT
  179. key.AccessString = models.PLACEHOLDER_TOKEN_TEXT
  180. returnKeys = append(returnKeys, key)
  181. }
  182. return returnKeys
  183. }
  184. const (
  185. maxr string = "ff578f57c15bb743beaa77d27637e02b598dffa9aebd15889187fe6eb3bdca516c3fa1a52eabef31f33b4b8c2e5b5524f1aa4f3329393912f40dbbe23d7f39723e0be05b6696b11f8eea0abe365a11d9f2735ac7e5b4e015ab19b35b84893685b37a9a0a62a566d6571d7e00d4241687f5c804f37cde9bf311c0781f51cc007c5a01a94f6cfcecea640b8e9ab7bd43e73e5df5d0e1eeb4d9b6cc44be67b7cad80808b17869561b579ffe0bbdeca5c83139e458000000000000000000000000000000000000000000000000000000000000000"
  186. )
  187. var (
  188. uno sync.Once
  189. maxentropy *big.Int
  190. )
  191. func init() {
  192. uno.Do(func() {
  193. maxentropy, _ = new(big.Int).SetString(maxr, 16)
  194. })
  195. }
  196. // == private methods ==
  197. func genKeyName() string {
  198. entropy, _ := rand.Int(rand.Reader, maxentropy)
  199. return strings.Join([]string{"key", entropy.Text(16)[:16]}, "-")
  200. }
  201. func GenKey() string {
  202. entropy, _ := rand.Int(rand.Reader, maxentropy)
  203. return entropy.Text(16)[:16]
  204. }
  205. func getAllAccessKeys() []models.AccessKey {
  206. var accesskeys = make([]models.AccessKey, 0)
  207. networks, err := GetNetworks()
  208. if err != nil {
  209. return accesskeys
  210. }
  211. for i := range networks {
  212. accesskeys = append(accesskeys, networks[i].AccessKeys...)
  213. }
  214. return accesskeys
  215. }