passphrase.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. // Copyright 2014 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. /*
  17. This key store behaves as KeyStorePlain with the difference that
  18. the private key is encrypted and on disk uses another JSON encoding.
  19. The crypto is documented at https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
  20. */
  21. package keystore
  22. import (
  23. "bytes"
  24. "crypto/aes"
  25. "crypto/rand"
  26. "crypto/sha256"
  27. "encoding/hex"
  28. "encoding/json"
  29. "fmt"
  30. "io"
  31. "os"
  32. "path/filepath"
  33. "github.com/ethereum/go-ethereum/accounts"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/common/math"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/google/uuid"
  38. "golang.org/x/crypto/pbkdf2"
  39. "golang.org/x/crypto/scrypt"
  40. )
  41. const (
  42. keyHeaderKDF = "scrypt"
  43. // StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB
  44. // memory and taking approximately 1s CPU time on a modern processor.
  45. StandardScryptN = 1 << 18
  46. // StandardScryptP is the P parameter of Scrypt encryption algorithm, using 256MB
  47. // memory and taking approximately 1s CPU time on a modern processor.
  48. StandardScryptP = 1
  49. // LightScryptN is the N parameter of Scrypt encryption algorithm, using 4MB
  50. // memory and taking approximately 100ms CPU time on a modern processor.
  51. LightScryptN = 1 << 12
  52. // LightScryptP is the P parameter of Scrypt encryption algorithm, using 4MB
  53. // memory and taking approximately 100ms CPU time on a modern processor.
  54. LightScryptP = 6
  55. scryptR = 8
  56. scryptDKLen = 32
  57. )
  58. type keyStorePassphrase struct {
  59. keysDirPath string
  60. scryptN int
  61. scryptP int
  62. // skipKeyFileVerification disables the security-feature which does
  63. // reads and decrypts any newly created keyfiles. This should be 'false' in all
  64. // cases except tests -- setting this to 'true' is not recommended.
  65. skipKeyFileVerification bool
  66. }
  67. func (ks keyStorePassphrase) GetKey(addr common.Address, filename, auth string) (*Key, error) {
  68. // Load the key from the keystore and decrypt its contents
  69. keyjson, err := os.ReadFile(filename)
  70. if err != nil {
  71. return nil, err
  72. }
  73. key, err := DecryptKey(keyjson, auth)
  74. if err != nil {
  75. return nil, err
  76. }
  77. // Make sure we're really operating on the requested key (no swap attacks)
  78. if key.Address != addr {
  79. return nil, fmt.Errorf("key content mismatch: have account %x, want %x", key.Address, addr)
  80. }
  81. return key, nil
  82. }
  83. // StoreKey generates a key, encrypts with 'auth' and stores in the given directory
  84. func StoreKey(dir, auth string, scryptN, scryptP int) (accounts.Account, error) {
  85. _, a, err := storeNewKey(&keyStorePassphrase{dir, scryptN, scryptP, false}, rand.Reader, auth)
  86. return a, err
  87. }
  88. func (ks keyStorePassphrase) StoreKey(filename string, key *Key, auth string) error {
  89. keyjson, err := EncryptKey(key, auth, ks.scryptN, ks.scryptP)
  90. if err != nil {
  91. return err
  92. }
  93. // Write into temporary file
  94. tmpName, err := writeTemporaryKeyFile(filename, keyjson)
  95. if err != nil {
  96. return err
  97. }
  98. if !ks.skipKeyFileVerification {
  99. // Verify that we can decrypt the file with the given password.
  100. _, err = ks.GetKey(key.Address, tmpName, auth)
  101. if err != nil {
  102. msg := "An error was encountered when saving and verifying the keystore file. \n" +
  103. "This indicates that the keystore is corrupted. \n" +
  104. "The corrupted file is stored at \n%v\n" +
  105. "Please file a ticket at:\n\n" +
  106. "https://github.com/ethereum/go-ethereum/issues." +
  107. "The error was : %s"
  108. //lint:ignore ST1005 This is a message for the user
  109. return fmt.Errorf(msg, tmpName, err)
  110. }
  111. }
  112. return os.Rename(tmpName, filename)
  113. }
  114. func (ks keyStorePassphrase) JoinPath(filename string) string {
  115. if filepath.IsAbs(filename) {
  116. return filename
  117. }
  118. return filepath.Join(ks.keysDirPath, filename)
  119. }
  120. // Encryptdata encrypts the data given as 'data' with the password 'auth'.
  121. func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) {
  122. salt := make([]byte, 32)
  123. if _, err := io.ReadFull(rand.Reader, salt); err != nil {
  124. panic("reading from crypto/rand failed: " + err.Error())
  125. }
  126. derivedKey, err := scrypt.Key(auth, salt, scryptN, scryptR, scryptP, scryptDKLen)
  127. if err != nil {
  128. return CryptoJSON{}, err
  129. }
  130. encryptKey := derivedKey[:16]
  131. iv := make([]byte, aes.BlockSize) // 16
  132. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  133. panic("reading from crypto/rand failed: " + err.Error())
  134. }
  135. cipherText, err := aesCTRXOR(encryptKey, data, iv)
  136. if err != nil {
  137. return CryptoJSON{}, err
  138. }
  139. mac := crypto.Keccak256(derivedKey[16:32], cipherText)
  140. scryptParamsJSON := make(map[string]interface{}, 5)
  141. scryptParamsJSON["n"] = scryptN
  142. scryptParamsJSON["r"] = scryptR
  143. scryptParamsJSON["p"] = scryptP
  144. scryptParamsJSON["dklen"] = scryptDKLen
  145. scryptParamsJSON["salt"] = hex.EncodeToString(salt)
  146. cipherParamsJSON := cipherparamsJSON{
  147. IV: hex.EncodeToString(iv),
  148. }
  149. cryptoStruct := CryptoJSON{
  150. Cipher: "aes-128-ctr",
  151. CipherText: hex.EncodeToString(cipherText),
  152. CipherParams: cipherParamsJSON,
  153. KDF: keyHeaderKDF,
  154. KDFParams: scryptParamsJSON,
  155. MAC: hex.EncodeToString(mac),
  156. }
  157. return cryptoStruct, nil
  158. }
  159. // EncryptKey encrypts a key using the specified scrypt parameters into a json
  160. // blob that can be decrypted later on.
  161. func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) {
  162. keyBytes := math.PaddedBigBytes(key.PrivateKey.D, 32)
  163. cryptoStruct, err := EncryptDataV3(keyBytes, []byte(auth), scryptN, scryptP)
  164. if err != nil {
  165. return nil, err
  166. }
  167. encryptedKeyJSONV3 := encryptedKeyJSONV3{
  168. hex.EncodeToString(key.Address[:]),
  169. cryptoStruct,
  170. key.Id.String(),
  171. version,
  172. }
  173. return json.Marshal(encryptedKeyJSONV3)
  174. }
  175. // DecryptKey decrypts a key from a json blob, returning the private key itself.
  176. func DecryptKey(keyjson []byte, auth string) (*Key, error) {
  177. // Parse the json into a simple map to fetch the key version
  178. m := make(map[string]interface{})
  179. if err := json.Unmarshal(keyjson, &m); err != nil {
  180. return nil, err
  181. }
  182. // Depending on the version try to parse one way or another
  183. var (
  184. keyBytes, keyId []byte
  185. err error
  186. )
  187. if version, ok := m["version"].(string); ok && version == "1" {
  188. k := new(encryptedKeyJSONV1)
  189. if err := json.Unmarshal(keyjson, k); err != nil {
  190. return nil, err
  191. }
  192. keyBytes, keyId, err = decryptKeyV1(k, auth)
  193. } else {
  194. k := new(encryptedKeyJSONV3)
  195. if err := json.Unmarshal(keyjson, k); err != nil {
  196. return nil, err
  197. }
  198. keyBytes, keyId, err = decryptKeyV3(k, auth)
  199. }
  200. // Handle any decryption errors and return the key
  201. if err != nil {
  202. return nil, err
  203. }
  204. key := crypto.ToECDSAUnsafe(keyBytes)
  205. id, err := uuid.FromBytes(keyId)
  206. if err != nil {
  207. return nil, err
  208. }
  209. return &Key{
  210. Id: id,
  211. Address: crypto.PubkeyToAddress(key.PublicKey),
  212. PrivateKey: key,
  213. }, nil
  214. }
  215. func DecryptDataV3(cryptoJson CryptoJSON, auth string) ([]byte, error) {
  216. if cryptoJson.Cipher != "aes-128-ctr" {
  217. return nil, fmt.Errorf("cipher not supported: %v", cryptoJson.Cipher)
  218. }
  219. mac, err := hex.DecodeString(cryptoJson.MAC)
  220. if err != nil {
  221. return nil, err
  222. }
  223. iv, err := hex.DecodeString(cryptoJson.CipherParams.IV)
  224. if err != nil {
  225. return nil, err
  226. }
  227. cipherText, err := hex.DecodeString(cryptoJson.CipherText)
  228. if err != nil {
  229. return nil, err
  230. }
  231. derivedKey, err := getKDFKey(cryptoJson, auth)
  232. if err != nil {
  233. return nil, err
  234. }
  235. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  236. if !bytes.Equal(calculatedMAC, mac) {
  237. return nil, ErrDecrypt
  238. }
  239. plainText, err := aesCTRXOR(derivedKey[:16], cipherText, iv)
  240. if err != nil {
  241. return nil, err
  242. }
  243. return plainText, err
  244. }
  245. func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byte, keyId []byte, err error) {
  246. if keyProtected.Version != version {
  247. return nil, nil, fmt.Errorf("version not supported: %v", keyProtected.Version)
  248. }
  249. keyUUID, err := uuid.Parse(keyProtected.Id)
  250. if err != nil {
  251. return nil, nil, err
  252. }
  253. keyId = keyUUID[:]
  254. plainText, err := DecryptDataV3(keyProtected.Crypto, auth)
  255. if err != nil {
  256. return nil, nil, err
  257. }
  258. return plainText, keyId, err
  259. }
  260. func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
  261. keyUUID, err := uuid.Parse(keyProtected.Id)
  262. if err != nil {
  263. return nil, nil, err
  264. }
  265. keyId = keyUUID[:]
  266. mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
  267. if err != nil {
  268. return nil, nil, err
  269. }
  270. iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
  271. if err != nil {
  272. return nil, nil, err
  273. }
  274. cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
  275. if err != nil {
  276. return nil, nil, err
  277. }
  278. derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
  279. if err != nil {
  280. return nil, nil, err
  281. }
  282. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  283. if !bytes.Equal(calculatedMAC, mac) {
  284. return nil, nil, ErrDecrypt
  285. }
  286. plainText, err := aesCBCDecrypt(crypto.Keccak256(derivedKey[:16])[:16], cipherText, iv)
  287. if err != nil {
  288. return nil, nil, err
  289. }
  290. return plainText, keyId, err
  291. }
  292. func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) {
  293. authArray := []byte(auth)
  294. salt, err := hex.DecodeString(cryptoJSON.KDFParams["salt"].(string))
  295. if err != nil {
  296. return nil, err
  297. }
  298. dkLen := ensureInt(cryptoJSON.KDFParams["dklen"])
  299. if cryptoJSON.KDF == keyHeaderKDF {
  300. n := ensureInt(cryptoJSON.KDFParams["n"])
  301. r := ensureInt(cryptoJSON.KDFParams["r"])
  302. p := ensureInt(cryptoJSON.KDFParams["p"])
  303. return scrypt.Key(authArray, salt, n, r, p, dkLen)
  304. } else if cryptoJSON.KDF == "pbkdf2" {
  305. c := ensureInt(cryptoJSON.KDFParams["c"])
  306. prf := cryptoJSON.KDFParams["prf"].(string)
  307. if prf != "hmac-sha256" {
  308. return nil, fmt.Errorf("unsupported PBKDF2 PRF: %s", prf)
  309. }
  310. key := pbkdf2.Key(authArray, salt, c, dkLen, sha256.New)
  311. return key, nil
  312. }
  313. return nil, fmt.Errorf("unsupported KDF: %s", cryptoJSON.KDF)
  314. }
  315. // TODO: can we do without this when unmarshalling dynamic JSON?
  316. // why do integers in KDF params end up as float64 and not int after
  317. // unmarshal?
  318. func ensureInt(x interface{}) int {
  319. res, ok := x.(int)
  320. if !ok {
  321. res = int(x.(float64))
  322. }
  323. return res
  324. }