crypto.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. crypto: Random number, password hashing and symmetric encryption routines for the MMGen suite
  20. """
  21. import os
  22. from collections import namedtuple
  23. from .globalvars import g
  24. from .opts import opt
  25. from .util import (
  26. msg,
  27. msg_r,
  28. dmsg,
  29. vmsg,
  30. vmsg_r,
  31. qmsg,
  32. fmt,
  33. die,
  34. make_chksum_8,
  35. compare_chksums,
  36. oneshot_warning,
  37. )
  38. mmenc_ext = 'mmenc'
  39. scramble_hash_rounds = 10
  40. salt_len = 16
  41. aesctr_iv_len = 16
  42. aesctr_dfl_iv = int.to_bytes(1,aesctr_iv_len,'big')
  43. hincog_chk_len = 8
  44. # Scrypt params: 'id_num': [N, r, p] (N is an exponent of two)
  45. # NB: hashlib.scrypt in Python (>=v3.6) supports max N value of 14. This means that
  46. # for hash presets > 3 the standalone scrypt library must be used!
  47. _hp = namedtuple('scrypt_preset',['N','r','p'])
  48. hash_presets = {
  49. '1': _hp(12, 8, 1),
  50. '2': _hp(13, 8, 4),
  51. '3': _hp(14, 8, 8),
  52. '4': _hp(15, 8, 12),
  53. '5': _hp(16, 8, 16),
  54. '6': _hp(17, 8, 20),
  55. '7': _hp(18, 8, 24),
  56. }
  57. class pwfile_reuse_warning(oneshot_warning):
  58. message = 'Reusing passphrase from file {!r} at user request'
  59. def __init__(self,fn):
  60. oneshot_warning.__init__(self,div=fn,fmt_args=[fn],reverse=True)
  61. def get_hash_params(hash_preset):
  62. if hash_preset in hash_presets:
  63. return hash_presets[hash_preset] # N,r,p
  64. else: # Shouldn't be here
  65. die(3,f"{hash_preset}: invalid 'hash_preset' value")
  66. def sha256_rounds(s,n):
  67. from hashlib import sha256
  68. for i in range(n):
  69. s = sha256(s).digest()
  70. return s
  71. def scramble_seed(seed,scramble_key):
  72. import hmac
  73. step1 = hmac.digest(seed,scramble_key,'sha256')
  74. if g.debug:
  75. msg(f'Seed: {seed.hex()!r}\nScramble key: {scramble_key}\nScrambled seed: {step1.hex()}\n')
  76. return sha256_rounds( step1, scramble_hash_rounds )
  77. def encrypt_seed(data,key,desc='seed'):
  78. return encrypt_data(data,key,desc=desc)
  79. def decrypt_seed(enc_seed,key,seed_id,key_id):
  80. vmsg_r('Checking key...')
  81. chk1 = make_chksum_8(key)
  82. if key_id:
  83. if not compare_chksums(key_id,'key ID',chk1,'computed'):
  84. msg('Incorrect passphrase or hash preset')
  85. return False
  86. dec_seed = decrypt_data(enc_seed,key,desc='seed')
  87. chk2 = make_chksum_8(dec_seed)
  88. if seed_id:
  89. if compare_chksums(seed_id,'Seed ID',chk2,'decrypted seed'):
  90. qmsg('Passphrase is OK')
  91. else:
  92. if not opt.debug:
  93. msg_r('Checking key ID...')
  94. if compare_chksums(key_id,'key ID',chk1,'computed'):
  95. msg('Key ID is correct but decryption of seed failed')
  96. else:
  97. msg('Incorrect passphrase or hash preset')
  98. vmsg('')
  99. return False
  100. # else:
  101. # qmsg(f'Generated IDs (Seed/Key): {chk2}/{chk1}')
  102. dmsg(f'Decrypted seed: {dec_seed.hex()}')
  103. return dec_seed
  104. def encrypt_data(data,key,iv=aesctr_dfl_iv,desc='data',verify=True,silent=False):
  105. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  106. from cryptography.hazmat.backends import default_backend
  107. if not silent:
  108. vmsg(f'Encrypting {desc}')
  109. c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
  110. encryptor = c.encryptor()
  111. enc_data = encryptor.update(data) + encryptor.finalize()
  112. if verify:
  113. vmsg_r(f'Performing a test decryption of the {desc}...')
  114. c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
  115. encryptor = c.encryptor()
  116. dec_data = encryptor.update(enc_data) + encryptor.finalize()
  117. if dec_data != data:
  118. die(2,f'ERROR.\nDecrypted {desc} doesn’t match original {desc}')
  119. if not silent:
  120. vmsg('done')
  121. return enc_data
  122. def decrypt_data(enc_data,key,iv=aesctr_dfl_iv,desc='data'):
  123. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  124. from cryptography.hazmat.backends import default_backend
  125. vmsg_r(f'Decrypting {desc} with key...')
  126. c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
  127. encryptor = c.encryptor()
  128. return encryptor.update(enc_data) + encryptor.finalize()
  129. def scrypt_hash_passphrase(passwd,salt,hash_preset,buflen=32):
  130. # Buflen arg is for brainwallets only, which use this function to generate
  131. # the seed directly.
  132. ps = get_hash_params(hash_preset)
  133. if isinstance(passwd,str):
  134. passwd = passwd.encode()
  135. def do_hashlib_scrypt():
  136. from hashlib import scrypt
  137. return scrypt(
  138. password = passwd,
  139. salt = salt,
  140. n = 2**ps.N,
  141. r = ps.r,
  142. p = ps.p,
  143. maxmem = 0,
  144. dklen = buflen )
  145. def do_standalone_scrypt():
  146. import scrypt
  147. return scrypt.hash(
  148. password = passwd,
  149. salt = salt,
  150. N = 2**ps.N,
  151. r = ps.r,
  152. p = ps.p,
  153. buflen = buflen )
  154. if int(hash_preset) > 3:
  155. msg_r('Hashing passphrase, please wait...')
  156. # hashlib.scrypt doesn't support N > 14 (hash preset > 3)
  157. ret = (
  158. do_standalone_scrypt() if ps.N > 14 or g.force_standalone_scrypt_module else
  159. do_hashlib_scrypt() )
  160. if int(hash_preset) > 3:
  161. msg_r('\b'*34 + ' '*34 + '\b'*34)
  162. return ret
  163. def make_key(passwd,salt,hash_preset,desc='encryption key',from_what='passphrase',verbose=False):
  164. if opt.verbose or verbose:
  165. msg_r(f"Generating {desc}{' from ' + from_what if from_what else ''}...")
  166. key = scrypt_hash_passphrase(passwd,salt,hash_preset)
  167. if opt.verbose or verbose: msg('done')
  168. dmsg(f'Key: {key.hex()}')
  169. return key
  170. def _get_random_data_from_user(uchars,desc):
  171. info1 = f"""
  172. Now we're going to gather some additional input from the keyboard to further
  173. randomize the random data {desc}.
  174. An encryption key will be created from this input, and the random data will
  175. be encrypted using the key. The resulting data is guaranteed to be at least
  176. as random as the original random data, so even if you type very predictably
  177. no harm will be done.
  178. However, to gain the maximum benefit, try making your input as random as
  179. possible. Type slowly and choose your symbols carefully. Try to use both
  180. upper and lowercase letters as well as punctuation and numerals. The timings
  181. between your keystrokes will also be used as a source of entropy, so be as
  182. random as possible in your timing as well.
  183. """
  184. info2 = f"""
  185. Please type {uchars} symbols on your keyboard. What you type will not be displayed
  186. on the screen.
  187. """
  188. msg(f'Enter {uchars} random symbols' if opt.quiet else
  189. '\n' + fmt(info1,indent=' ') +
  190. '\n' + fmt(info2) )
  191. import time
  192. from .term import get_char_raw
  193. key_data = ''
  194. time_data = []
  195. for i in range(uchars):
  196. key_data += get_char_raw(f'\rYou may begin typing. {uchars-i} symbols left: ')
  197. time_data.append(time.time())
  198. msg_r( '\r' if opt.quiet else f'\rThank you. That’s enough.{" "*18}\n\n' )
  199. time_data = [f'{t:.22f}'.rstrip('0') for t in time_data]
  200. avg_prec = sum(len(t.split('.')[1]) for t in time_data) // len(time_data)
  201. if avg_prec < g.min_time_precision:
  202. ymsg(f'WARNING: Avg. time precision of only {avg_prec} decimal points. User entropy quality is degraded!')
  203. ret = key_data + '\n' + '\n'.join(time_data)
  204. if g.debug:
  205. msg(f'USER ENTROPY (user input + keystroke timings):\n{ret}')
  206. from .ui import line_input
  207. line_input('User random data successfully acquired. Press ENTER to continue: ')
  208. return ret.encode()
  209. def get_random(length):
  210. os_rand = os.urandom(length)
  211. assert len(os_rand) == length, f'OS random number generator returned {len(os_rand)} (!= {length}) bytes!'
  212. return add_user_random(
  213. rand_bytes = os_rand,
  214. desc = 'from your operating system' )
  215. def add_user_random(
  216. rand_bytes,
  217. desc,
  218. urand = {'data':b'', 'counter':0} ):
  219. assert type(rand_bytes) == bytes, 'add_user_random_chk1'
  220. if opt.usr_randchars:
  221. if not urand['data']:
  222. from hashlib import sha256
  223. urand['data'] = sha256(_get_random_data_from_user(opt.usr_randchars,desc)).digest()
  224. # counter protects against very evil rng that might repeatedly output the same data
  225. urand['counter'] += 1
  226. os_rand = os.urandom(8)
  227. assert len(os_rand) == 8, f'OS random number generator returned {len(os_rand)} (!= 8) bytes!'
  228. import hmac
  229. key = hmac.digest(
  230. urand['data'],
  231. os_rand + int.to_bytes(urand['counter'],8,'big'),
  232. 'sha256' )
  233. msg('Encrypting random data {} with ephemeral key #{}'.format( desc, urand['counter'] ))
  234. return encrypt_data( data=rand_bytes, key=key, desc=desc, verify=False, silent=True )
  235. else:
  236. return rand_bytes
  237. def get_hash_preset_from_user(
  238. old_preset = g.dfl_hash_preset,
  239. data_desc = 'data',
  240. prompt = None ):
  241. prompt = prompt or (
  242. f'Enter hash preset for {data_desc},\n' +
  243. f'or hit ENTER to accept the default value ({old_preset!r}): ' )
  244. from .ui import line_input
  245. while True:
  246. ret = line_input(prompt)
  247. if ret:
  248. if ret in hash_presets:
  249. return ret
  250. else:
  251. msg('Invalid input. Valid choices are {}'.format(', '.join(hash_presets)))
  252. else:
  253. return old_preset
  254. def get_new_passphrase(data_desc,hash_preset,passwd_file,pw_desc='passphrase'):
  255. message = f"""
  256. You must choose a passphrase to encrypt your {data_desc} with.
  257. A key will be generated from your passphrase using a hash preset of '{hash_preset}'.
  258. Please note that no strength checking of passphrases is performed.
  259. For an empty passphrase, just hit ENTER twice.
  260. """
  261. if passwd_file:
  262. from .fileutil import get_words_from_file
  263. pw = ' '.join(get_words_from_file(
  264. infile = passwd_file,
  265. desc = f'{pw_desc} for {data_desc}',
  266. quiet = pwfile_reuse_warning(passwd_file).warning_shown ))
  267. else:
  268. qmsg('\n'+fmt(message,indent=' '))
  269. from .ui import get_words_from_user
  270. if opt.echo_passphrase:
  271. pw = ' '.join(get_words_from_user(f'Enter {pw_desc} for {data_desc}: '))
  272. else:
  273. for i in range(g.passwd_max_tries):
  274. pw = ' '.join(get_words_from_user(f'Enter {pw_desc} for {data_desc}: '))
  275. pw_chk = ' '.join(get_words_from_user(f'Repeat {pw_desc}: '))
  276. dmsg(f'Passphrases: [{pw}] [{pw_chk}]')
  277. if pw == pw_chk:
  278. vmsg('Passphrases match')
  279. break
  280. else:
  281. msg('Passphrases do not match. Try again.')
  282. else:
  283. die(2,f'User failed to duplicate passphrase in {g.passwd_max_tries} attempts')
  284. if pw == '':
  285. qmsg('WARNING: Empty passphrase')
  286. return pw
  287. def get_passphrase(data_desc,passwd_file,pw_desc='passphrase'):
  288. if passwd_file:
  289. from .fileutil import get_words_from_file
  290. return ' '.join(get_words_from_file(
  291. infile = passwd_file,
  292. desc = f'{pw_desc} for {data_desc}',
  293. quiet = pwfile_reuse_warning(passwd_file).warning_shown ))
  294. else:
  295. from .ui import get_words_from_user
  296. return ' '.join(get_words_from_user(f'Enter {pw_desc} for {data_desc}: '))
  297. mmenc_salt_len = 32
  298. mmenc_nonce_len = 32
  299. def mmgen_encrypt(data,desc='data',hash_preset=None):
  300. salt = get_random(mmenc_salt_len)
  301. iv = get_random(aesctr_iv_len)
  302. nonce = get_random(mmenc_nonce_len)
  303. hp = hash_preset or opt.hash_preset or get_hash_preset_from_user(data_desc=desc)
  304. m = ('user-requested','default')[hp=='3']
  305. vmsg(f'Encrypting {desc}')
  306. qmsg(f'Using {m} hash preset of {hp!r}')
  307. passwd = get_new_passphrase(
  308. data_desc = desc,
  309. hash_preset = hp,
  310. passwd_file = opt.passwd_file )
  311. key = make_key(passwd,salt,hp)
  312. from hashlib import sha256
  313. enc_d = encrypt_data( sha256(nonce+data).digest() + nonce + data, key, iv, desc=desc )
  314. return salt+iv+enc_d
  315. def mmgen_decrypt(data,desc='data',hash_preset=None):
  316. vmsg(f'Preparing to decrypt {desc}')
  317. dstart = mmenc_salt_len + aesctr_iv_len
  318. salt = data[:mmenc_salt_len]
  319. iv = data[mmenc_salt_len:dstart]
  320. enc_d = data[dstart:]
  321. hp = hash_preset or opt.hash_preset or get_hash_preset_from_user(data_desc=desc)
  322. m = ('user-requested','default')[hp=='3']
  323. qmsg(f'Using {m} hash preset of {hp!r}')
  324. passwd = get_passphrase(
  325. data_desc = desc,
  326. passwd_file = opt.passwd_file )
  327. key = make_key(passwd,salt,hp)
  328. dec_d = decrypt_data( enc_d, key, iv, desc )
  329. sha256_len = 32
  330. from hashlib import sha256
  331. if dec_d[:sha256_len] == sha256(dec_d[sha256_len:]).digest():
  332. vmsg('OK')
  333. return dec_d[sha256_len+mmenc_nonce_len:]
  334. else:
  335. msg('Incorrect passphrase or hash preset')
  336. return False
  337. def mmgen_decrypt_retry(d,desc='data'):
  338. while True:
  339. d_dec = mmgen_decrypt(d,desc)
  340. if d_dec: return d_dec
  341. msg('Trying again...')