passwdlist.py 8.2 KB

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