Debian Codegraph @

tests/pkey.py

raw ◀ ▶
1 Debian patch touch this file
1 from io import StringIO
2 from pathlib import Path
3 from unittest.mock import call, patch
4
5 from cryptography.hazmat.primitives.asymmetric.ec import (
6 EllipticCurvePrivateKey,
7 )
8 from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey
9 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
10 from pytest import mark, raises
11
12 from paramiko import (
13 ECDSAKey,
14 Ed25519Key,
15 Message,
16 PKey,
17 PublicBlob,
18 RSAKey,
19 UnknownKeyType,
20 )
21 from paramiko.pkey import OPENSSH, PEM, PrivateKey
22 from paramiko.ssh_exception import SSHException
23
24 from ._util import _support
25
26
27 class PKey_:
28 # NOTE: this is incidentally tested by a number of other tests, such as the
29 # agent.py test suite
30 class from_type_string:
31 def loads_from_type_and_bytes(self, keys):
32 obj = PKey.from_type_string(keys.full_type, keys.pkey.asbytes())
33 assert obj == keys.pkey
34
35 def accepts_passphrase(self, keys):
36 obj = PKey.from_type_string(
37 keys.full_type, keys.pkey.asbytes(), password=keys.passphrase
38 )
39 assert obj == keys.pkey
40
41 def raises_UnknownKeyType_for_unknown_type_names(self):
42 key = b"not even a real key, smh"
43 with raises(UnknownKeyType) as exc:
44 PKey.from_type_string("wat", key)
45 assert exc.value.key_type == "wat"
46 assert exc.value.key_bytes == key
47
48 class from_path:
49 def loads_from_Path(self, keys):
50 obj = PKey.from_path(keys.path, password=keys.passphrase)
51 assert obj == keys.pkey
52
53 def loads_from_str(self):
54 key = PKey.from_path(str(_support("rsa.key")))
55 assert isinstance(key, RSAKey)
56
57 @patch("paramiko.pkey.Path")
58 def expands_user(self, mPath):
59 # real key for guts that want a real key format
60 mykey = Path(_support("rsa.key"))
61 pathy = mPath.return_value.expanduser.return_value
62 # read_bytes for cryptography.io's loaders
63 pathy.read_bytes.return_value = mykey.read_bytes()
64 # open() for our own class loader
65 pathy.open.return_value = mykey.open()
66 # fake out exists() to avoid attempts to load cert
67 pathy.exists.return_value = False
68 PKey.from_path("whatever") # we're not testing expanduser itself
69 # Both key and cert paths
70 mPath.return_value.expanduser.assert_has_calls([call(), call()])
71
72 def raises_UnknownKeyType_for_unknown_types(self):
73 # I.e. a real, becomes a useful object via cryptography.io, key
74 # class that we do NOT support. Chose Ed448 randomly as OpenSSH
75 # doesn't seem to support it either, going by ssh-keygen...
76 keypath = _support("ed448.key")
77 with raises(UnknownKeyType) as exc:
78 PKey.from_path(keypath)
79 assert issubclass(exc.value.key_type, Ed448PrivateKey)
80 with open(keypath, "rb") as fd:
81 assert exc.value.key_bytes == fd.read()
82
83 def leaves_cryptography_exceptions_untouched(self):
84 # a Python file is not a private key!
85 with raises(ValueError):
86 PKey.from_path(__file__)
87
88 class automatically_loads_certificates:
89 def existing_cert_loaded_when_given_key_path(self):
90 key = PKey.from_path(_support("rsa.key"))
91 # Public blob exists despite no .load_certificate call
92 assert key.public_blob is not None
93 assert (
94 key.public_blob.key_type == "[email protected]"
95 )
96 # And it's definitely the one we expected
97 assert key.public_blob == PublicBlob.from_file(
98 _support("rsa.key-cert.pub")
99 )
100
101 def can_be_given_cert_path_instead(self):
102 key = PKey.from_path(_support("rsa.key-cert.pub"))
103 # It's still a key, not a PublicBlob
104 assert isinstance(key, RSAKey)
105 # Public blob exists despite no .load_certificate call
106 assert key.public_blob is not None
107 assert (
108 key.public_blob.key_type == "[email protected]"
109 )
110 # And it's definitely the one we expected
111 assert key.public_blob == PublicBlob.from_file(
112 _support("rsa.key-cert.pub")
113 )
114
115 def no_cert_load_if_no_cert(self):
116 # This key exists (it's a copy of the regular one) but has no
117 # matching -cert.pub
118 key = PKey.from_path(_support("rsa-lonely.key"))
119 assert key.public_blob is None
120
121 def excepts_usefully_if_no_key_only_cert(self):
122 # TODO: is that truly an error condition? the cert is ~the
123 # pubkey and we still require the privkey for signing, yea?
124 # This cert exists (it's a copy of the regular one) but there's
125 # no rsa-missing.key to load.
126 with raises(FileNotFoundError) as info:
127 PKey.from_path(_support("rsa-missing.key-cert.pub"))
128 assert info.value.filename.endswith("rsa-missing.key")
129
130 class load_certificate:
131 def rsa_public_cert_blobs(self):
132 # Data to test signing with (arbitrary)
133 data = b"ice weasels"
134 # Load key w/o cert at first (so avoiding .from_path)
135 key = RSAKey.from_private_key_file(_support("rsa.key"))
136 assert key.public_blob is None
137 # Sign regular-style (using, arbitrarily, SHA2)
138 msg = key.sign_ssh_data(data, "rsa-sha2-256")
139 msg.rewind()
140 assert "rsa-sha2-256" == msg.get_text()
141 signed = msg.get_binary() # for comparison later
142
143 # Load cert and inspect its internals
144 key.load_certificate(_support("rsa.key-cert.pub"))
145 assert key.public_blob is not None
146 assert key.public_blob.key_type == "[email protected]"
147 assert key.public_blob.comment == "test_rsa.key.pub"
148 msg = Message(key.public_blob.key_blob)
149 # cert type
150 assert msg.get_text() == "[email protected]"
151 # nonce
152 msg.get_string()
153 # public numbers
154 assert msg.get_mpint() == key.public_numbers.e
155 assert msg.get_mpint() == key.public_numbers.n
156 # serial number
157 assert msg.get_int64() == 1234
158 # TODO: whoever wrote the OG tests didn't care about the remaining
159 # fields from
160 # https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys
161 # so neither do I, for now...
162
163 # Sign cert-style (still SHA256 - so this actually does almost
164 # exactly the same thing under the hood as the previous sign)
165 msg = key.sign_ssh_data(data, "[email protected]")
166 msg.rewind()
167 assert "rsa-sha2-256" == msg.get_text()
168 assert signed == msg.get_binary() # same signature as above
169 msg.rewind()
170 assert key.verify_ssh_sig(b"ice weasels", msg) # our data verified
171
172 def loading_cert_of_different_type_from_key_raises_ValueError(self):
173 edkey = Ed25519Key.from_private_key_file(_support("ed25519.key"))
174 err = "PublicBlob type [email protected] incompatible with key type ssh-ed25519" # noqa
175 with raises(ValueError, match=err):
176 edkey.load_certificate(_support("rsa.key-cert.pub"))
177
178 def fingerprint(self, keys):
179 # NOTE: Hardcoded fingerprint expectation stored in fixture.
180 assert keys.pkey.fingerprint == keys.expected_fp
181
182 def algorithm_name(self, keys):
183 key = keys.pkey
184 if isinstance(key, RSAKey):
185 assert key.algorithm_name == "RSA"
186 elif isinstance(key, ECDSAKey):
187 assert key.algorithm_name == "ECDSA"
188 elif isinstance(key, Ed25519Key):
189 assert key.algorithm_name == "ED25519"
190 # TODO: corner case: AgentKey, whose .name can be cert-y (due to the
191 # value of the name field passed via agent protocol) and thus
192 # algorithm_name is eg "RSA-CERT" - keys loaded directly from disk will
193 # never look this way, even if they have a .public_blob attached.
194
195 class equality_and_hashing:
196 def same_key_is_equal_to_itself(self, keys):
197 assert keys.pkey == keys.pkey2
198
199 def same_key_same_hash(self, keys):
200 # NOTE: this isn't a great test due to hashseed randomization under
201 # Python 3 preventing use of static values, but it does still prove
202 # that __hash__ is implemented/doesn't explode & works across
203 # instances
204 assert hash(keys.pkey) == hash(keys.pkey2)
205
206 def keys_are_not_equal_to_other_types(self, keys):
207 for value in [None, True, ""]:
208 assert keys.pkey != value
209
210 class identifiers_classmethods:
211 def default_is_class_name_attribute(self):
212 # NOTE: not all classes _have_ this, only the ones that don't
213 # customize identifiers().
214 class MyKey(PKey):
215 name = "it me"
216
217 assert MyKey.identifiers() == ["it me"]
218
219 def rsa_is_all_combos_of_cert_and_sha_type(self):
220 assert RSAKey.identifiers() == [
221 "rsa-sha2-256",
222 "[email protected]",
223 "rsa-sha2-512",
224 "[email protected]",
225 # Still required for identifying keys-not-algorithms! But now
226 # they come last.
227 "ssh-rsa",
228 "[email protected]",
229 ]
230
231 def ed25519_is_protocol_name(self):
•232 assert Ed25519Key.identifiers() == [
233 "ssh-ed25519",
234 "[email protected]",
235 ]
236
237 def ecdsa_is_all_curve_names(self):
238 assert ECDSAKey.identifiers() == [
239 "ecdsa-sha2-nistp256",
240 "ecdsa-sha2-nistp384",
241 "ecdsa-sha2-nistp521",
242 ]
243
244 class write_private_key_and_file:
245 @mark.parametrize(
246 "key_path, expected_class",
247 [
248 ("rsa.key", RSAPrivateKey),
249 ("ecdsa-256.key", EllipticCurvePrivateKey),
250 # TODO: Ed25519 after we sort it out
251 ],
252 )
253 def uses_private_key_property(
254 self, key_path: str, expected_class: PrivateKey
255 ) -> None:
256 key_obj = PKey.from_path(_support(key_path))
257 assert isinstance(key_obj.private_key, expected_class)
258
259 # TODO: Ed25519 after we sort its writing out
260 @mark.parametrize(
261 "key_class, key_kwargs, key_name",
262 [
263 (RSAKey, dict(bits=4098), "RSA"),
264 (ECDSAKey, dict(bits=384), "EC"),
265 ],
266 )
267 @mark.parametrize("key_format", [PEM, OPENSSH])
268 def can_write_multiple_formats(
269 self,
270 key_class: str,
271 key_kwargs: dict,
272 key_format: PrivateKey,
273 key_name: str,
274 tmp_path: Path,
275 ) -> None:
276 # Roundtrip-as-proof
277 temp_key = tmp_path / "my.key"
278 key = key_class.generate(**key_kwargs)
279 key.write_private_key_file(
280 filename=str(temp_key), file_format=key_format
281 )
282 read_key = PKey.from_path(temp_key)
283 assert read_key == key
284 # Paranoia seasoning
285 if key_format is PEM:
286 assert f"BEGIN {key_name} PRIVATE KEY" in temp_key.read_text()
287 elif key_format is OPENSSH:
288 assert "BEGIN OPENSSH PRIVATE KEY" in temp_key.read_text()
289
290
291 class Ed25519Key_:
292 def has_non_excepting_repr_during_load_errors(self) -> None:
293 """
294 Inside baseball: don't throw scary looking AttributeErrors inside
295 repr() shown during other errors (eg "normal" load errors due to common
296 case of trying an unknown key input as each possible type).
297
298 Most PKey subclasses don't have this particular problem, Ed25519Key
299 does due to its original implementation where key material attributes
300 had no default assignment.
301 """
302 with raises(
303 SSHException, match="not a valid OPENSSH private key file"
304 ) as info:
305 Ed25519Key(file_obj=StringIO("ohai! I have lines. Technically."))
306 # When bug under test is not fixed, this will blow up with
307 # AttributeErrors about _signing_key/_verifying_key (as they won't have
308 # been assigned).
309 # When fixed, we get a normal looking repr (albeit whose fingerprint
310 # will effectively be that of an 'empty' key bytes)
311 assert (
312 repr(info.traceback[1].locals["self"])
313 == "PKey(alg=ED25519, bits=256, fp=SHA256:UsIasxMWEd9VFEwjARWWtGJ08DgHp1eib3gSBLed54U)"
314 )