crypto.py 14 KB

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