passwdlist.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. passwdlist: Password list class for the MMGen suite
  20. """
  21. from collections import namedtuple
  22. from .globalvars import g
  23. from .util import ymsg,is_int,die
  24. from .obj import ImmutableAttr,ListItemAttr,MMGenPWIDString,TwComment
  25. from .key import PrivKey
  26. from .addr import MMGenPasswordType,AddrIdx,AddrListID
  27. from .addrlist import (
  28. AddrListChksum,
  29. AddrListIDStr,
  30. AddrListEntryBase,
  31. AddrList,
  32. )
  33. class PasswordListEntry(AddrListEntryBase):
  34. passwd = ListItemAttr(str,typeconv=False) # TODO: create Password type
  35. idx = ImmutableAttr(AddrIdx)
  36. comment = ListItemAttr(TwComment,reassign_ok=True)
  37. sec = ListItemAttr(PrivKey,include_proto=True)
  38. class PasswordList(AddrList):
  39. entry_type = PasswordListEntry
  40. main_attr = 'passwd'
  41. desc = 'password'
  42. gen_desc = 'password'
  43. gen_desc_pl = 's'
  44. gen_addrs = False
  45. gen_keys = False
  46. gen_passwds = True
  47. pw_len = None
  48. dfl_pw_fmt = 'b58'
  49. pwinfo = namedtuple('passwd_info',['min_len','max_len','dfl_len','valid_lens','desc','chk_func'])
  50. pw_info = {
  51. 'b32': pwinfo(10, 42 ,24, None, 'base32 password', 'baseconv.is_b32_str'), # 32**24 < 2**128
  52. 'b58': pwinfo(8, 36 ,20, None, 'base58 password', 'baseconv.is_b58_str'), # 58**20 < 2**128
  53. 'bip39': pwinfo(12, 24 ,24, [12,18,24],'BIP39 mnemonic', 'bip39.is_bip39_mnemonic'),
  54. 'xmrseed': pwinfo(25, 25, 25, [25], 'Monero new-style mnemonic','xmrseed.is_xmrseed'),
  55. 'hex': pwinfo(32, 64 ,64, [32,48,64],'hexadecimal password', 'util.is_hex_str'),
  56. }
  57. chksum_rec_f = lambda foo,e: (str(e.idx), e.passwd)
  58. feature_warn_fs = 'WARNING: {!r} is a potentially dangerous feature. Use at your own risk!'
  59. hex2bip39 = False
  60. def __init__(
  61. self,
  62. proto,
  63. infile = None,
  64. seed = None,
  65. pw_idxs = None,
  66. pw_id_str = None,
  67. pw_len = None,
  68. pw_fmt = None,
  69. chk_params_only = False,
  70. skip_chksum_msg = False ):
  71. self.proto = proto # proto is ignored
  72. if not g.debug_addrlist:
  73. self.dmsg_sc = self.noop
  74. if infile:
  75. self.infile = infile
  76. # sets self.pw_id_str, self.pw_fmt, self.pw_len, self.chk_func:
  77. self.data = self.get_file().parse_file(infile)
  78. else:
  79. if not chk_params_only:
  80. for k in (seed,pw_idxs):
  81. assert k
  82. self.pw_id_str = MMGenPWIDString(pw_id_str)
  83. self.set_pw_fmt(pw_fmt)
  84. self.set_pw_len(pw_len)
  85. if chk_params_only:
  86. return
  87. if self.hex2bip39:
  88. ymsg(self.feature_warn_fs.format(pw_fmt))
  89. self.set_pw_len_vs_seed_len(pw_len,seed) # sets self.bip39, self.xmrseed, self.xmrproto self.baseconv
  90. self.al_id = AddrListID( sid=seed.sid, mmtype=MMGenPasswordType(self.proto,'P') )
  91. self.data = self.generate(seed,pw_idxs)
  92. self.num_addrs = len(self.data)
  93. self.fmt_data = ''
  94. self.chksum = AddrListChksum(self)
  95. fs = f'{self.al_id.sid}-{self.pw_id_str}-{self.pw_fmt_disp}-{self.pw_len}[{{}}]'
  96. self.id_str = AddrListIDStr(self,fs)
  97. if not skip_chksum_msg:
  98. self.do_chksum_msg(record=not infile)
  99. def set_pw_fmt(self,pw_fmt):
  100. if pw_fmt == 'hex2bip39':
  101. self.hex2bip39 = True
  102. self.pw_fmt = 'bip39'
  103. self.pw_fmt_disp = 'hex2bip39'
  104. else:
  105. self.pw_fmt = pw_fmt
  106. self.pw_fmt_disp = pw_fmt
  107. if self.pw_fmt not in self.pw_info:
  108. die( 'InvalidPasswdFormat',
  109. '{!r}: invalid password format. Valid formats: {}'.format(
  110. self.pw_fmt,
  111. ', '.join(self.pw_info) ))
  112. def chk_pw_len(self,passwd=None):
  113. if passwd is None:
  114. assert self.pw_len,'either passwd or pw_len must be set'
  115. pw_len = self.pw_len
  116. fs = '{l}: invalid user-requested length for {b} ({c}{m})'
  117. else:
  118. pw_len = len(passwd)
  119. fs = '{pw}: {b} has invalid length {l} ({c}{m} characters)'
  120. d = self.pw_info[self.pw_fmt]
  121. if d.valid_lens:
  122. if pw_len not in d.valid_lens:
  123. die(2, fs.format( l=pw_len, b=d.desc, c='not one of ', m=d.valid_lens, pw=passwd ))
  124. elif pw_len > d.max_len:
  125. die(2, fs.format( l=pw_len, b=d.desc, c='>', m=d.max_len, pw=passwd ))
  126. elif pw_len < d.min_len:
  127. die(2, fs.format( l=pw_len, b=d.desc, c='<', m=d.min_len, pw=passwd ))
  128. def set_pw_len(self,pw_len):
  129. d = self.pw_info[self.pw_fmt]
  130. if pw_len is None:
  131. self.pw_len = d.dfl_len
  132. return
  133. if not is_int(pw_len):
  134. die(2,f'{pw_len!r}: invalid user-requested password length (not an integer)')
  135. self.pw_len = int(pw_len)
  136. self.chk_pw_len()
  137. def set_pw_len_vs_seed_len(self,pw_len,seed):
  138. pf = self.pw_fmt
  139. if pf == 'hex':
  140. pw_bytes = self.pw_len // 2
  141. good_pw_len = seed.byte_len * 2
  142. elif pf == 'bip39':
  143. from .bip39 import bip39
  144. self.bip39 = bip39()
  145. pw_bytes = bip39.nwords2seedlen(self.pw_len,in_bytes=True)
  146. good_pw_len = bip39.seedlen2nwords(seed.byte_len,in_bytes=True)
  147. elif pf == 'xmrseed':
  148. from .xmrseed import xmrseed
  149. from .protocol import init_proto
  150. self.xmrseed = xmrseed()
  151. self.xmrproto = init_proto('xmr')
  152. pw_bytes = xmrseed().seedlen_map_rev[self.pw_len]
  153. try:
  154. good_pw_len = xmrseed().seedlen_map[seed.byte_len]
  155. except:
  156. die(1,f'{seed.byte_len*8}: unsupported seed length for Monero new-style mnemonic')
  157. elif pf in ('b32','b58'):
  158. pw_int = (32 if pf == 'b32' else 58) ** self.pw_len
  159. pw_bytes = pw_int.bit_length() // 8
  160. from .baseconv import baseconv
  161. self.baseconv = baseconv(self.pw_fmt)
  162. good_pw_len = len( baseconv(pf).frombytes(b'\xff'*seed.byte_len) )
  163. else:
  164. raise NotImplementedError(f'{pf!r}: unknown password format')
  165. if pw_bytes > seed.byte_len:
  166. die(1,
  167. 'Cannot generate passwords with more entropy than underlying seed! ({} bits)\n'.format(
  168. len(seed.data) * 8 ) + (
  169. 'Re-run the command with --passwd-len={}' if pf in ('bip39','hex') else
  170. 'Re-run the command, specifying a password length of {} or less'
  171. ).format(good_pw_len) )
  172. if pf in ('bip39','hex') and pw_bytes < seed.byte_len:
  173. from .ui import keypress_confirm
  174. if not keypress_confirm(
  175. f'WARNING: requested {self.pw_info[pf].desc} length has less entropy ' +
  176. 'than underlying seed!\nIs this what you want?',
  177. default_yes = True ):
  178. die(1,'Exiting at user request')
  179. def gen_passwd(self,secbytes):
  180. assert self.pw_fmt in self.pw_info
  181. if self.pw_fmt == 'hex':
  182. # take most significant part
  183. return secbytes.hex()[:self.pw_len]
  184. elif self.pw_fmt == 'bip39':
  185. pw_len_bytes = self.bip39.nwords2seedlen( self.pw_len, in_bytes=True )
  186. # take most significant part
  187. return ' '.join( self.bip39.fromhex(secbytes[:pw_len_bytes].hex()) )
  188. elif self.pw_fmt == 'xmrseed':
  189. pw_len_bytes = self.xmrseed.seedlen_map_rev[self.pw_len]
  190. bytes_preproc = self.xmrproto.preprocess_key(
  191. secbytes[:pw_len_bytes], # take most significant part
  192. None )
  193. return ' '.join( self.xmrseed.frombytes(bytes_preproc) )
  194. else:
  195. # take least significant part
  196. return self.baseconv.frombytes(
  197. secbytes,
  198. pad = self.pw_len,
  199. tostr = True )[-self.pw_len:]
  200. def check_format(self,pw):
  201. if not self.chk_func(pw):
  202. raise ValueError(f'Password is not valid {self.pw_info[self.pw_fmt].desc} data')
  203. pwlen = len(pw.split()) if self.pw_fmt in ('bip39','xmrseed') else len(pw)
  204. if pwlen != self.pw_len:
  205. raise ValueError(f'Password has incorrect length ({pwlen} != {self.pw_len})')
  206. return True
  207. def scramble_seed(self,seed):
  208. # Changing either pw_fmt or pw_len will cause a different, unrelated
  209. # set of passwords to be generated: this is what we want.
  210. # NB: In original implementation, pw_id_str was 'baseN', not 'bN'
  211. scramble_key = f'{self.pw_fmt}:{self.pw_len}:{self.pw_id_str}'
  212. if self.hex2bip39:
  213. pwlen = self.bip39.nwords2seedlen(self.pw_len,in_hex=True)
  214. scramble_key = f'hex:{pwlen}:{self.pw_id_str}'
  215. self.dmsg_sc('str',scramble_key)
  216. from .crypto import Crypto
  217. return Crypto().scramble_seed(seed,scramble_key.encode())