passphrase.go 11 KB

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