crypto.py 14 KB

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