| 1 |
# Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import abc |
| 11 |
import binascii |
| 12 |
import datetime as _datetime |
| 13 |
import os |
| 14 |
import typing as t |
| 15 |
from base64 import b64encode |
| 16 |
from datetime import datetime |
| 17 |
from hashlib import sha256 |
| 18 |
|
| 19 |
from ansible.module_utils.common.text.converters import to_text |
| 20 |
|
| 21 |
from ansible_collections.community.crypto.plugins.module_utils._openssh.utils import ( |
| 22 |
OpensshParser, |
| 23 |
_OpensshWriter, |
| 24 |
) |
| 25 |
from ansible_collections.community.crypto.plugins.module_utils._time import UTC as _UTC |
| 26 |
from ansible_collections.community.crypto.plugins.module_utils._time import ( |
| 27 |
add_or_remove_timezone as _add_or_remove_timezone, |
| 28 |
) |
| 29 |
from ansible_collections.community.crypto.plugins.module_utils._time import ( |
| 30 |
convert_relative_to_datetime, |
| 31 |
) |
| 32 |
|
| 33 |
if t.TYPE_CHECKING: |
| 34 |
from ansible_collections.community.crypto.plugins.module_utils._openssh.cryptography import ( # pragma: no cover |
| 35 |
PubKeyType, |
| 36 |
) |
| 37 |
|
| 38 |
DateFormat = t.Literal["human_readable", "openssh", "timestamp"] # pragma: no cover |
| 39 |
DateFormatStr = t.Literal["human_readable", "openssh"] # pragma: no cover |
| 40 |
DateFormatInt = t.Literal["timestamp"] # pragma: no cover |
| 41 |
|
| 42 |
|
| 43 |
# Protocol References |
| 44 |
# ------------------- |
| 45 |
# https://datatracker.ietf.org/doc/html/rfc4251 |
| 46 |
# https://datatracker.ietf.org/doc/html/rfc4253 |
| 47 |
# https://datatracker.ietf.org/doc/html/rfc5656 |
| 48 |
# https://datatracker.ietf.org/doc/html/rfc8032 |
| 49 |
# https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD |
| 50 |
# |
| 51 |
# Inspired by: |
| 52 |
# ------------ |
| 53 |
# https://github.com/pyca/cryptography/blob/main/src/cryptography/hazmat/primitives/serialization/ssh.py |
| 54 |
# https://github.com/paramiko/paramiko/blob/master/paramiko/message.py |
| 55 |
|
| 56 |
|
| 57 |
# See https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD |
| 58 |
_USER_TYPE = 1 |
| 59 |
_HOST_TYPE = 2 |
| 60 |
|
| 61 |
_SSH_TYPE_STRINGS: dict[PubKeyType, bytes] = { |
| 62 |
"rsa": b"ssh-rsa", |
| 63 |
"dsa": b"ssh-dss", |
| 64 |
"ecdsa-nistp256": b"ecdsa-sha2-nistp256", |
| 65 |
"ecdsa-nistp384": b"ecdsa-sha2-nistp384", |
| 66 |
"ecdsa-nistp521": b"ecdsa-sha2-nistp521", |
| 67 |
"ed25519": b"ssh-ed25519", |
| 68 |
} |
| 69 |
_CERT_SUFFIX_V01 = b"[email protected]" |
| 70 |
|
| 71 |
# See https://datatracker.ietf.org/doc/html/rfc5656#section-6.1 |
| 72 |
_ECDSA_CURVE_IDENTIFIERS = { |
| 73 |
"ecdsa-nistp256": b"nistp256", |
| 74 |
"ecdsa-nistp384": b"nistp384", |
| 75 |
"ecdsa-nistp521": b"nistp521", |
| 76 |
} |
| 77 |
_ECDSA_CURVE_IDENTIFIERS_LOOKUP: dict[bytes, PubKeyType] = { |
| 78 |
b"nistp256": "ecdsa-nistp256", |
| 79 |
b"nistp384": "ecdsa-nistp384", |
| 80 |
b"nistp521": "ecdsa-nistp521", |
| 81 |
} |
| 82 |
|
| 83 |
_ALWAYS = _add_or_remove_timezone(datetime(1970, 1, 1), with_timezone=True) |
| 84 |
_FOREVER = datetime(9999, 12, 31, 23, 59, 59, 999999, _UTC) |
| 85 |
|
| 86 |
_CRITICAL_OPTIONS = ( |
| 87 |
"force-command", |
| 88 |
"source-address", |
| 89 |
"verify-required", |
| 90 |
) |
| 91 |
|
| 92 |
_DIRECTIVES = ( |
| 93 |
"clear", |
| 94 |
"no-x11-forwarding", |
| 95 |
"no-agent-forwarding", |
| 96 |
"no-port-forwarding", |
| 97 |
"no-pty", |
| 98 |
"no-user-rc", |
| 99 |
) |
| 100 |
|
| 101 |
_EXTENSIONS = ( |
| 102 |
"permit-x11-forwarding", |
| 103 |
"permit-agent-forwarding", |
| 104 |
"permit-port-forwarding", |
| 105 |
"permit-pty", |
| 106 |
"permit-user-rc", |
| 107 |
) |
| 108 |
|
| 109 |
|
| 110 |
class OpensshCertificateTimeParameters: |
| 111 |
def __init__( |
| 112 |
self, *, valid_from: str | bytes | int, valid_to: str | bytes | int |
| 113 |
) -> None: |
| 114 |
self._valid_from = self.to_datetime(valid_from) |
| 115 |
self._valid_to = self.to_datetime(valid_to) |
| 116 |
|
| 117 |
if self._valid_from > self._valid_to: |
| 118 |
raise ValueError( |
| 119 |
f"Valid from: {valid_from!r} must not be greater than Valid to: {valid_to!r}" |
| 120 |
) |
| 121 |
|
| 122 |
def __eq__(self, other: object) -> bool: |
| 123 |
if not isinstance(other, type(self)): |
| 124 |
return NotImplemented |
| 125 |
return ( |
| 126 |
self._valid_from == other._valid_from and self._valid_to == other._valid_to |
| 127 |
) |
| 128 |
|
| 129 |
def __ne__(self, other: object) -> bool: |
| 130 |
return not self == other |
| 131 |
|
| 132 |
@property |
| 133 |
def validity_string(self) -> str: |
| 134 |
if not (self._valid_from == _ALWAYS and self._valid_to == _FOREVER): |
| 135 |
return f"{self.valid_from(date_format='openssh')}:{self.valid_to(date_format='openssh')}" |
| 136 |
return "" |
| 137 |
|
| 138 |
@t.overload |
| 139 |
def valid_from(self, date_format: DateFormatStr) -> str: ... |
| 140 |
|
| 141 |
@t.overload |
| 142 |
def valid_from(self, date_format: DateFormatInt) -> int: ... |
| 143 |
|
| 144 |
@t.overload |
| 145 |
def valid_from(self, date_format: DateFormat) -> str | int: ... |
| 146 |
|
| 147 |
def valid_from(self, date_format: DateFormat) -> str | int: |
| 148 |
return self.format_datetime(self._valid_from, date_format=date_format) |
| 149 |
|
| 150 |
@t.overload |
| 151 |
def valid_to(self, date_format: DateFormatStr) -> str: ... |
| 152 |
|
| 153 |
@t.overload |
| 154 |
def valid_to(self, date_format: DateFormatInt) -> int: ... |
| 155 |
|
| 156 |
@t.overload |
| 157 |
def valid_to(self, date_format: DateFormat) -> str | int: ... |
| 158 |
|
| 159 |
def valid_to(self, date_format: DateFormat) -> str | int: |
| 160 |
return self.format_datetime(self._valid_to, date_format=date_format) |
| 161 |
|
| 162 |
def within_range(self, valid_at: str | bytes | int | None) -> bool: |
| 163 |
if valid_at is not None: |
| 164 |
valid_at_datetime = self.to_datetime(valid_at) |
| 165 |
return self._valid_from <= valid_at_datetime <= self._valid_to |
| 166 |
return True |
| 167 |
|
| 168 |
@t.overload |
| 169 |
@staticmethod |
| 170 |
def format_datetime(dt: datetime, *, date_format: DateFormatStr) -> str: ... |
| 171 |
|
| 172 |
@t.overload |
| 173 |
@staticmethod |
| 174 |
def format_datetime(dt: datetime, *, date_format: DateFormatInt) -> int: ... |
| 175 |
|
| 176 |
@t.overload |
| 177 |
@staticmethod |
| 178 |
def format_datetime(dt: datetime, *, date_format: DateFormat) -> str | int: ... |
| 179 |
|
| 180 |
@staticmethod |
| 181 |
def format_datetime(dt: datetime, *, date_format: DateFormat) -> str | int: |
| 182 |
if date_format in ("human_readable", "openssh"): |
| 183 |
if dt == _ALWAYS: |
| 184 |
return "always" |
| 185 |
if dt == _FOREVER: |
| 186 |
return "forever" |
| 187 |
return ( |
| 188 |
dt.isoformat().replace("+00:00", "") |
| 189 |
if date_format == "human_readable" |
| 190 |
else dt.strftime("%Y%m%d%H%M%S") |
| 191 |
) |
| 192 |
if date_format == "timestamp": |
| 193 |
td = dt - _ALWAYS |
| 194 |
return int( |
| 195 |
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 |
| 196 |
) |
| 197 |
raise ValueError(f"{date_format} is not a valid format") |
| 198 |
|
| 199 |
@staticmethod |
| 200 |
def to_datetime(time_string_or_timestamp: str | bytes | int) -> datetime: |
| 201 |
if isinstance(time_string_or_timestamp, (str, bytes)): |
| 202 |
return OpensshCertificateTimeParameters._time_string_to_datetime( |
| 203 |
to_text(time_string_or_timestamp.strip()) |
| 204 |
) |
| 205 |
if isinstance(time_string_or_timestamp, int): |
| 206 |
return OpensshCertificateTimeParameters._timestamp_to_datetime( |
| 207 |
time_string_or_timestamp |
| 208 |
) |
| 209 |
raise ValueError( |
| 210 |
f"Value must be of type (str, unicode, int) not {type(time_string_or_timestamp)}" |
| 211 |
) |
| 212 |
|
| 213 |
@staticmethod |
| 214 |
def _timestamp_to_datetime(timestamp: int) -> datetime: |
| 215 |
if timestamp == 0x0: |
| 216 |
return _ALWAYS |
| 217 |
if timestamp == 0xFFFFFFFFFFFFFFFF: |
| 218 |
return _FOREVER |
| 219 |
try: |
| 220 |
return datetime.fromtimestamp(timestamp, tz=_datetime.timezone.utc) |
| 221 |
except OverflowError as e: |
| 222 |
raise ValueError from e |
| 223 |
|
| 224 |
@staticmethod |
| 225 |
def _time_string_to_datetime(time_string: str) -> datetime: |
| 226 |
if time_string == "always": |
| 227 |
return _ALWAYS |
| 228 |
if time_string == "forever": |
| 229 |
return _FOREVER |
| 230 |
if is_relative_time_string(time_string): |
| 231 |
result = convert_relative_to_datetime(time_string, with_timezone=True) |
| 232 |
if result is None: |
| 233 |
raise ValueError |
| 234 |
return result |
| 235 |
result = None |
| 236 |
for time_format in ("%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"): |
| 237 |
try: |
| 238 |
result = _add_or_remove_timezone( |
| 239 |
datetime.strptime(time_string, time_format), |
| 240 |
with_timezone=True, |
| 241 |
) |
| 242 |
except ValueError: |
| 243 |
pass |
| 244 |
if result is None: |
| 245 |
raise ValueError |
| 246 |
return result |
| 247 |
|
| 248 |
|
| 249 |
_OpensshCertificateOption = t.TypeVar( |
| 250 |
"_OpensshCertificateOption", bound="OpensshCertificateOption" |
| 251 |
) |
| 252 |
|
| 253 |
|
| 254 |
class OpensshCertificateOption: |
| 255 |
def __init__( |
| 256 |
self, |
| 257 |
*, |
| 258 |
option_type: t.Literal["critical", "extension"], |
| 259 |
name: str | bytes, |
| 260 |
data: str | bytes, |
| 261 |
): |
| 262 |
if option_type not in ("critical", "extension"): |
| 263 |
raise ValueError("type must be either 'critical' or 'extension'") |
| 264 |
|
| 265 |
if not isinstance(name, (str, bytes)): |
| 266 |
raise TypeError(f"name must be a string not {type(name)}") |
| 267 |
|
| 268 |
if not isinstance(data, (str, bytes)): |
| 269 |
raise TypeError(f"data must be a string not {type(data)}") |
| 270 |
|
| 271 |
self._option_type = option_type |
| 272 |
self._name = name.lower() |
| 273 |
self._data = data |
| 274 |
|
| 275 |
def __eq__(self, other: object) -> bool: |
| 276 |
if not isinstance(other, type(self)): |
| 277 |
return NotImplemented |
| 278 |
|
| 279 |
return all( |
| 280 |
[ |
| 281 |
self._option_type == other._option_type, |
| 282 |
self._name == other._name, |
| 283 |
self._data == other._data, |
| 284 |
] |
| 285 |
) |
| 286 |
|
| 287 |
def __hash__(self) -> int: |
| 288 |
return hash((self._option_type, self._name, self._data)) |
| 289 |
|
| 290 |
def __ne__(self, other: object) -> bool: |
| 291 |
return not self == other |
| 292 |
|
| 293 |
def __str__(self) -> str: |
| 294 |
if self._data: |
| 295 |
return f"{self._name!r}={self._data!r}" |
| 296 |
return f"{self._name!r}" |
| 297 |
|
| 298 |
@property |
| 299 |
def data(self) -> str | bytes: |
| 300 |
return self._data |
| 301 |
|
| 302 |
@property |
| 303 |
def name(self) -> str | bytes: |
| 304 |
return self._name |
| 305 |
|
| 306 |
@property |
| 307 |
def type(self) -> t.Literal["critical", "extension"]: |
| 308 |
return self._option_type |
| 309 |
|
| 310 |
@classmethod |
| 311 |
def from_string( |
| 312 |
cls: t.Type[_OpensshCertificateOption], option_string: str # noqa: UP006 |
| 313 |
) -> _OpensshCertificateOption: |
| 314 |
if not isinstance(option_string, str): |
| 315 |
raise ValueError( |
| 316 |
f"option_string must be a string not {type(option_string)}" |
| 317 |
) |
| 318 |
option_type = None |
| 319 |
|
| 320 |
if ":" in option_string: |
| 321 |
option_type, value = option_string.strip().split(":", 1) |
| 322 |
if "=" in value: |
| 323 |
name, data = value.split("=", 1) |
| 324 |
else: |
| 325 |
name, data = value, "" |
| 326 |
elif "=" in option_string: |
| 327 |
name, data = option_string.strip().split("=", 1) |
| 328 |
else: |
| 329 |
name, data = option_string.strip(), "" |
| 330 |
|
| 331 |
return cls( |
| 332 |
# We have str, but we're expecting a specific literal: |
| 333 |
option_type=option_type or get_option_type(name.lower()), # type: ignore |
| 334 |
name=name, |
| 335 |
data=data, |
| 336 |
) |
| 337 |
|
| 338 |
|
| 339 |
if t.TYPE_CHECKING: |
| 340 |
|
| 341 |
class _OpensshCertificateInfoKwarg(t.TypedDict): |
| 342 |
nonce: t.NotRequired[bytes | None] |
| 343 |
serial: t.NotRequired[int | None] |
| 344 |
cert_type: t.NotRequired[int | None] |
| 345 |
key_id: t.NotRequired[bytes | None] |
| 346 |
principals: t.NotRequired[list[bytes] | None] |
| 347 |
valid_after: t.NotRequired[int | None] |
| 348 |
valid_before: t.NotRequired[int | None] |
| 349 |
critical_options: t.NotRequired[list[tuple[bytes, bytes]] | None] |
| 350 |
extensions: t.NotRequired[list[tuple[bytes, bytes]] | None] |
| 351 |
reserved: t.NotRequired[bytes | None] |
| 352 |
signing_key: t.NotRequired[bytes | None] |
| 353 |
|
| 354 |
|
| 355 |
class OpensshCertificateInfo(metaclass=abc.ABCMeta): |
| 356 |
"""Encapsulates all certificate information which is signed by a CA key""" |
| 357 |
|
| 358 |
def __init__( |
| 359 |
self, |
| 360 |
*, |
| 361 |
nonce: bytes | None = None, |
| 362 |
serial: int | None = None, |
| 363 |
cert_type: int | None = None, |
| 364 |
key_id: bytes | None = None, |
| 365 |
principals: list[bytes] | None = None, |
| 366 |
valid_after: int | None = None, |
| 367 |
valid_before: int | None = None, |
| 368 |
critical_options: list[tuple[bytes, bytes]] | None = None, |
| 369 |
extensions: list[tuple[bytes, bytes]] | None = None, |
| 370 |
reserved: bytes | None = None, |
| 371 |
signing_key: bytes | None = None, |
| 372 |
): |
| 373 |
self.nonce = nonce |
| 374 |
self.serial = serial |
| 375 |
self._cert_type: int | None = cert_type |
| 376 |
self.key_id = key_id |
| 377 |
self.principals = principals |
| 378 |
self.valid_after = valid_after |
| 379 |
self.valid_before = valid_before |
| 380 |
self.critical_options = critical_options |
| 381 |
self.extensions = extensions |
| 382 |
self.reserved = reserved |
| 383 |
self.signing_key = signing_key |
| 384 |
|
| 385 |
self.type_string: bytes | None = None |
| 386 |
|
| 387 |
@property |
| 388 |
def cert_type(self) -> t.Literal["user", "host", ""]: |
| 389 |
if self._cert_type == _USER_TYPE: |
| 390 |
return "user" |
| 391 |
if self._cert_type == _HOST_TYPE: |
| 392 |
return "host" |
| 393 |
return "" |
| 394 |
|
| 395 |
@cert_type.setter |
| 396 |
def cert_type(self, cert_type: t.Literal["user", "host"] | int) -> None: |
| 397 |
if cert_type in ("user", _USER_TYPE): |
| 398 |
self._cert_type = _USER_TYPE |
| 399 |
elif cert_type in ("host", _HOST_TYPE): |
| 400 |
self._cert_type = _HOST_TYPE |
| 401 |
else: |
| 402 |
raise ValueError(f"{cert_type} is not a valid certificate type") |
| 403 |
|
| 404 |
def signing_key_fingerprint(self) -> bytes: |
| 405 |
if self.signing_key is None: |
| 406 |
raise ValueError("signing_key not present") |
| 407 |
return fingerprint(self.signing_key) |
| 408 |
|
| 409 |
@abc.abstractmethod |
| 410 |
def public_key_fingerprint(self) -> bytes: |
| 411 |
pass |
| 412 |
|
| 413 |
@abc.abstractmethod |
| 414 |
def parse_public_numbers(self, parser: OpensshParser) -> None: |
| 415 |
pass |
| 416 |
|
| 417 |
|
| 418 |
class OpensshRSACertificateInfo(OpensshCertificateInfo): |
| 419 |
def __init__( |
| 420 |
self, |
| 421 |
*, |
| 422 |
e: int | None = None, |
| 423 |
n: int | None = None, |
| 424 |
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg], |
| 425 |
) -> None: |
| 426 |
super().__init__(**kwargs) |
| 427 |
self.type_string = _SSH_TYPE_STRINGS["rsa"] + _CERT_SUFFIX_V01 |
| 428 |
self.e = e |
| 429 |
self.n = n |
| 430 |
|
| 431 |
# See https://datatracker.ietf.org/doc/html/rfc4253#section-6.6 |
| 432 |
def public_key_fingerprint(self) -> bytes: |
| 433 |
if self.e is None or self.n is None: |
| 434 |
return b"" |
| 435 |
|
| 436 |
writer = _OpensshWriter() |
| 437 |
writer.string(_SSH_TYPE_STRINGS["rsa"]) |
| 438 |
writer.mpint(self.e) |
| 439 |
writer.mpint(self.n) |
| 440 |
|
| 441 |
return fingerprint(writer.bytes()) |
| 442 |
|
| 443 |
def parse_public_numbers(self, parser: OpensshParser) -> None: |
| 444 |
self.e = parser.mpint() |
| 445 |
self.n = parser.mpint() |
| 446 |
|
| 447 |
|
| 448 |
class OpensshDSACertificateInfo(OpensshCertificateInfo): |
| 449 |
def __init__( |
| 450 |
self, |
| 451 |
*, |
| 452 |
p: int | None = None, |
| 453 |
q: int | None = None, |
| 454 |
g: int | None = None, |
| 455 |
y: int | None = None, |
| 456 |
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg], |
| 457 |
) -> None: |
| 458 |
super().__init__(**kwargs) |
| 459 |
self.type_string = _SSH_TYPE_STRINGS["dsa"] + _CERT_SUFFIX_V01 |
| 460 |
self.p = p |
| 461 |
self.q = q |
| 462 |
self.g = g |
| 463 |
self.y = y |
| 464 |
|
| 465 |
# See https://datatracker.ietf.org/doc/html/rfc4253#section-6.6 |
| 466 |
def public_key_fingerprint(self) -> bytes: |
| 467 |
if self.p is None or self.q is None or self.g is None or self.y is None: |
| 468 |
return b"" |
| 469 |
|
| 470 |
writer = _OpensshWriter() |
| 471 |
writer.string(_SSH_TYPE_STRINGS["dsa"]) |
| 472 |
writer.mpint(self.p) |
| 473 |
writer.mpint(self.q) |
| 474 |
writer.mpint(self.g) |
| 475 |
writer.mpint(self.y) |
| 476 |
|
| 477 |
return fingerprint(writer.bytes()) |
| 478 |
|
| 479 |
def parse_public_numbers(self, parser: OpensshParser) -> None: |
| 480 |
self.p = parser.mpint() |
| 481 |
self.q = parser.mpint() |
| 482 |
self.g = parser.mpint() |
| 483 |
self.y = parser.mpint() |
| 484 |
|
| 485 |
|
| 486 |
class OpensshECDSACertificateInfo(OpensshCertificateInfo): |
| 487 |
def __init__( |
| 488 |
self, |
| 489 |
*, |
| 490 |
curve: bytes | None = None, |
| 491 |
public_key: bytes | None = None, |
| 492 |
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg], |
| 493 |
): |
| 494 |
super().__init__(**kwargs) |
| 495 |
self._curve: bytes | None = None |
| 496 |
if curve is not None: |
| 497 |
self.curve = curve |
| 498 |
|
| 499 |
self.public_key = public_key |
| 500 |
|
| 501 |
@property |
| 502 |
def curve(self) -> bytes | None: |
| 503 |
return self._curve |
| 504 |
|
| 505 |
@curve.setter |
| 506 |
def curve(self, curve: bytes) -> None: |
| 507 |
if curve in _ECDSA_CURVE_IDENTIFIERS.values(): |
| 508 |
self._curve = curve |
| 509 |
self.type_string = ( |
| 510 |
_SSH_TYPE_STRINGS[_ECDSA_CURVE_IDENTIFIERS_LOOKUP[curve]] |
| 511 |
+ _CERT_SUFFIX_V01 |
| 512 |
) |
| 513 |
else: |
| 514 |
raise ValueError( |
| 515 |
"Curve must be one of {(b','.join(_ECDSA_CURVE_IDENTIFIERS.values())).decode('UTF-8')}" |
| 516 |
) |
| 517 |
|
| 518 |
# See https://datatracker.ietf.org/doc/html/rfc4253#section-6.6 |
| 519 |
def public_key_fingerprint(self) -> bytes: |
| 520 |
if self.curve is None or self.public_key is None: |
| 521 |
return b"" |
| 522 |
|
| 523 |
writer = _OpensshWriter() |
| 524 |
writer.string(_SSH_TYPE_STRINGS[_ECDSA_CURVE_IDENTIFIERS_LOOKUP[self.curve]]) |
| 525 |
writer.string(self.curve) |
| 526 |
writer.string(self.public_key) |
| 527 |
|
| 528 |
return fingerprint(writer.bytes()) |
| 529 |
|
| 530 |
def parse_public_numbers(self, parser: OpensshParser) -> None: |
| 531 |
self.curve = parser.string() |
| 532 |
self.public_key = parser.string() |
| 533 |
|
| 534 |
|
| 535 |
class OpensshED25519CertificateInfo(OpensshCertificateInfo): |
| 536 |
def __init__( |
| 537 |
self, |
| 538 |
*, |
| 539 |
pk: bytes | None = None, |
| 540 |
**kwargs: t.Unpack[_OpensshCertificateInfoKwarg], |
| 541 |
) -> None: |
| 542 |
super().__init__(**kwargs) |
| 543 |
self.type_string = _SSH_TYPE_STRINGS["ed25519"] + _CERT_SUFFIX_V01 |
| 544 |
self.pk = pk |
| 545 |
|
| 546 |
def public_key_fingerprint(self) -> bytes: |
| 547 |
if self.pk is None: |
| 548 |
return b"" |
| 549 |
|
| 550 |
writer = _OpensshWriter() |
| 551 |
writer.string(_SSH_TYPE_STRINGS["ed25519"]) |
| 552 |
writer.string(self.pk) |
| 553 |
|
| 554 |
return fingerprint(writer.bytes()) |
| 555 |
|
| 556 |
def parse_public_numbers(self, parser: OpensshParser) -> None: |
| 557 |
self.pk = parser.string() |
| 558 |
|
| 559 |
|
| 560 |
_OpensshCertificate = t.TypeVar("_OpensshCertificate", bound="OpensshCertificate") |
| 561 |
|
| 562 |
|
| 563 |
# See https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD |
| 564 |
class OpensshCertificate: |
| 565 |
"""Encapsulates a formatted OpenSSH certificate including signature and signing key""" |
| 566 |
|
| 567 |
def __init__(self, *, cert_info: OpensshCertificateInfo, signature: bytes): |
| 568 |
self._cert_info = cert_info |
| 569 |
self.signature = signature |
| 570 |
|
| 571 |
@classmethod |
| 572 |
def load( |
| 573 |
cls: t.Type[_OpensshCertificate], path: str | os.PathLike # noqa: UP006 |
| 574 |
) -> _OpensshCertificate: |
| 575 |
if not os.path.exists(path): |
| 576 |
raise ValueError(f"{path} is not a valid path.") |
| 577 |
|
| 578 |
try: |
| 579 |
with open(path, "rb") as cert_file: |
| 580 |
data = cert_file.read() |
| 581 |
except (IOError, OSError) as e: |
| 582 |
raise ValueError(f"{path} cannot be opened for reading: {e}") from e |
| 583 |
|
| 584 |
try: |
| 585 |
format_identifier, b64_cert = data.split(b" ")[:2] |
| 586 |
cert = binascii.a2b_base64(b64_cert) |
| 587 |
except (binascii.Error, ValueError) as e: |
| 588 |
raise ValueError("Certificate not in OpenSSH format") from e |
| 589 |
|
| 590 |
for key_type, string in _SSH_TYPE_STRINGS.items(): |
| 591 |
if format_identifier == string + _CERT_SUFFIX_V01: |
| 592 |
pub_key_type = key_type |
| 593 |
break |
| 594 |
else: |
| 595 |
raise ValueError( |
| 596 |
f"Invalid certificate format identifier: {format_identifier!r}" |
| 597 |
) |
| 598 |
|
| 599 |
parser = OpensshParser(data=cert) |
| 600 |
|
| 601 |
if format_identifier != parser.string(): |
| 602 |
raise ValueError("Certificate formats do not match") |
| 603 |
|
| 604 |
try: |
| 605 |
cert_info = cls._parse_cert_info(pub_key_type, parser) |
| 606 |
signature = parser.string() |
| 607 |
except (TypeError, ValueError) as e: |
| 608 |
raise ValueError(f"Invalid certificate data: {e}") from e |
| 609 |
|
| 610 |
if parser.remaining_bytes(): |
| 611 |
raise ValueError( |
| 612 |
f"{parser.remaining_bytes()} bytes of additional data was not parsed while loading {path}" |
| 613 |
) |
| 614 |
|
| 615 |
return cls( |
| 616 |
cert_info=cert_info, |
| 617 |
signature=signature, |
| 618 |
) |
| 619 |
|
| 620 |
@property |
| 621 |
def type_string(self) -> str: |
| 622 |
return to_text(self._cert_info.type_string) |
| 623 |
|
| 624 |
@property |
| 625 |
def nonce(self) -> bytes: |
| 626 |
if self._cert_info.nonce is None: |
| 627 |
raise ValueError |
| 628 |
return self._cert_info.nonce |
| 629 |
|
| 630 |
@property |
| 631 |
def public_key(self) -> str: |
| 632 |
return to_text(self._cert_info.public_key_fingerprint()) |
| 633 |
|
| 634 |
@property |
| 635 |
def serial(self) -> int: |
| 636 |
if self._cert_info.serial is None: |
| 637 |
raise ValueError |
| 638 |
return self._cert_info.serial |
| 639 |
|
| 640 |
@property |
| 641 |
def type(self) -> t.Literal["user", "host"]: |
| 642 |
result = self._cert_info.cert_type |
| 643 |
if result == "": |
| 644 |
raise ValueError |
| 645 |
return result |
| 646 |
|
| 647 |
@property |
| 648 |
def key_id(self) -> str: |
| 649 |
return to_text(self._cert_info.key_id) |
| 650 |
|
| 651 |
@property |
| 652 |
def principals(self) -> list[str]: |
| 653 |
if self._cert_info.principals is None: |
| 654 |
raise ValueError |
| 655 |
return [to_text(p) for p in self._cert_info.principals] |
| 656 |
|
| 657 |
@property |
| 658 |
def valid_after(self) -> int: |
| 659 |
if self._cert_info.valid_after is None: |
| 660 |
raise ValueError |
| 661 |
return self._cert_info.valid_after |
| 662 |
|
| 663 |
@property |
| 664 |
def valid_before(self) -> int: |
| 665 |
if self._cert_info.valid_before is None: |
| 666 |
raise ValueError |
| 667 |
return self._cert_info.valid_before |
| 668 |
|
| 669 |
@property |
| 670 |
def critical_options(self) -> list[OpensshCertificateOption]: |
| 671 |
if self._cert_info.critical_options is None: |
| 672 |
raise ValueError |
| 673 |
return [ |
| 674 |
OpensshCertificateOption( |
| 675 |
option_type="critical", name=to_text(n), data=to_text(d) |
| 676 |
) |
| 677 |
for n, d in self._cert_info.critical_options |
| 678 |
] |
| 679 |
|
| 680 |
@property |
| 681 |
def extensions(self) -> list[OpensshCertificateOption]: |
| 682 |
if self._cert_info.extensions is None: |
| 683 |
raise ValueError |
| 684 |
return [ |
| 685 |
OpensshCertificateOption( |
| 686 |
option_type="extension", name=to_text(n), data=to_text(d) |
| 687 |
) |
| 688 |
for n, d in self._cert_info.extensions |
| 689 |
] |
| 690 |
|
| 691 |
@property |
| 692 |
def reserved(self) -> bytes: |
| 693 |
if self._cert_info.reserved is None: |
| 694 |
raise ValueError |
| 695 |
return self._cert_info.reserved |
| 696 |
|
| 697 |
@property |
| 698 |
def signing_key(self) -> str: |
| 699 |
return to_text(self._cert_info.signing_key_fingerprint()) |
| 700 |
|
| 701 |
@property |
| 702 |
def signature_type(self) -> str: |
| 703 |
signature_data = OpensshParser.signature_data(signature_string=self.signature) |
| 704 |
return to_text(signature_data["signature_type"]) |
| 705 |
|
| 706 |
@staticmethod |
| 707 |
def _parse_cert_info( |
| 708 |
pub_key_type: PubKeyType, parser: OpensshParser |
| 709 |
) -> OpensshCertificateInfo: |
| 710 |
cert_info = get_cert_info_object(pub_key_type) |
| 711 |
cert_info.nonce = parser.string() |
| 712 |
cert_info.parse_public_numbers(parser) |
| 713 |
cert_info.serial = parser.uint64() |
| 714 |
# mypy doesn't understand that the setter accepts other types than the getter: |
| 715 |
cert_info.cert_type = parser.uint32() # type: ignore |
| 716 |
cert_info.key_id = parser.string() |
| 717 |
cert_info.principals = parser.string_list() |
| 718 |
cert_info.valid_after = parser.uint64() |
| 719 |
cert_info.valid_before = parser.uint64() |
| 720 |
cert_info.critical_options = parser.option_list() |
| 721 |
cert_info.extensions = parser.option_list() |
| 722 |
cert_info.reserved = parser.string() |
| 723 |
cert_info.signing_key = parser.string() |
| 724 |
|
| 725 |
return cert_info |
| 726 |
|
| 727 |
def to_dict(self) -> dict[str, t.Any]: |
| 728 |
time_parameters = OpensshCertificateTimeParameters( |
| 729 |
valid_from=self.valid_after, valid_to=self.valid_before |
| 730 |
) |
| 731 |
return { |
| 732 |
"type_string": self.type_string, |
| 733 |
"nonce": self.nonce, |
| 734 |
"serial": self.serial, |
| 735 |
"cert_type": self.type, |
| 736 |
"identifier": self.key_id, |
| 737 |
"principals": self.principals, |
| 738 |
"valid_after": time_parameters.valid_from(date_format="human_readable"), |
| 739 |
"valid_before": time_parameters.valid_to(date_format="human_readable"), |
| 740 |
"critical_options": [ |
| 741 |
str(critical_option) for critical_option in self.critical_options |
| 742 |
], |
| 743 |
"extensions": [str(extension) for extension in self.extensions], |
| 744 |
"reserved": self.reserved, |
| 745 |
"public_key": self.public_key, |
| 746 |
"signing_key": self.signing_key, |
| 747 |
} |
| 748 |
|
| 749 |
|
| 750 |
def apply_directives(directives: t.Iterable[str]) -> list[OpensshCertificateOption]: |
| 751 |
if any(d not in _DIRECTIVES for d in directives): |
| 752 |
raise ValueError(f"directives must be one of {', '.join(_DIRECTIVES)}") |
| 753 |
|
| 754 |
directive_to_option = { |
| 755 |
"no-x11-forwarding": OpensshCertificateOption( |
| 756 |
option_type="extension", name="permit-x11-forwarding", data="" |
| 757 |
), |
| 758 |
"no-agent-forwarding": OpensshCertificateOption( |
| 759 |
option_type="extension", name="permit-agent-forwarding", data="" |
| 760 |
), |
| 761 |
"no-port-forwarding": OpensshCertificateOption( |
| 762 |
option_type="extension", name="permit-port-forwarding", data="" |
| 763 |
), |
| 764 |
"no-pty": OpensshCertificateOption( |
| 765 |
option_type="extension", name="permit-pty", data="" |
| 766 |
), |
| 767 |
"no-user-rc": OpensshCertificateOption( |
| 768 |
option_type="extension", name="permit-user-rc", data="" |
| 769 |
), |
| 770 |
} |
| 771 |
|
| 772 |
if "clear" in directives: |
| 773 |
return [] |
| 774 |
return list( |
| 775 |
set(default_options()) - set(directive_to_option[d] for d in directives) |
| 776 |
) |
| 777 |
|
| 778 |
|
| 779 |
def default_options() -> list[OpensshCertificateOption]: |
| 780 |
return [ |
| 781 |
OpensshCertificateOption(option_type="extension", name=name, data="") |
| 782 |
for name in _EXTENSIONS |
| 783 |
] |
| 784 |
|
| 785 |
|
| 786 |
def fingerprint(public_key: bytes) -> bytes: |
| 787 |
"""Generates a SHA256 hash and formats output to resemble ``ssh-keygen``""" |
| 788 |
h = sha256() |
| 789 |
h.update(public_key) |
| 790 |
return b"SHA256:" + b64encode(h.digest()).rstrip(b"=") |
| 791 |
|
| 792 |
|
| 793 |
def get_cert_info_object(key_type: PubKeyType) -> OpensshCertificateInfo: |
| 794 |
if key_type == "rsa": |
| 795 |
return OpensshRSACertificateInfo() |
| 796 |
if key_type == "dsa": |
| 797 |
return OpensshDSACertificateInfo() |
| 798 |
if key_type in ("ecdsa-nistp256", "ecdsa-nistp384", "ecdsa-nistp521"): |
| 799 |
return OpensshECDSACertificateInfo() |
| 800 |
if key_type == "ed25519": |
| 801 |
return OpensshED25519CertificateInfo() |
| 802 |
raise ValueError(f"{key_type} is not a valid key type") |
| 803 |
|
| 804 |
|
| 805 |
def get_option_type(name: str) -> t.Literal["critical", "extension"]: |
| 806 |
if name in _CRITICAL_OPTIONS: |
| 807 |
return "critical" |
| 808 |
if name in _EXTENSIONS: |
| 809 |
return "extension" |
| 810 |
raise ValueError( |
| 811 |
f"{name} is not a valid option. Custom options must start with 'critical:' or 'extension:' to indicate type" |
| 812 |
) |
| 813 |
|
| 814 |
|
| 815 |
def is_relative_time_string(time_string: str) -> bool: |
| 816 |
return time_string.startswith("+") or time_string.startswith("-") |
| 817 |
|
| 818 |
|
| 819 |
def parse_option_list( |
| 820 |
option_list: t.Iterable[str], |
| 821 |
) -> tuple[list[OpensshCertificateOption], list[OpensshCertificateOption]]: |
| 822 |
critical_options = [] |
| 823 |
directives = [] |
| 824 |
extensions = [] |
| 825 |
|
| 826 |
for option in option_list: |
| 827 |
if option.lower() in _DIRECTIVES: |
| 828 |
directives.append(option.lower()) |
| 829 |
else: |
| 830 |
option_object = OpensshCertificateOption.from_string(option) |
| 831 |
if option_object.type == "critical": |
| 832 |
critical_options.append(option_object) |
| 833 |
else: |
| 834 |
extensions.append(option_object) |
| 835 |
|
| 836 |
return critical_options, list(set(extensions + apply_directives(directives))) |
| 837 |
|
| 838 |
|
| 839 |
__all__ = ( |
| 840 |
"OpensshCertificate", |
| 841 |
"OpensshCertificateInfo", |
| 842 |
"OpensshCertificateOption", |
| 843 |
"OpensshCertificateTimeParameters", |
| 844 |
"OpensshDSACertificateInfo", |
| 845 |
"OpensshECDSACertificateInfo", |
| 846 |
"OpensshED25519CertificateInfo", |
| 847 |
"OpensshRSACertificateInfo", |
| 848 |
"apply_directives", |
| 849 |
"default_options", |
| 850 |
"fingerprint", |
| 851 |
"get_cert_info_object", |
| 852 |
"get_option_type", |
| 853 |
"is_relative_time_string", |
| 854 |
"parse_option_list", |
| 855 |
) |