Debian Codegraph @

lib/ansible/_internal/_ssh/_ssh_agent.py

raw
1 # Copyright: Contributors to the Ansible project
2 # BSD 3 Clause License (see licenses/BSD-3-Clause.txt or https://opensource.org/license/bsd-3-clause/)
3
4 from __future__ import annotations
5
6 import binascii
7 import dataclasses
8 import enum
9 import functools
10 import hashlib
11 import socket
12 import types
13 import typing as t
14
15 try:
16 from cryptography.hazmat.primitives import serialization
17 from cryptography.hazmat.primitives.asymmetric.dsa import (
18 DSAParameterNumbers,
19 DSAPrivateKey,
20 DSAPublicKey,
21 DSAPublicNumbers,
22 )
23 from cryptography.hazmat.primitives.asymmetric.ec import (
24 EllipticCurve,
25 EllipticCurvePrivateKey,
26 EllipticCurvePublicKey,
27 SECP256R1,
28 SECP384R1,
29 SECP521R1,
30 )
31 from cryptography.hazmat.primitives.asymmetric.ed25519 import (
32 Ed25519PrivateKey,
33 Ed25519PublicKey,
34 )
35 from cryptography.hazmat.primitives.asymmetric.rsa import (
36 RSAPrivateKey,
37 RSAPublicKey,
38 RSAPublicNumbers,
39 )
40 except ImportError:
41 HAS_CRYPTOGRAPHY = False
42 else:
43 HAS_CRYPTOGRAPHY = True
44
45 CryptoPublicKey = t.Union[
46 DSAPublicKey,
47 EllipticCurvePublicKey,
48 Ed25519PublicKey,
49 RSAPublicKey,
50 ]
51
52 CryptoPrivateKey = t.Union[
53 DSAPrivateKey,
54 EllipticCurvePrivateKey,
55 Ed25519PrivateKey,
56 RSAPrivateKey,
57 ]
58
59
60 if t.TYPE_CHECKING:
61 from cryptography.hazmat.primitives.asymmetric.dsa import DSAPrivateNumbers
62 from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateNumbers
63 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers
64
65
66 _SSH_AGENT_CLIENT_SOCKET_TIMEOUT = 10
67 _SSH_AGENT_MAX_RESPONSE_BYTES = 256 * 1024 # not part of the RFC, just a safety measure
68
69
70 class ProtocolMsgNumbers(enum.IntEnum):
71 # Responses
72 SSH_AGENT_FAILURE = 5
73 SSH_AGENT_SUCCESS = 6
74 SSH_AGENT_IDENTITIES_ANSWER = 12
75 SSH_AGENT_SIGN_RESPONSE = 14
76 SSH_AGENT_EXTENSION_FAILURE = 28
77 SSH_AGENT_EXTENSION_RESPONSE = 29
78
79 # Constraints
80 SSH_AGENT_CONSTRAIN_LIFETIME = 1
81 SSH_AGENT_CONSTRAIN_CONFIRM = 2
82 SSH_AGENT_CONSTRAIN_EXTENSION = 255
83
84 # Requests
85 SSH_AGENTC_REQUEST_IDENTITIES = 11
86 SSH_AGENTC_SIGN_REQUEST = 13
87 SSH_AGENTC_ADD_IDENTITY = 17
88 SSH_AGENTC_REMOVE_IDENTITY = 18
89 SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19
90 SSH_AGENTC_ADD_SMARTCARD_KEY = 20
91 SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21
92 SSH_AGENTC_LOCK = 22
93 SSH_AGENTC_UNLOCK = 23
94 SSH_AGENTC_ADD_ID_CONSTRAINED = 25
95 SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26
96 SSH_AGENTC_EXTENSION = 27
97
98 def to_blob(self) -> bytes:
99 return bytes([self])
100
101
102 class SshAgentFailure(RuntimeError):
103 """Server failure or unexpected response."""
104
105
106 # NOTE: Classes below somewhat represent "Data Type Representations Used in the SSH Protocols"
107 # as specified by RFC4251
108
109
110 @t.runtime_checkable
111 class SupportsToBlob(t.Protocol):
112 def to_blob(self) -> bytes: ...
113
114
115 @t.runtime_checkable
116 class SupportsFromBlob(t.Protocol):
117 @classmethod
118 def from_blob(cls, blob: memoryview | bytes) -> t.Self: ...
119
120 @classmethod
121 def consume_from_blob(cls, blob: memoryview | bytes) -> tuple[t.Self, memoryview | bytes]: ...
122
123
124 def _split_blob(blob: memoryview | bytes, length: int) -> tuple[memoryview | bytes, memoryview | bytes]:
125 if len(blob) < length:
126 raise ValueError("_split_blob: unexpected data length")
127 return blob[:length], blob[length:]
128
129
130 class VariableSized:
131 @classmethod
132 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
133 raise NotImplementedError
134
135 @classmethod
136 def consume_from_blob(cls, blob: memoryview | bytes) -> tuple[t.Self, memoryview | bytes]:
137 length = uint32.from_blob(blob[:4])
138 blob = blob[4:]
139 data, rest = _split_blob(blob, length)
140 return cls.from_blob(data), rest
141
142
143 class uint32(int):
144 def to_blob(self) -> bytes:
145 return self.to_bytes(length=4, byteorder='big')
146
147 @classmethod
148 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
149 return cls.from_bytes(blob, byteorder='big')
150
151 @classmethod
152 def consume_from_blob(cls, blob: memoryview | bytes) -> tuple[t.Self, memoryview | bytes]:
153 length = uint32(4)
154 data, rest = _split_blob(blob, length)
155 return cls.from_blob(data), rest
156
157
158 class mpint(int, VariableSized):
159 def to_blob(self) -> bytes:
160 if self < 0:
161 raise ValueError("negative mpint not allowed")
162 if self == 0:
163 return uint32(self).to_blob()
164 nbytes = (self.bit_length() + 8) // 8
165 ret = bytearray(self.to_bytes(length=nbytes, byteorder='big'))
166 ret[:0] = uint32(len(ret)).to_blob()
167 return ret
168
169 @classmethod
170 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
171 if blob and blob[0] > 127:
172 raise ValueError("Invalid data")
173 return cls.from_bytes(blob, byteorder='big')
174
175
176 class constraints(bytes):
177 def to_blob(self) -> bytes:
178 return self
179
180
181 class binary_string(bytes, VariableSized):
182 def to_blob(self) -> bytes:
183 return uint32(len(self)).to_blob() + self
184
185 @classmethod
186 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
187 return cls(blob)
188
189
190 class unicode_string(str, VariableSized):
191 def to_blob(self) -> bytes:
192 val = self.encode('utf-8')
193 return uint32(len(val)).to_blob() + val
194
195 @classmethod
196 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
197 return cls(bytes(blob).decode('utf-8'))
198
199
200 class KeyAlgo(VariableSized, enum.StrEnum):
201 RSA = "ssh-rsa"
202 DSA = "ssh-dss"
203 ECDSA256 = "ecdsa-sha2-nistp256"
204 SKECDSA256 = "[email protected]"
205 ECDSA384 = "ecdsa-sha2-nistp384"
206 ECDSA521 = "ecdsa-sha2-nistp521"
207 ED25519 = "ssh-ed25519"
208 SKED25519 = "[email protected]"
209 RSASHA256 = "rsa-sha2-256"
210 RSASHA512 = "rsa-sha2-512"
211
212 @property
213 def main_type(self) -> str:
214 match self:
215 case self.RSA:
216 return 'RSA'
217 case self.DSA:
218 return 'DSA'
219 case self.ECDSA256 | self.ECDSA384 | self.ECDSA521:
220 return 'ECDSA'
221 case self.ED25519:
222 return 'ED25519'
223 case _:
224 raise NotImplementedError(self.name)
225
226 def to_blob(self) -> bytes:
227 b_self = self.encode('utf-8')
228 return uint32(len(b_self)).to_blob() + b_self
229
230 @classmethod
231 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
232 return cls(bytes(blob).decode('utf-8'))
233
234
235 if HAS_CRYPTOGRAPHY:
236 _ECDSA_KEY_TYPE: dict[KeyAlgo, type[EllipticCurve]] = {
237 KeyAlgo.ECDSA256: SECP256R1,
238 KeyAlgo.ECDSA384: SECP384R1,
239 KeyAlgo.ECDSA521: SECP521R1,
240 }
241
242
243 @dataclasses.dataclass
244 class Msg:
245 def to_blob(self) -> bytes:
246 rv = bytearray()
247 for field in dataclasses.fields(self):
248 fv = getattr(self, field.name)
249 if isinstance(fv, SupportsToBlob):
250 rv.extend(fv.to_blob())
251 else:
252 raise NotImplementedError(field.type)
253 return rv
254
255 @classmethod
256 def from_blob(cls, blob: memoryview | bytes) -> t.Self:
257 args: list[t.Any] = []
258 for _field_name, field_type in t.get_type_hints(cls).items():
259 if isinstance(field_type, SupportsFromBlob):
260 fv, blob = field_type.consume_from_blob(blob)
261 args.append(fv)
262 else:
263 raise NotImplementedError(str(field_type))
264 return cls(*args)
265
266
267 @dataclasses.dataclass
268 class PrivateKeyMsg(Msg):
269 @staticmethod
270 def from_private_key(private_key: CryptoPrivateKey) -> PrivateKeyMsg:
271 match private_key:
272 case RSAPrivateKey():
273 rsa_pn: RSAPrivateNumbers = private_key.private_numbers()
274 return RSAPrivateKeyMsg(
275 KeyAlgo.RSA,
276 mpint(rsa_pn.public_numbers.n),
277 mpint(rsa_pn.public_numbers.e),
278 mpint(rsa_pn.d),
279 mpint(rsa_pn.iqmp),
280 mpint(rsa_pn.p),
281 mpint(rsa_pn.q),
282 )
283 case DSAPrivateKey():
284 dsa_pn: DSAPrivateNumbers = private_key.private_numbers()
285 return DSAPrivateKeyMsg(
286 KeyAlgo.DSA,
287 mpint(dsa_pn.public_numbers.parameter_numbers.p),
288 mpint(dsa_pn.public_numbers.parameter_numbers.q),
289 mpint(dsa_pn.public_numbers.parameter_numbers.g),
290 mpint(dsa_pn.public_numbers.y),
291 mpint(dsa_pn.x),
292 )
293 case EllipticCurvePrivateKey():
294 ecdsa_pn: EllipticCurvePrivateNumbers = private_key.private_numbers()
295 key_size = private_key.key_size
296 return EcdsaPrivateKeyMsg(
297 getattr(KeyAlgo, f'ECDSA{key_size}'),
298 unicode_string(f'nistp{key_size}'),
299 binary_string(
300 private_key.public_key().public_bytes(
301 encoding=serialization.Encoding.X962,
302 format=serialization.PublicFormat.UncompressedPoint,
303 )
304 ),
305 mpint(ecdsa_pn.private_value),
306 )
307 case Ed25519PrivateKey():
308 public_bytes = private_key.public_key().public_bytes(
309 encoding=serialization.Encoding.Raw,
310 format=serialization.PublicFormat.Raw,
311 )
312 private_bytes = private_key.private_bytes(
313 encoding=serialization.Encoding.Raw,
314 format=serialization.PrivateFormat.Raw,
315 encryption_algorithm=serialization.NoEncryption(),
316 )
317 return Ed25519PrivateKeyMsg(
318 KeyAlgo.ED25519,
319 binary_string(public_bytes),
320 binary_string(private_bytes + public_bytes),
321 )
322 case _:
323 raise NotImplementedError(private_key)
324
325
326 @dataclasses.dataclass(order=True, slots=True)
327 class RSAPrivateKeyMsg(PrivateKeyMsg):
328 type: KeyAlgo
329 n: mpint
330 e: mpint
331 d: mpint
332 iqmp: mpint
333 p: mpint
334 q: mpint
335 comment: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
336 constraints: constraints = dataclasses.field(default=constraints(b''))
337
338
339 @dataclasses.dataclass(order=True, slots=True)
340 class DSAPrivateKeyMsg(PrivateKeyMsg):
341 type: KeyAlgo
342 p: mpint
343 q: mpint
344 g: mpint
345 y: mpint
346 x: mpint
347 comment: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
348 constraints: constraints = dataclasses.field(default=constraints(b''))
349
350
351 @dataclasses.dataclass(order=True, slots=True)
352 class EcdsaPrivateKeyMsg(PrivateKeyMsg):
353 type: KeyAlgo
354 ecdsa_curve_name: unicode_string
355 Q: binary_string
356 d: mpint
357 comment: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
358 constraints: constraints = dataclasses.field(default=constraints(b''))
359
360
361 @dataclasses.dataclass(order=True, slots=True)
362 class Ed25519PrivateKeyMsg(PrivateKeyMsg):
363 type: KeyAlgo
364 enc_a: binary_string
365 k_env_a: binary_string
366 comment: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
367 constraints: constraints = dataclasses.field(default=constraints(b''))
368
369
370 @dataclasses.dataclass
371 class PublicKeyMsg(Msg):
372 @staticmethod
373 def get_dataclass(type: KeyAlgo) -> type[
374 t.Union[
375 RSAPublicKeyMsg,
376 EcdsaPublicKeyMsg,
377 Ed25519PublicKeyMsg,
378 DSAPublicKeyMsg,
379 ]
380 ]:
381 match type:
382 case KeyAlgo.RSA:
383 return RSAPublicKeyMsg
384 case KeyAlgo.ECDSA256 | KeyAlgo.ECDSA384 | KeyAlgo.ECDSA521:
385 return EcdsaPublicKeyMsg
386 case KeyAlgo.ED25519:
387 return Ed25519PublicKeyMsg
388 case KeyAlgo.DSA:
389 return DSAPublicKeyMsg
390 case _:
391 raise NotImplementedError(type)
392
393 @functools.cached_property
394 def public_key(self) -> CryptoPublicKey:
395 type: KeyAlgo = self.type
396 match type:
397 case KeyAlgo.RSA:
398 return RSAPublicNumbers(self.e, self.n).public_key()
399 case KeyAlgo.ECDSA256 | KeyAlgo.ECDSA384 | KeyAlgo.ECDSA521:
400 curve = _ECDSA_KEY_TYPE[KeyAlgo(type)]
401 return EllipticCurvePublicKey.from_encoded_point(curve(), self.Q)
402 case KeyAlgo.ED25519:
403 return Ed25519PublicKey.from_public_bytes(self.enc_a)
404 case KeyAlgo.DSA:
405 return DSAPublicNumbers(self.y, DSAParameterNumbers(self.p, self.q, self.g)).public_key()
406 case _:
407 raise NotImplementedError(type)
408
409 @staticmethod
410 def from_public_key(public_key: CryptoPublicKey) -> PublicKeyMsg:
411 match public_key:
412 case DSAPublicKey():
413 dsa_pn: DSAPublicNumbers = public_key.public_numbers()
414 return DSAPublicKeyMsg(
415 KeyAlgo.DSA,
416 mpint(dsa_pn.parameter_numbers.p),
417 mpint(dsa_pn.parameter_numbers.q),
418 mpint(dsa_pn.parameter_numbers.g),
419 mpint(dsa_pn.y),
420 )
421 case EllipticCurvePublicKey():
422 return EcdsaPublicKeyMsg(
423 getattr(KeyAlgo, f'ECDSA{public_key.curve.key_size}'),
424 unicode_string(f'nistp{public_key.curve.key_size}'),
425 binary_string(
426 public_key.public_bytes(
427 encoding=serialization.Encoding.X962,
428 format=serialization.PublicFormat.UncompressedPoint,
429 )
430 ),
431 )
432 case Ed25519PublicKey():
433 return Ed25519PublicKeyMsg(
434 KeyAlgo.ED25519,
435 binary_string(
436 public_key.public_bytes(
437 encoding=serialization.Encoding.Raw,
438 format=serialization.PublicFormat.Raw,
439 )
440 ),
441 )
442 case RSAPublicKey():
443 rsa_pn: RSAPublicNumbers = public_key.public_numbers()
444 return RSAPublicKeyMsg(KeyAlgo.RSA, mpint(rsa_pn.e), mpint(rsa_pn.n))
445 case _:
446 raise NotImplementedError(public_key)
447
448 @functools.cached_property
449 def fingerprint(self) -> str:
450 return binascii.b2a_base64(hashlib.sha256(self.to_blob()).digest(), newline=False).rstrip(b'=').decode('utf-8')
451
452
453 @dataclasses.dataclass(order=True, slots=True)
454 class RSAPublicKeyMsg(PublicKeyMsg):
455 type: KeyAlgo
456 e: mpint
457 n: mpint
458
459
460 @dataclasses.dataclass(order=True, slots=True)
461 class DSAPublicKeyMsg(PublicKeyMsg):
462 type: KeyAlgo
463 p: mpint
464 q: mpint
465 g: mpint
466 y: mpint
467
468
469 @dataclasses.dataclass(order=True, slots=True)
470 class EcdsaPublicKeyMsg(PublicKeyMsg):
471 type: KeyAlgo
472 ecdsa_curve_name: unicode_string
473 Q: binary_string
474
475
476 @dataclasses.dataclass(order=True, slots=True)
477 class Ed25519PublicKeyMsg(PublicKeyMsg):
478 type: KeyAlgo
479 enc_a: binary_string
480
481
482 @dataclasses.dataclass(order=True, frozen=True, slots=True)
483 class Identity:
484 key: PublicKeyMsg
485 comment: unicode_string
486
487
488 class SshAgentClient:
489 def __init__(self, auth_sock: str) -> None:
490 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
491 self._sock.settimeout(_SSH_AGENT_CLIENT_SOCKET_TIMEOUT)
492 self._sock.connect(auth_sock)
493
494 def close(self) -> None:
495 self._sock.close()
496
497 def __enter__(self) -> t.Self:
498 return self
499
500 def __exit__(
501 self,
502 exc_type: type[BaseException] | None,
503 exc_value: BaseException | None,
504 traceback: types.TracebackType | None,
505 ) -> None:
506 self.close()
507
508 def _read_all(self, bytes_to_read: int) -> bytes:
509 data_read = bytearray()
510 while bytes_to_read:
511 data = self._sock.recv(bytes_to_read)
512 if not data:
513 raise ConnectionError("agent: connection closed")
514 bytes_to_read -= len(data)
515 data_read.extend(data)
516 return bytes(data_read)
517
518 def send(self, msg: bytes) -> bytes:
519 length = uint32(len(msg)).to_blob()
520 self._sock.sendall(length + msg)
521 bufsize = uint32.from_blob(self._read_all(4))
522 if bufsize > _SSH_AGENT_MAX_RESPONSE_BYTES:
523 raise SshAgentFailure("agent: response too large")
524 resp = self._read_all(bufsize)
525 if resp[0] == ProtocolMsgNumbers.SSH_AGENT_FAILURE:
526 raise SshAgentFailure('agent: failure')
527 return resp
528
529 def remove_all(self) -> None:
530 self.send(ProtocolMsgNumbers.SSH_AGENTC_REMOVE_ALL_IDENTITIES.to_blob())
531
532 def remove(self, public_key: CryptoPublicKey) -> None:
533 key_blob = PublicKeyMsg.from_public_key(public_key).to_blob()
534 self.send(ProtocolMsgNumbers.SSH_AGENTC_REMOVE_IDENTITY.to_blob() + uint32(len(key_blob)).to_blob() + key_blob)
535
536 def add(
537 self,
538 private_key: CryptoPrivateKey,
539 comment: str | None = None,
540 lifetime: int | None = None,
541 confirm: bool | None = None,
542 ) -> None:
543 key_msg = PrivateKeyMsg.from_private_key(private_key)
544 key_msg.comment = unicode_string(comment or '')
545 if lifetime:
546 key_msg.constraints += constraints([ProtocolMsgNumbers.SSH_AGENT_CONSTRAIN_LIFETIME]).to_blob() + uint32(lifetime).to_blob()
547 if confirm:
548 key_msg.constraints += constraints([ProtocolMsgNumbers.SSH_AGENT_CONSTRAIN_CONFIRM]).to_blob()
549
550 if key_msg.constraints:
551 msg = ProtocolMsgNumbers.SSH_AGENTC_ADD_ID_CONSTRAINED.to_blob()
552 else:
553 msg = ProtocolMsgNumbers.SSH_AGENTC_ADD_IDENTITY.to_blob()
554 msg += key_msg.to_blob()
555 self.send(msg)
556
557 def list(self) -> list[Identity]:
558 req = ProtocolMsgNumbers.SSH_AGENTC_REQUEST_IDENTITIES.to_blob()
559 r = memoryview(bytearray(self.send(req)))
560 if r[0] != ProtocolMsgNumbers.SSH_AGENT_IDENTITIES_ANSWER:
561 raise SshAgentFailure('agent: non-identities answer received for identities list')
562
563 blob = r[1:]
564 nkeys, blob = uint32.consume_from_blob(blob)
565 rv = []
566 for i in range(nkeys):
567 key_blob, blob = self._consume_field(blob)
568
569 peek_key_algo, dummy = self._consume_field(key_blob)
570 pub_key_msg_cls = PublicKeyMsg.get_dataclass(KeyAlgo(bytes(peek_key_algo).decode('utf-8')))
571
572 comment_blob, blob = self._consume_field(blob)
573
574 rv.append(Identity(pub_key_msg_cls.from_blob(key_blob), unicode_string.from_blob(comment_blob)))
575
576 if blob:
577 raise SshAgentFailure("agent: received more keys than advertised")
578
579 return rv
580
581 @staticmethod
582 def _consume_field(blob: memoryview | bytes) -> tuple[memoryview | bytes, memoryview | bytes]:
583 length = uint32.from_blob(blob[:4])
584 blob = blob[4:]
585 data, rest = _split_blob(blob, length)
586 return data, rest
587
588 def __contains__(self, public_key: CryptoPublicKey) -> bool:
589 msg = PublicKeyMsg.from_public_key(public_key)
590 return any(i.key == msg for i in self.list())
591
592
593 @functools.cache
594 def key_data_into_crypto_objects(key_data: bytes, passphrase: bytes | None) -> tuple[CryptoPrivateKey, CryptoPublicKey, str]:
595 private_key = serialization.ssh.load_ssh_private_key(key_data, passphrase)
596 public_key = private_key.public_key()
597 fingerprint = PublicKeyMsg.from_public_key(public_key).fingerprint
598
599 return private_key, public_key, fingerprint