keystore_passphrase.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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/common"
  35. "github.com/ethereum/go-ethereum/common/math"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/pborman/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 := ioutil.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) (common.Address, error) {
  85. _, a, err := storeNewKey(&keyStorePassphrase{dir, scryptN, scryptP, false}, rand.Reader, auth)
  86. return a.Address, 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. return fmt.Errorf(msg, tmpName, err)
  109. }
  110. }
  111. return os.Rename(tmpName, filename)
  112. }
  113. func (ks keyStorePassphrase) JoinPath(filename string) string {
  114. if filepath.IsAbs(filename) {
  115. return filename
  116. }
  117. return filepath.Join(ks.keysDirPath, filename)
  118. }
  119. // Encryptdata encrypts the data given as 'data' with the password 'auth'.
  120. func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) {
  121. salt := make([]byte, 32)
  122. if _, err := io.ReadFull(rand.Reader, salt); err != nil {
  123. panic("reading from crypto/rand failed: " + err.Error())
  124. }
  125. derivedKey, err := scrypt.Key(auth, salt, scryptN, scryptR, scryptP, scryptDKLen)
  126. if err != nil {
  127. return CryptoJSON{}, err
  128. }
  129. encryptKey := derivedKey[:16]
  130. iv := make([]byte, aes.BlockSize) // 16
  131. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  132. panic("reading from crypto/rand failed: " + err.Error())
  133. }
  134. cipherText, err := aesCTRXOR(encryptKey, data, iv)
  135. if err != nil {
  136. return CryptoJSON{}, err
  137. }
  138. mac := crypto.Keccak256(derivedKey[16:32], cipherText)
  139. scryptParamsJSON := make(map[string]interface{}, 5)
  140. scryptParamsJSON["n"] = scryptN
  141. scryptParamsJSON["r"] = scryptR
  142. scryptParamsJSON["p"] = scryptP
  143. scryptParamsJSON["dklen"] = scryptDKLen
  144. scryptParamsJSON["salt"] = hex.EncodeToString(salt)
  145. cipherParamsJSON := cipherparamsJSON{
  146. IV: hex.EncodeToString(iv),
  147. }
  148. cryptoStruct := CryptoJSON{
  149. Cipher: "aes-128-ctr",
  150. CipherText: hex.EncodeToString(cipherText),
  151. CipherParams: cipherParamsJSON,
  152. KDF: keyHeaderKDF,
  153. KDFParams: scryptParamsJSON,
  154. MAC: hex.EncodeToString(mac),
  155. }
  156. return cryptoStruct, nil
  157. }
  158. // EncryptKey encrypts a key using the specified scrypt parameters into a json
  159. // blob that can be decrypted later on.
  160. func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) {
  161. keyBytes := math.PaddedBigBytes(key.PrivateKey.D, 32)
  162. cryptoStruct, err := EncryptDataV3(keyBytes, []byte(auth), scryptN, scryptP)
  163. if err != nil {
  164. return nil, err
  165. }
  166. encryptedKeyJSONV3 := encryptedKeyJSONV3{
  167. hex.EncodeToString(key.Address[:]),
  168. cryptoStruct,
  169. key.Id.String(),
  170. version,
  171. }
  172. return json.Marshal(encryptedKeyJSONV3)
  173. }
  174. // DecryptKey decrypts a key from a json blob, returning the private key itself.
  175. func DecryptKey(keyjson []byte, auth string) (*Key, error) {
  176. // Parse the json into a simple map to fetch the key version
  177. m := make(map[string]interface{})
  178. if err := json.Unmarshal(keyjson, &m); err != nil {
  179. return nil, err
  180. }
  181. // Depending on the version try to parse one way or another
  182. var (
  183. keyBytes, keyId []byte
  184. err error
  185. )
  186. if version, ok := m["version"].(string); ok && version == "1" {
  187. k := new(encryptedKeyJSONV1)
  188. if err := json.Unmarshal(keyjson, k); err != nil {
  189. return nil, err
  190. }
  191. keyBytes, keyId, err = decryptKeyV1(k, auth)
  192. } else {
  193. k := new(encryptedKeyJSONV3)
  194. if err := json.Unmarshal(keyjson, k); err != nil {
  195. return nil, err
  196. }
  197. keyBytes, keyId, err = decryptKeyV3(k, auth)
  198. }
  199. // Handle any decryption errors and return the key
  200. if err != nil {
  201. return nil, err
  202. }
  203. key := crypto.ToECDSAUnsafe(keyBytes)
  204. return &Key{
  205. Id: uuid.UUID(keyId),
  206. Address: crypto.PubkeyToAddress(key.PublicKey),
  207. PrivateKey: key,
  208. }, nil
  209. }
  210. func DecryptDataV3(cryptoJson CryptoJSON, auth string) ([]byte, error) {
  211. if cryptoJson.Cipher != "aes-128-ctr" {
  212. return nil, fmt.Errorf("Cipher not supported: %v", cryptoJson.Cipher)
  213. }
  214. mac, err := hex.DecodeString(cryptoJson.MAC)
  215. if err != nil {
  216. return nil, err
  217. }
  218. iv, err := hex.DecodeString(cryptoJson.CipherParams.IV)
  219. if err != nil {
  220. return nil, err
  221. }
  222. cipherText, err := hex.DecodeString(cryptoJson.CipherText)
  223. if err != nil {
  224. return nil, err
  225. }
  226. derivedKey, err := getKDFKey(cryptoJson, auth)
  227. if err != nil {
  228. return nil, err
  229. }
  230. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  231. if !bytes.Equal(calculatedMAC, mac) {
  232. return nil, ErrDecrypt
  233. }
  234. plainText, err := aesCTRXOR(derivedKey[:16], cipherText, iv)
  235. if err != nil {
  236. return nil, err
  237. }
  238. return plainText, err
  239. }
  240. func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byte, keyId []byte, err error) {
  241. if keyProtected.Version != version {
  242. return nil, nil, fmt.Errorf("Version not supported: %v", keyProtected.Version)
  243. }
  244. keyId = uuid.Parse(keyProtected.Id)
  245. plainText, err := DecryptDataV3(keyProtected.Crypto, auth)
  246. if err != nil {
  247. return nil, nil, err
  248. }
  249. return plainText, keyId, err
  250. }
  251. func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
  252. keyId = uuid.Parse(keyProtected.Id)
  253. mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
  254. if err != nil {
  255. return nil, nil, err
  256. }
  257. iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
  258. if err != nil {
  259. return nil, nil, err
  260. }
  261. cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
  262. if err != nil {
  263. return nil, nil, err
  264. }
  265. derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
  266. if err != nil {
  267. return nil, nil, err
  268. }
  269. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  270. if !bytes.Equal(calculatedMAC, mac) {
  271. return nil, nil, ErrDecrypt
  272. }
  273. plainText, err := aesCBCDecrypt(crypto.Keccak256(derivedKey[:16])[:16], cipherText, iv)
  274. if err != nil {
  275. return nil, nil, err
  276. }
  277. return plainText, keyId, err
  278. }
  279. func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) {
  280. authArray := []byte(auth)
  281. salt, err := hex.DecodeString(cryptoJSON.KDFParams["salt"].(string))
  282. if err != nil {
  283. return nil, err
  284. }
  285. dkLen := ensureInt(cryptoJSON.KDFParams["dklen"])
  286. if cryptoJSON.KDF == keyHeaderKDF {
  287. n := ensureInt(cryptoJSON.KDFParams["n"])
  288. r := ensureInt(cryptoJSON.KDFParams["r"])
  289. p := ensureInt(cryptoJSON.KDFParams["p"])
  290. return scrypt.Key(authArray, salt, n, r, p, dkLen)
  291. } else if cryptoJSON.KDF == "pbkdf2" {
  292. c := ensureInt(cryptoJSON.KDFParams["c"])
  293. prf := cryptoJSON.KDFParams["prf"].(string)
  294. if prf != "hmac-sha256" {
  295. return nil, fmt.Errorf("Unsupported PBKDF2 PRF: %s", prf)
  296. }
  297. key := pbkdf2.Key(authArray, salt, c, dkLen, sha256.New)
  298. return key, nil
  299. }
  300. return nil, fmt.Errorf("Unsupported KDF: %s", cryptoJSON.KDF)
  301. }
  302. // TODO: can we do without this when unmarshalling dynamic JSON?
  303. // why do integers in KDF params end up as float64 and not int after
  304. // unmarshal?
  305. func ensureInt(x interface{}) int {
  306. res, ok := x.(int)
  307. if !ok {
  308. res = int(x.(float64))
  309. }
  310. return res
  311. }