aes_gcm_storage.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package storage
  17. import (
  18. "crypto/aes"
  19. "crypto/cipher"
  20. "crypto/rand"
  21. "encoding/json"
  22. "io"
  23. "os"
  24. "github.com/ethereum/go-ethereum/log"
  25. )
  26. type storedCredential struct {
  27. // The iv
  28. Iv []byte `json:"iv"`
  29. // The ciphertext
  30. CipherText []byte `json:"c"`
  31. }
  32. // AESEncryptedStorage is a storage type which is backed by a json-file. The json-file contains
  33. // key-value mappings, where the keys are _not_ encrypted, only the values are.
  34. type AESEncryptedStorage struct {
  35. // File to read/write credentials
  36. filename string
  37. // Key stored in base64
  38. key []byte
  39. }
  40. // NewAESEncryptedStorage creates a new encrypted storage backed by the given file/key
  41. func NewAESEncryptedStorage(filename string, key []byte) *AESEncryptedStorage {
  42. return &AESEncryptedStorage{
  43. filename: filename,
  44. key: key,
  45. }
  46. }
  47. // Put stores a value by key. 0-length keys results in noop.
  48. func (s *AESEncryptedStorage) Put(key, value string) {
  49. if len(key) == 0 {
  50. return
  51. }
  52. data, err := s.readEncryptedStorage()
  53. if err != nil {
  54. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  55. return
  56. }
  57. ciphertext, iv, err := encrypt(s.key, []byte(value), []byte(key))
  58. if err != nil {
  59. log.Warn("Failed to encrypt entry", "err", err)
  60. return
  61. }
  62. encrypted := storedCredential{Iv: iv, CipherText: ciphertext}
  63. data[key] = encrypted
  64. if err = s.writeEncryptedStorage(data); err != nil {
  65. log.Warn("Failed to write entry", "err", err)
  66. }
  67. }
  68. // Get returns the previously stored value, or an error if it does not exist or
  69. // key is of 0-length.
  70. func (s *AESEncryptedStorage) Get(key string) (string, error) {
  71. if len(key) == 0 {
  72. return "", ErrZeroKey
  73. }
  74. data, err := s.readEncryptedStorage()
  75. if err != nil {
  76. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  77. return "", err
  78. }
  79. encrypted, exist := data[key]
  80. if !exist {
  81. log.Warn("Key does not exist", "key", key)
  82. return "", ErrNotFound
  83. }
  84. entry, err := decrypt(s.key, encrypted.Iv, encrypted.CipherText, []byte(key))
  85. if err != nil {
  86. log.Warn("Failed to decrypt key", "key", key)
  87. return "", err
  88. }
  89. return string(entry), nil
  90. }
  91. // Del removes a key-value pair. If the key doesn't exist, the method is a noop.
  92. func (s *AESEncryptedStorage) Del(key string) {
  93. data, err := s.readEncryptedStorage()
  94. if err != nil {
  95. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  96. return
  97. }
  98. delete(data, key)
  99. if err = s.writeEncryptedStorage(data); err != nil {
  100. log.Warn("Failed to write entry", "err", err)
  101. }
  102. }
  103. // readEncryptedStorage reads the file with encrypted creds
  104. func (s *AESEncryptedStorage) readEncryptedStorage() (map[string]storedCredential, error) {
  105. creds := make(map[string]storedCredential)
  106. raw, err := os.ReadFile(s.filename)
  107. if err != nil {
  108. if os.IsNotExist(err) {
  109. // Doesn't exist yet
  110. return creds, nil
  111. }
  112. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  113. }
  114. if err = json.Unmarshal(raw, &creds); err != nil {
  115. log.Warn("Failed to unmarshal encrypted storage", "err", err, "file", s.filename)
  116. return nil, err
  117. }
  118. return creds, nil
  119. }
  120. // writeEncryptedStorage write the file with encrypted creds
  121. func (s *AESEncryptedStorage) writeEncryptedStorage(creds map[string]storedCredential) error {
  122. raw, err := json.Marshal(creds)
  123. if err != nil {
  124. return err
  125. }
  126. if err = os.WriteFile(s.filename, raw, 0600); err != nil {
  127. return err
  128. }
  129. return nil
  130. }
  131. // encrypt encrypts plaintext with the given key, with additional data
  132. // The 'additionalData' is used to place the (plaintext) KV-store key into the V,
  133. // to prevent the possibility to alter a K, or swap two entries in the KV store with each other.
  134. func encrypt(key []byte, plaintext []byte, additionalData []byte) ([]byte, []byte, error) {
  135. block, err := aes.NewCipher(key)
  136. if err != nil {
  137. return nil, nil, err
  138. }
  139. aesgcm, err := cipher.NewGCM(block)
  140. if err != nil {
  141. return nil, nil, err
  142. }
  143. nonce := make([]byte, aesgcm.NonceSize())
  144. if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
  145. return nil, nil, err
  146. }
  147. ciphertext := aesgcm.Seal(nil, nonce, plaintext, additionalData)
  148. return ciphertext, nonce, nil
  149. }
  150. func decrypt(key []byte, nonce []byte, ciphertext []byte, additionalData []byte) ([]byte, error) {
  151. block, err := aes.NewCipher(key)
  152. if err != nil {
  153. return nil, err
  154. }
  155. aesgcm, err := cipher.NewGCM(block)
  156. if err != nil {
  157. return nil, err
  158. }
  159. plaintext, err := aesgcm.Open(nil, nonce, ciphertext, additionalData)
  160. if err != nil {
  161. return nil, err
  162. }
  163. return plaintext, nil
  164. }