Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
1) # SPDX-FileCopyrightText: 2025 Marco Ricci <software@the13thletter.info>
2) #
3) # SPDX-License-Identifier: Zlib
4)
|
Move the tests for the stub...
Marco Ricci authored 11 months ago
|
5) """Tests for the test suite's data and machinery.
|
Add module docstrings for t...
Marco Ricci authored 11 months ago
|
6)
|
Move the tests for the stub...
Marco Ricci authored 11 months ago
|
7) Currently, this entails testing [the SSH test keys][data.ALL_KEYS]
8) for internal consistency, and testing the functionality of the [stubbed
9) SSH agent][tests.machinery.StubbedSSHAgentSocket], in all variations.
|
Add module docstrings for t...
Marco Ricci authored 11 months ago
|
10)
11) """
12)
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
13) from __future__ import annotations
14)
15) import base64
|
Move the tests for the stub...
Marco Ricci authored 11 months ago
|
16) import contextlib
17) import errno
18) import os
19) import pathlib
20) import re
21) from typing import TYPE_CHECKING
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
22)
23) import pytest
24)
|
Move the tests for the stub...
Marco Ricci authored 11 months ago
|
25) from derivepassphrase import _types, ssh_agent, vault
26) from tests import data, machinery
27)
28) if TYPE_CHECKING:
29) from collections.abc import Iterator
30)
31) from typing_extensions import Buffer
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
32)
|
Change the code style to us...
Marco Ricci authored 1 year ago
|
33) OPENSSH_MAGIC = b"openssh-key-v1\x00"
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
34) OPENSSH_HEADER = (
35) OPENSSH_MAGIC # magic
|
Change the code style to us...
Marco Ricci authored 1 year ago
|
36) + b"\x00\x00\x00\x04none" # ciphername
37) + b"\x00\x00\x00\x04none" # kdfname
38) + b"\x00\x00\x00\x00" # kdfoptions
39) + b"\x00\x00\x00\x01" # number of keys
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
40) )
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
41) OPENSSH_NONE_CIPHER_BLOCKSIZE = 8
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
42)
43)
44) def as_openssh_keyfile_payload(
45) public_key: bytes, private_key: bytes, checkint: int
46) ) -> bytes:
47) """Format an SSH private key in OpenSSH format.
48)
49) Args:
50) public_key:
51) The unframed public key, in SSH wire format.
52) private_key:
53) The unframed private key, in SSH wire format, including the
54) comment.
55) checkint:
56) The "check" integer to use.
57)
58) Returns:
59) The payload for a formatted OpenSSH private key, as a byte
60) string, without the base64 encoding and the framing lines.
61)
62) """
63) # The OpenSSH private key file format is described in PROTOCOL.key
64) # in their git repository; see below for links to OpenSSH 10.0p2.
65) # The block size of the "none" cipher is 8 bytes; see line 108 of
66) # cipher.c, with definitions from line 67 onwards. Padding is not
67) # used if the payload already is a multiple of 8 bytes long; see
68) # line 2935 onwards of sshkey.c
69) #
70) # https://github.com/openssh/openssh-portable/raw/2593769fb291fe6c542173927698c69e9f9a08b9/PROTOCOL.key
71) # https://github.com/openssh/openssh-portable/raw/2593769fb291fe6c542173927698c69e9f9a08b9/cipher.c
72) # https://github.com/openssh/openssh-portable/raw/2593769fb291fe6c542173927698c69e9f9a08b9/sshkey.c
73) string = ssh_agent.SSHAgentClient.string
74) uint32 = ssh_agent.SSHAgentClient.uint32
75) payload = bytearray(OPENSSH_HEADER)
76) payload.extend(string(public_key))
77) secret = bytearray()
78) secret.extend(uint32(checkint)) # checkint
79) secret.extend(uint32(checkint)) # checkint
80) secret.extend(private_key) # privatekey1 and comment1
81) i = 1
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
82) while len(secret) % OPENSSH_NONE_CIPHER_BLOCKSIZE != 0:
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
83) secret.append(i)
84) i += 1
85) payload.extend(string(secret)) # encrypted, padded list of private keys
86) return bytes(payload)
87)
88)
89) def minimize_openssh_keyfile_padding(
90) decoded_openssh_private_key: bytes,
91) ) -> bytes:
92) """Minimize the padding used in an OpenSSH private key file.
93)
94) Args:
95) decoded_openssh_private_key:
96) The non-base64-encoded, unframed, formatted OpenSSH private
97) key.
98)
99) Returns:
100) The same non-base64-encoded, unframed, formatted OpenSSH private
101) key, but with minimal padding applied.
102)
103) """
104) string = ssh_agent.SSHAgentClient.string
105) unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
106)
107) _public_key, framed_private_block = unstring_prefix(
108) decoded_openssh_private_key.removeprefix(OPENSSH_HEADER)
109) )
110) result = bytearray(decoded_openssh_private_key).removesuffix(
111) framed_private_block
112) )
113) private_block, trailer = unstring_prefix(framed_private_block)
114) assert not trailer
115)
116) # Skip two checkint values.
117) key_type, remainder = unstring_prefix(private_block[8:])
118) # We need to semi-generically skip private key payloads. Currently,
119) # all supported (test) key types exclusively store multi-precision
120) # integers or strings as their private key payload (which are both
121) # parsed the same way, but interpreted differently). We can
122) # therefore generically parse `k` strings/mpints (for different
123) # values of `k`, depending on key type) to correctly skip the
124) # private key payload, and don't have to deal with having to parse
125) # and skip other types of data such as uint32s.
126) #
127) # (This scheme needs updating if ever a different data type needs to
128) # be parsed.)
129) num_mpints = {
|
Change the code style to us...
Marco Ricci authored 1 year ago
|
130) b"ssh-ed25519": 2,
131) b"ssh-ed448": 2,
132) b"ssh-rsa": 6,
133) b"ssh-dss": 5,
134) b"ecdsa-sha2-nistp256": 3,
135) b"ecdsa-sha2-nistp384": 3,
136) b"ecdsa-sha2-nistp521": 3,
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
137) }
138) for _ in range(num_mpints[key_type]):
139) _, remainder = unstring_prefix(remainder)
140) # Skip comment.
141) _comment, remainder = unstring_prefix(remainder)
142) new_private_block = bytearray(private_block).removesuffix(remainder)
143) padding = bytearray(remainder)
144)
145) expected_padding = bytearray()
146) for i in range(1, len(padding) + 1):
147) expected_padding.append(i & 0xFF)
148) assert padding == expected_padding
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
149) while len(padding) >= OPENSSH_NONE_CIPHER_BLOCKSIZE:
150) padding[-OPENSSH_NONE_CIPHER_BLOCKSIZE:] = b""
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
151)
152) new_private_block.extend(padding)
153) result.extend(string(new_private_block))
154) return result
155)
156)
157) class Parametrize:
158) """Common test parametrizations."""
159)
|
Move the tests for the stub...
Marco Ricci authored 11 months ago
|
160) STUBBED_AGENT_ADDRESSES = pytest.mark.parametrize(
161) ["address", "exception", "match"],
162) [
163) pytest.param(None, KeyError, "SSH_AUTH_SOCK", id="unset"),
164) pytest.param("stub-ssh-agent:", None, "", id="standard"),
165) pytest.param(
166) str(pathlib.Path("~").expanduser()),
167) FileNotFoundError,
168) os.strerror(errno.ENOENT),
169) id="invalid-url",
170) ),
171) pytest.param(
172) "stub-ssh-agent:EPROTONOSUPPORT",
173) OSError,
174) os.strerror(errno.EPROTONOSUPPORT),
175) id="protocol-not-supported",
176) ),
177) pytest.param(
178) "stub-ssh-agent:ABCDEFGHIJKLMNOPQRSTUVWXYZ",
179) OSError,
180) os.strerror(errno.EINVAL),
181) id="invalid-error-code",
182) ),
183) ],
184) )
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
185) TEST_KEYS = pytest.mark.parametrize(
|
Reformat tests after refact...
Marco Ricci authored 1 year ago
|
186) ["keyname", "key"],
|
Use leaf module imports in...
Marco Ricci authored 1 year ago
|
187) data.ALL_KEYS.items(),
188) ids=data.ALL_KEYS.keys(),
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
189) )
|
Move the tests for the stub...
Marco Ricci authored 11 months ago
|
190) INVALID_SSH_AGENT_MESSAGES = pytest.mark.parametrize(
191) "message",
192) [
193) pytest.param(b"\x00\x00\x00\x00", id="empty-message"),
194) pytest.param(b"\x00\x00\x00\x0f\x0d", id="truncated-message"),
195) pytest.param(
196) b"\x00\x00\x00\x06\x1b\x00\x00\x00\x01\xff",
197) id="invalid-extension-name",
198) ),
199) pytest.param(
200) b"\x00\x00\x00\x11\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
201) id="sign-with-trailing-data",
202) ),
203) ],
204) )
205) UNSUPPORTED_SSH_AGENT_MESSAGES = pytest.mark.parametrize(
206) "message",
207) [
208) pytest.param(
209) ssh_agent.SSHAgentClient.string(
210) b"".join([
211) b"\x0d",
212) ssh_agent.SSHAgentClient.string(
213) data.ALL_KEYS["rsa"].public_key_data
214) ),
215) ssh_agent.SSHAgentClient.string(vault.Vault.UUID),
216) b"\x00\x00\x00\x02",
217) ])
218) ),
219) id="sign-with-flags",
220) ),
221) pytest.param(
222) ssh_agent.SSHAgentClient.string(
223) b"".join([
224) b"\x0d",
225) ssh_agent.SSHAgentClient.string(
226) data.ALL_KEYS["ed25519"].public_key_data
227) ),
228) b"\x00\x00\x00\x08\x00\x01\x02\x03\x04\x05\x06\x07",
229) b"\x00\x00\x00\x00",
230) ])
231) ),
232) id="sign-with-nonstandard-passphrase",
233) ),
234) pytest.param(
235) ssh_agent.SSHAgentClient.string(
236) b"".join([
237) b"\x0d",
238) ssh_agent.SSHAgentClient.string(
239) data.ALL_KEYS["dsa1024"].public_key_data
240) ),
241) ssh_agent.SSHAgentClient.string(vault.Vault.UUID),
242) b"\x00\x00\x00\x00",
243) ])
244) ),
245) id="sign-key-no-expected-signature",
246) ),
247) pytest.param(
248) ssh_agent.SSHAgentClient.string(
249) b"".join([
250) b"\x0d",
251) b"\x00\x00\x00\x00",
252) ssh_agent.SSHAgentClient.string(vault.Vault.UUID),
253) b"\x00\x00\x00\x00",
254) ])
255) ),
256) id="sign-key-unregistered-test-key",
257) ),
258) ],
259) )
260) SUPPORTED_SSH_TEST_KEYS = pytest.mark.parametrize(
261) ["ssh_test_key_type", "ssh_test_key"],
262) list(data.SUPPORTED_KEYS.items()),
263) ids=data.SUPPORTED_KEYS.keys(),
264) )
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
265)
266)
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
267) class TestTestKeys:
268) """Tests testing the test keys."""
269)
270) @Parametrize.TEST_KEYS
271) def test_public_keys_are_internally_consistent(
272) self,
273) keyname: str,
274) key: data.SSHTestKey,
275) ) -> None:
276) """The public key data structures are internally consistent."""
277) del keyname
278) string = ssh_agent.SSHAgentClient.string
279) public_key_lines = key.public_key.splitlines(keepends=False)
280) assert len(public_key_lines) == 1
281) line_parts = public_key_lines[0].strip(b"\r\n").split(None, 2)
282) key_type_name, public_key_b64 = line_parts[:2]
283) assert base64.standard_b64encode(key.public_key_data) == public_key_b64
284) assert key.public_key_data.startswith(string(key_type_name))
285)
286) @Parametrize.TEST_KEYS
287) def test_private_keys_are_consistent_with_public_keys(
288) self,
289) keyname: str,
290) key: data.SSHTestKey,
291) ) -> None:
292) """The private key data are consistent with their public parts."""
293) del keyname
294) string = ssh_agent.SSHAgentClient.string
295)
296) if key.public_key_data.startswith(string(b"ssh-rsa")):
297) # RSA public keys are *not* prefixes of the corresponding
298) # private key in OpenSSH format! RSA public keys consist of
299) # an exponent e and a modulus n, which in the public key are
300) # in the order (e, n), but in the order (n, e) in the
301) # OpenSSH private key. We thus need to parse and rearrange
302) # the components of the public key into a new "mangled"
303) # public key that then *is* a prefix of the respective
304) # private key.
305) unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
306) key_type, numbers = unstring_prefix(key.public_key_data)
307) e, encoded_n = unstring_prefix(numbers)
308) n, trailer = unstring_prefix(encoded_n)
309) assert not trailer
310) mangled_public_key_data = string(key_type) + string(n) + string(e)
311) assert (
312) key.private_key_blob[: len(mangled_public_key_data)]
313) == mangled_public_key_data
314) )
315) else:
316) assert (
317) key.private_key_blob[: len(key.public_key_data)]
318) == key.public_key_data
319) )
320)
321) @Parametrize.TEST_KEYS
322) def test_private_keys_are_internally_consistent(
323) self,
324) keyname: str,
325) key: data.SSHTestKey,
326) ) -> None:
327) """The private key data structures are internally consistent."""
328) del keyname
329) string = ssh_agent.SSHAgentClient.string
330)
331) private_key_lines = [
332) line
333) for line in key.private_key.splitlines(keepends=False)
334) if line and not line.startswith((b"-----BEGIN", b"-----END"))
335) ]
336) private_key_from_openssh = base64.standard_b64decode(
337) b"".join(private_key_lines)
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
338) )
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
339) wrapped_public_key = string(key.public_key_data)
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
340) assert (
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
341) private_key_from_openssh[
342) len(OPENSSH_HEADER) : len(OPENSSH_HEADER)
343) + len(wrapped_public_key)
344) ]
345) == wrapped_public_key
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
346) )
347)
|
Refactor the testing machin...
Marco Ricci authored 1 year ago
|
348) # Offset skips the header, the wrapped public key, and the
349) # framing of the private keys section.
350) offset = len(OPENSSH_HEADER) + len(wrapped_public_key) + 4
351) checkint = int.from_bytes(
352) private_key_from_openssh[offset : offset + 4], "big"
353) )
354) assert minimize_openssh_keyfile_padding(
355) private_key_from_openssh
356) ) == minimize_openssh_keyfile_padding(
357) as_openssh_keyfile_payload(
358) public_key=key.public_key_data,
359) private_key=key.private_key_blob,
360) checkint=checkint,
361) )
|
Fix, and test for, the cons...
Marco Ricci authored 1 year ago
|
362) )
|