Add prototype implementation
Marco Ricci authored 4 months ago
|
4)
5) """Work-alike of vault(1) – a deterministic, stateless password manager
6)
7) """
8)
9) from __future__ import annotations
10)
11) import collections
12) import hashlib
13) import math
14) import warnings
15)
16) from typing import assert_type, reveal_type
17)
18) import sequin
19) import ssh_agent_client
20)
21) class Vault:
22) """A work-alike of James Coglan's vault.
23)
24) Store settings for generating (actually: deriving) passphrases for
25) named services, with various constraints, given only a master
26) passphrase. Also, actually generate the passphrase. The derivation
27) is deterministic and non-secret; only the master passphrase need be
28) kept secret. The implementation is compatible with [vault][].
29)
30) [James Coglan explains the passphrase derivation algorithm in great
31) detail][ALGORITHM] in his blog post on said topic: A principally
32) infinite bit stream is obtained by running a key-derivation function
33) on the master passphrase and the service name, then this bit stream
34) is fed into a [sequin][] to generate random numbers in the correct
35) range, and finally these random numbers select passphrase characters
36) until the desired length is reached.
37)
38) [vault]: https://getvau.lt
39) [ALGORITHM]: https://blog.jcoglan.com/2012/07/16/designing-vaults-generator-algorithm/
40)
41) """
42) _UUID = b'e87eb0f4-34cb-46b9-93ad-766c5ab063e7'
43) """A tag used by vault in the bit stream generation."""
44) _CHARSETS: collections.OrderedDict[str, bytes]
45) """
46) Known character sets from which to draw passphrase characters.
47) Relies on a certain, fixed order for their definition and their
48) contents.
49)
50) """
51) _CHARSETS = collections.OrderedDict([
52) ('lower', b'abcdefghijklmnopqrstuvwxyz'),
53) ('upper', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
54) ('alpha', b''), # Placeholder.
55) ('number', b'0123456789'),
56) ('alphanum', b''), # Placeholder.
57) ('space', b' '),
58) ('dash', b'-_'),
59) ('symbol', b'!"#$%&\'()*+,./:;<=>?@[\\]^{|}~-_'),
60) ('all', b''), # Placeholder.
61) ])
62) _CHARSETS['alpha'] = _CHARSETS['lower'] + _CHARSETS['upper']
63) _CHARSETS['alphanum'] = _CHARSETS['alpha'] + _CHARSETS['number']
64) _CHARSETS['all'] = (_CHARSETS['alphanum'] + _CHARSETS['space']
65) + _CHARSETS['symbol'])
66)
67) def __init__(
68) self, *, phrase: bytes | bytearray = b'', length: int = 20,
69) repeat: int = 0, lower: int | None = None,
70) upper: int | None = None, number: int | None = None,
71) space: int | None = None, dash: int | None = None,
72) symbol: int | None = None,
73) ) -> None:
74) """Initialize the Vault object.
75)
76) Args:
77) phrase:
78) The master passphrase from which to derive the service
79) passphrases.
80) length:
81) Desired passphrase length.
82) repeat:
83) The maximum number of immediate character repetitions
84) allowed in the passphrase. Disabled if set to 0.
85) lower:
86) Optional constraint on lowercase characters. If
87) positive, include this many lowercase characters
88) somewhere in the passphrase. If 0, avoid lowercase
89) characters altogether.
90) upper:
91) Same as `lower`, but for uppercase characters.
92) number:
93) Same as `lower`, but for ASCII digits.
94) space:
95) Same as `lower`, but for the space character.
96) dash:
97) Same as `lower`, but for the hyphen-minus and underscore
98) characters.
99) symbol:
100) Same as `lower`, but for all other hitherto unlisted
101) ASCII printable characters (except backquote).
102)
103) """
104) self._phrase = bytes(phrase)
105) self._length = length
106) self._repeat = repeat
107) self._allowed = bytearray(self._CHARSETS['all'])
108) self._required: list[bytes] = []
109) def subtract_or_require(
110) count: int | None, characters: bytes | bytearray
111) ) -> None:
112) if not isinstance(count, int):
113) return
114) elif count <= 0:
115) self._allowed = self._subtract(characters, self._allowed)
116) else:
117) for _ in range(count):
118) self._required.append(characters)
119) subtract_or_require(lower, self._CHARSETS['lower'])
120) subtract_or_require(upper, self._CHARSETS['upper'])
121) subtract_or_require(number, self._CHARSETS['number'])
122) subtract_or_require(space, self._CHARSETS['space'])
123) subtract_or_require(dash, self._CHARSETS['dash'])
124) subtract_or_require(symbol, self._CHARSETS['symbol'])
|
Add prototype implementation
Marco Ricci authored 4 months ago
|
126) raise ValueError('requested passphrase length too short')
127) if not self._allowed:
128) raise ValueError('no allowed characters left')
129) for _ in range(len(self._required), self._length):
130) self._required.append(bytes(self._allowed))
131)
132) def _entropy_upper_bound(self) -> int:
133) """Estimate the passphrase entropy, given the current settings.
134)
135) The entropy is the base 2 logarithm of the amount of
136) possibilities. We operate directly on the logarithms, and round
137) each summand up, overestimating the true entropy.
138)
139) """
140) factors: list[int] = []
141) for i, charset in enumerate(self._required):
142) factors.append(i + 1)
143) factors.append(len(charset))
144) return sum(int(math.ceil(math.log2(f))) for f in factors)
145)
146) @classmethod
147) def create_hash(
148) cls, key: bytes | bytearray, message: bytes | bytearray, *,
149) length: int = 32,
150) ) -> bytes:
151) """Create a pseudorandom byte stream from key and message.
152)
153) Args:
154) key:
155) A cryptographic key. Typically a master passphrase, or
156) an SSH signature.
157) message:
158) A message. Typically a vault service name.
159) length:
160) The length of the byte stream to generate.
161)
162) Returns:
163) A pseudorandom byte string of length `length`.
164)
165) Note:
166) Shorter values returned from this method (with the same key
167) and message) are prefixes of longer values returned from
168) this method. (This property is inherited from the
169) underlying PBKDF2 function.) It is thus safe (if slow) to
170) call this method with the same input with ever-increasing
171) target lengths.
172)
173) """
174) return hashlib.pbkdf2_hmac(hash_name='sha1', password=key,
175) salt=message, iterations=8, dklen=length)
176)
177) def generate(
|
Add prototype implementation
Marco Ricci authored 4 months ago
|
245)
246) @classmethod
247) def phrase_from_signature(
248) cls, key: bytes | bytearray, /
249) ) -> bytes | bytearray:
250) """Obtain the master passphrase from a configured SSH key.
251)
252) vault allows the usage of certain SSH keys to derive a master
253) passphrase, by signing the vault UUID with the SSH key. The key
254) type must ensure that signatures are deterministic.
255)
256) Args:
257) key: The (public) SSH key to use for signing.
258)
259) Returns:
260) The signature of the vault UUID under this key.
261)
262) Raises:
263) ValueError:
264) The SSH key is principally unsuitable for this use case.
265) Usually this means that the signature is not
266) deterministic.
267)
268) """
269) deterministic_signature_types = {
270) 'ssh-ed25519':
271) lambda k: k.startswith(b'\x00\x00\x00\x0bssh-ed25519'),
272) 'ssh-rsa':
273) lambda k: k.startswith(b'\x00\x00\x00\x07ssh-rsa'),
274) }
275) if not any(v(key) for v in deterministic_signature_types.values()):
276) raise ValueError(
277) 'unsuitable SSH key: bad key, or signature not deterministic')
278) with ssh_agent_client.SSHAgentClient() as client:
279) ret = client.sign(key, cls._UUID)
280) return ret
281)
282) def _subtract(
283) self, charset: bytes | bytearray, allowed: bytes | bytearray,
284) ) -> bytearray:
285) """Remove the characters in charset from allowed.
286)
287) This preserves the relative order of characters in `allowed`.
288)
289) Args:
290) charset: Characters to remove.
291) allowed: Character set to remove the other characters from.
292)
293) Returns:
294) The pruned character set.
295)
296) Raises:
297) ValueError: `charset` contained duplicate characters.
298)
299) """
300) allowed = (allowed if isinstance(allowed, bytearray)
301) else bytearray(allowed))
302) assert_type(allowed, bytearray)
303) if len(frozenset(charset)) != len(charset):
304) raise ValueError('duplicate characters in set')
305) for c in charset:
306) try:
307) pos = allowed.index(c)
|