2d292af3e81527750e46a2167d30efe840ac58ca
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

1) # SPDX-FileCopyrightText: 2024 Marco Ricci <m@the13thletter.info>
2) #
3) # SPDX-License-Identifier: MIT
4) 
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 weeks ago

5) """Python port of the vault(1) password generation scheme."""
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

6) 
7) from __future__ import annotations
8) 
9) import base64
10) import collections
11) import hashlib
12) import math
13) from collections.abc import Callable
14) from typing import TypeAlias
15) 
16) from typing_extensions import assert_type
17) 
18) from derivepassphrase import sequin, ssh_agent
19) 
20) __author__ = 'Marco Ricci <m@the13thletter.info>'
21) 
22) 
23) _CHARSETS = collections.OrderedDict([
24)     ('lower', b'abcdefghijklmnopqrstuvwxyz'),
25)     ('upper', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
26)     ('alpha', b''),  # Placeholder.
27)     ('number', b'0123456789'),
28)     ('alphanum', b''),  # Placeholder.
29)     ('space', b' '),
30)     ('dash', b'-_'),
31)     ('symbol', b'!"#$%&\'()*+,./:;<=>?@[\\]^{|}~-_'),
32)     ('all', b''),  # Placeholder.
33) ])
34) _CHARSETS['alpha'] = _CHARSETS['lower'] + _CHARSETS['upper']
35) _CHARSETS['alphanum'] = _CHARSETS['alpha'] + _CHARSETS['number']
36) _CHARSETS['all'] = (
37)     _CHARSETS['alphanum'] + _CHARSETS['space'] + _CHARSETS['symbol']
38) )
39) 
40) 
41) class Vault:
42)     """A work-alike of James Coglan's vault.
43) 
44)     Store settings for generating (actually: deriving) passphrases for
45)     named services, with various constraints, given only a master
46)     passphrase.  Also, actually generate the passphrase.  The derivation
47)     is deterministic and non-secret; only the master passphrase need be
48)     kept secret.  The implementation is compatible with [vault][].
49) 
50)     [James Coglan explains the passphrase derivation algorithm in great
51)     detail][ALGORITHM] in his blog post on said topic: A principally
52)     infinite bit stream is obtained by running a key-derivation function
53)     on the master passphrase and the service name, then this bit stream
Marco Ricci Update documentation to use...

Marco Ricci authored 1 month ago

54)     is fed into a [Sequin][derivepassphrase.sequin.Sequin] to generate
55)     random numbers in the correct range, and finally these random
56)     numbers select passphrase characters until the desired length is
57)     reached.
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

58) 
59)     [vault]: https://getvau.lt
60)     [ALGORITHM]: https://blog.jcoglan.com/2012/07/16/designing-vaults-generator-algorithm/
61) 
62)     """
63) 
64)     _UUID = b'e87eb0f4-34cb-46b9-93ad-766c5ab063e7'
65)     """A tag used by vault in the bit stream generation."""
66)     _CHARSETS = _CHARSETS
67)     """
68)         Known character sets from which to draw passphrase characters.
69)         Relies on a certain, fixed order for their definition and their
70)         contents.
71) 
72)     """
73) 
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 weeks ago

74)     def __init__(  # noqa: PLR0913
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

75)         self,
76)         *,
77)         phrase: bytes | bytearray | str = b'',
78)         length: int = 20,
79)         repeat: int = 0,
80)         lower: int | None = None,
81)         upper: int | None = None,
82)         number: int | None = None,
83)         space: int | None = None,
84)         dash: int | None = None,
85)         symbol: int | None = None,
86)     ) -> None:
87)         """Initialize the Vault object.
88) 
89)         Args:
90)             phrase:
91)                 The master passphrase from which to derive the service
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 weeks ago

92)                 passphrases.
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

93)             length:
94)                 Desired passphrase length.
95)             repeat:
96)                 The maximum number of immediate character repetitions
97)                 allowed in the passphrase.  Disabled if set to 0.
98)             lower:
99)                 Optional constraint on ASCII lowercase characters.  If
100)                 positive, include this many lowercase characters
101)                 somewhere in the passphrase.  If 0, avoid lowercase
102)                 characters altogether.
103)             upper:
104)                 Same as `lower`, but for ASCII uppercase characters.
105)             number:
106)                 Same as `lower`, but for ASCII digits.
107)             space:
108)                 Same as `lower`, but for the space character.
109)             dash:
110)                 Same as `lower`, but for the hyphen-minus and underscore
111)                 characters.
112)             symbol:
113)                 Same as `lower`, but for all other hitherto unlisted
114)                 ASCII printable characters (except backquote).
115) 
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 weeks ago

116)         Raises:
117)             ValueError:
118)                 Conflicting passphrase constraints.  Permit more
119)                 characters, or increase the desired passphrase length.
120) 
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

121)         """
122)         self._phrase = self._get_binary_string(phrase)
123)         self._length = length
124)         self._repeat = repeat
125)         self._allowed = bytearray(self._CHARSETS['all'])
126)         self._required: list[bytes] = []
127) 
128)         def subtract_or_require(
129)             count: int | None, characters: bytes | bytearray
130)         ) -> None:
131)             if not isinstance(count, int):
132)                 return
133)             if count <= 0:
134)                 self._allowed = self._subtract(characters, self._allowed)
135)             else:
136)                 for _ in range(count):
137)                     self._required.append(characters)
138) 
139)         subtract_or_require(lower, self._CHARSETS['lower'])
140)         subtract_or_require(upper, self._CHARSETS['upper'])
141)         subtract_or_require(number, self._CHARSETS['number'])
142)         subtract_or_require(space, self._CHARSETS['space'])
143)         subtract_or_require(dash, self._CHARSETS['dash'])
144)         subtract_or_require(symbol, self._CHARSETS['symbol'])
145)         if len(self._required) > self._length:
146)             msg = 'requested passphrase length too short'
147)             raise ValueError(msg)
148)         if not self._allowed:
149)             msg = 'no allowed characters left'
150)             raise ValueError(msg)
151)         for _ in range(len(self._required), self._length):
152)             self._required.append(bytes(self._allowed))
153) 
154)     def _entropy(self) -> float:
155)         """Estimate the passphrase entropy, given the current settings.
156) 
157)         The entropy is the base 2 logarithm of the amount of
158)         possibilities.  We operate directly on the logarithms, and use
159)         sorting and [`math.fsum`][] to keep high accuracy.
160) 
161)         Note:
162)             We actually overestimate the entropy here because of poor
163)             handling of character repetitions.  In the extreme, assuming
164)             that only one character were allowed, then because there is
165)             only one possible string of each given length, the entropy
166)             of that string `s` is always be zero.  However, we calculate
167)             the entropy as `math.log2(math.factorial(len(s)))`, i.e. we
168)             assume the characters at the respective string position are
169)             distinguishable from each other.
170) 
171)         Returns:
172)             A valid (and somewhat close) upper bound to the entropy.
173) 
174)         """
175)         factors: list[int] = []
176)         if not self._required or any(not x for x in self._required):
177)             return float('-inf')
178)         for i, charset in enumerate(self._required):
179)             factors.extend([i + 1, len(charset)])
180)         factors.sort()
181)         return math.fsum(math.log2(f) for f in factors)
182) 
183)     def _estimate_sufficient_hash_length(
184)         self,
185)         safety_factor: float = 2.0,
186)     ) -> int:
187)         """Estimate the sufficient hash length, given the current settings.
188) 
189)         Using the entropy (via `_entropy`) and a safety factor, give an
190)         initial estimate of the length to use for `create_hash` such
191)         that using a `Sequin` with this hash will not exhaust it during
192)         passphrase generation.
193) 
194)         Args:
195)             safety_factor: The safety factor.  Must be at least 1.
196) 
197)         Returns:
198)             The estimated sufficient hash length.
199) 
200)         Warning:
201)             This is a heuristic, not an exact computation; it may
202)             underestimate the true necessary hash length.  It is
203)             intended as a starting point for searching for a sufficient
204)             hash length, usually by doubling the hash length each time
205)             it does not yet prove so.
206) 
207)         """
208)         try:
209)             safety_factor = float(safety_factor)
210)         except TypeError as e:
211)             msg = f'invalid safety factor: not a float: {safety_factor!r}'
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 weeks ago

212)             raise TypeError(msg) from e  # noqa: DOC501
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

213)         if not math.isfinite(safety_factor) or safety_factor < 1.0:
214)             msg = f'invalid safety factor {safety_factor!r}'
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 weeks ago

215)             raise ValueError(msg)  # noqa: DOC501
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 1 month ago

216)         # Ensure the bound is strictly positive.
217)         entropy_bound = max(1, self._entropy())
218)         return int(math.ceil(safety_factor * entropy_bound / 8))
219) 
220)     @staticmethod
221)     def _get_binary_string(s: bytes | bytearray | str, /) -> bytes:
222)         """Convert the input string to a read-only, binary string.
223) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 weeks ago

224)         If it is a text string, return the string's UTF-8
225)         representation.