94068756e896574a397b4717388b02ed661a22a9
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

1) # SPDX-FileCopyrightText: 2024 Marco Ricci <m@the13thletter.info>
2) #
3) # SPDX-License-Identifier: MIT
4) 
Marco Ricci Update documentation to use...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months 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 3 months 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 3 months 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) 
74)     def __init__(
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 months ago

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

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

Marco Ricci authored 2 months ago

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