| 1 |
# Copyright (c) 2020, Doug Stanley <[email protected]> |
| 2 |
# Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 7 |
# Do not use this from other collections or standalone plugins/modules! |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import os |
| 12 |
import re |
| 13 |
import typing as t |
| 14 |
from contextlib import contextmanager |
| 15 |
from struct import Struct |
| 16 |
|
| 17 |
# Protocol References |
| 18 |
# ------------------- |
| 19 |
# https://datatracker.ietf.org/doc/html/rfc4251 |
| 20 |
# https://datatracker.ietf.org/doc/html/rfc4253 |
| 21 |
# https://datatracker.ietf.org/doc/html/rfc5656 |
| 22 |
# https://datatracker.ietf.org/doc/html/rfc8032 |
| 23 |
# |
| 24 |
# Inspired by: |
| 25 |
# ------------ |
| 26 |
# https://github.com/pyca/cryptography/blob/main/src/cryptography/hazmat/primitives/serialization/ssh.py |
| 27 |
# https://github.com/paramiko/paramiko/blob/master/paramiko/message.py |
| 28 |
|
| 29 |
# 0 (False) or 1 (True) encoded as a single byte |
| 30 |
_BOOLEAN = Struct(b"?") |
| 31 |
# Unsigned 8-bit integer in network-byte-order |
| 32 |
_UBYTE = Struct(b"!B") |
| 33 |
_UBYTE_MAX = 0xFF |
| 34 |
# Unsigned 32-bit integer in network-byte-order |
| 35 |
_UINT32 = Struct(b"!I") |
| 36 |
# Unsigned 32-bit little endian integer |
| 37 |
_UINT32_LE = Struct(b"<I") |
| 38 |
_UINT32_MAX = 0xFFFFFFFF |
| 39 |
# Unsigned 64-bit integer in network-byte-order |
| 40 |
_UINT64 = Struct(b"!Q") |
| 41 |
_UINT64_MAX = 0xFFFFFFFFFFFFFFFF |
| 42 |
|
| 43 |
|
| 44 |
_T = t.TypeVar("_T") |
| 45 |
|
| 46 |
|
| 47 |
def any_in(sequence: t.Iterable[_T], *elements: _T) -> bool: |
| 48 |
return any(e in sequence for e in elements) |
| 49 |
|
| 50 |
|
| 51 |
def file_mode(path: str | os.PathLike) -> int: |
| 52 |
if not os.path.exists(path): |
| 53 |
return 0o000 |
| 54 |
return os.stat(path).st_mode & 0o777 |
| 55 |
|
| 56 |
|
| 57 |
def parse_openssh_version(version_string: str) -> str | None: |
| 58 |
"""Parse the version output of ssh -V and return version numbers that can be compared""" |
| 59 |
|
| 60 |
parsed_result = re.match( |
| 61 |
r"^.*openssh_(?P<version>[0-9.]+)(p?[0-9]+)[^0-9]*.*$", version_string.lower() |
| 62 |
) |
| 63 |
if parsed_result is not None: |
| 64 |
version = parsed_result.group("version").strip() |
| 65 |
else: |
| 66 |
version = None |
| 67 |
|
| 68 |
return version |
| 69 |
|
| 70 |
|
| 71 |
@contextmanager |
| 72 |
def secure_open(*, path: str | os.PathLike, mode: int) -> t.Iterator[int]: |
| 73 |
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode) |
| 74 |
try: |
| 75 |
yield fd |
| 76 |
finally: |
| 77 |
os.close(fd) |
| 78 |
|
| 79 |
|
| 80 |
def secure_write(*, path: str | os.PathLike, mode: int, content: bytes) -> None: |
| 81 |
with secure_open(path=path, mode=mode) as fd: |
| 82 |
os.write(fd, content) |
| 83 |
|
| 84 |
|
| 85 |
# See https://datatracker.ietf.org/doc/html/rfc4251#section-5 for SSH data types |
| 86 |
class OpensshParser: |
| 87 |
"""Parser for OpenSSH encoded objects""" |
| 88 |
|
| 89 |
BOOLEAN_OFFSET = 1 |
| 90 |
UINT32_OFFSET = 4 |
| 91 |
UINT64_OFFSET = 8 |
| 92 |
|
| 93 |
def __init__(self, *, data: bytes | bytearray) -> None: |
| 94 |
if not isinstance(data, (bytes, bytearray)): |
| 95 |
raise TypeError(f"Data must be bytes-like not {type(data)}") |
| 96 |
|
| 97 |
self._data = memoryview(data) |
| 98 |
self._pos = 0 |
| 99 |
|
| 100 |
def boolean(self) -> bool: |
| 101 |
next_pos = self._check_position(self.BOOLEAN_OFFSET) |
| 102 |
|
| 103 |
value: bool = _BOOLEAN.unpack(self._data[self._pos : next_pos])[0] |
| 104 |
self._pos = next_pos |
| 105 |
return value |
| 106 |
|
| 107 |
def uint32(self) -> int: |
| 108 |
next_pos = self._check_position(self.UINT32_OFFSET) |
| 109 |
|
| 110 |
value: int = _UINT32.unpack(self._data[self._pos : next_pos])[0] |
| 111 |
self._pos = next_pos |
| 112 |
return value |
| 113 |
|
| 114 |
def uint64(self) -> int: |
| 115 |
next_pos = self._check_position(self.UINT64_OFFSET) |
| 116 |
|
| 117 |
value: int = _UINT64.unpack(self._data[self._pos : next_pos])[0] |
| 118 |
self._pos = next_pos |
| 119 |
return value |
| 120 |
|
| 121 |
def string(self) -> bytes: |
| 122 |
length = self.uint32() |
| 123 |
|
| 124 |
next_pos = self._check_position(length) |
| 125 |
|
| 126 |
value = self._data[self._pos : next_pos] |
| 127 |
self._pos = next_pos |
| 128 |
# Cast to bytes is required as a memoryview slice is itself a memoryview |
| 129 |
return bytes(value) |
| 130 |
|
| 131 |
def mpint(self) -> int: |
| 132 |
return self._big_int(self.string(), "big", signed=True) |
| 133 |
|
| 134 |
def name_list(self) -> list[str]: |
| 135 |
raw_string = self.string() |
| 136 |
return raw_string.decode("ASCII").split(",") |
| 137 |
|
| 138 |
# Convenience function, but not an official data type from SSH |
| 139 |
def string_list(self) -> list[bytes]: |
| 140 |
result = [] |
| 141 |
raw_string = self.string() |
| 142 |
|
| 143 |
if raw_string: |
| 144 |
parser = OpensshParser(data=raw_string) |
| 145 |
while parser.remaining_bytes(): |
| 146 |
result.append(parser.string()) |
| 147 |
|
| 148 |
return result |
| 149 |
|
| 150 |
# Convenience function, but not an official data type from SSH |
| 151 |
def option_list(self) -> list[tuple[bytes, bytes]]: |
| 152 |
result = [] |
| 153 |
raw_string = self.string() |
| 154 |
|
| 155 |
if raw_string: |
| 156 |
parser = OpensshParser(data=raw_string) |
| 157 |
|
| 158 |
while parser.remaining_bytes(): |
| 159 |
name = parser.string() |
| 160 |
data = parser.string() |
| 161 |
if data: |
| 162 |
# data is doubly-encoded |
| 163 |
data = OpensshParser(data=data).string() |
| 164 |
result.append((name, data)) |
| 165 |
|
| 166 |
return result |
| 167 |
|
| 168 |
def seek(self, offset: int) -> int: |
| 169 |
self._pos = self._check_position(offset) |
| 170 |
|
| 171 |
return self._pos |
| 172 |
|
| 173 |
def remaining_bytes(self) -> int: |
| 174 |
return len(self._data) - self._pos |
| 175 |
|
| 176 |
def _check_position(self, offset: int) -> int: |
| 177 |
if self._pos + offset > len(self._data): |
| 178 |
raise ValueError(f"Insufficient data remaining at position: {self._pos}") |
| 179 |
if self._pos + offset < 0: |
| 180 |
raise ValueError("Position cannot be less than zero.") |
| 181 |
return self._pos + offset |
| 182 |
|
| 183 |
@classmethod |
| 184 |
def signature_data(cls, *, signature_string: bytes) -> dict[str, bytes | int]: |
| 185 |
signature_data: dict[str, bytes | int] = {} |
| 186 |
|
| 187 |
parser = cls(data=signature_string) |
| 188 |
signature_type = parser.string() |
| 189 |
signature_blob = parser.string() |
| 190 |
|
| 191 |
blob_parser = cls(data=signature_blob) |
| 192 |
if signature_type in (b"ssh-rsa", b"rsa-sha2-256", b"rsa-sha2-512"): |
| 193 |
# https://datatracker.ietf.org/doc/html/rfc4253#section-6.6 |
| 194 |
# https://datatracker.ietf.org/doc/html/rfc8332#section-3 |
| 195 |
signature_data["s"] = cls._big_int(signature_blob, "big") |
| 196 |
elif signature_type == b"ssh-dss": |
| 197 |
# https://datatracker.ietf.org/doc/html/rfc4253#section-6.6 |
| 198 |
signature_data["r"] = cls._big_int(signature_blob[:20], "big") |
| 199 |
signature_data["s"] = cls._big_int(signature_blob[20:], "big") |
| 200 |
elif signature_type in ( |
| 201 |
b"ecdsa-sha2-nistp256", |
| 202 |
b"ecdsa-sha2-nistp384", |
| 203 |
b"ecdsa-sha2-nistp521", |
| 204 |
): |
| 205 |
# https://datatracker.ietf.org/doc/html/rfc5656#section-3.1.2 |
| 206 |
signature_data["r"] = blob_parser.mpint() |
| 207 |
signature_data["s"] = blob_parser.mpint() |
| 208 |
elif signature_type == b"ssh-ed25519": |
| 209 |
# https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.2 |
| 210 |
signature_data["R"] = cls._big_int(signature_blob[:32], "little") |
| 211 |
signature_data["S"] = cls._big_int(signature_blob[32:], "little") |
| 212 |
else: |
| 213 |
raise ValueError(f"{signature_type!r} is not a valid signature type") |
| 214 |
|
| 215 |
signature_data["signature_type"] = signature_type |
| 216 |
|
| 217 |
return signature_data |
| 218 |
|
| 219 |
@classmethod |
| 220 |
def _big_int( |
| 221 |
cls, |
| 222 |
raw_string: bytes, |
| 223 |
byte_order: t.Literal["big", "little"], |
| 224 |
signed: bool = False, |
| 225 |
) -> int: |
| 226 |
if byte_order not in ("big", "little"): |
| 227 |
raise ValueError( |
| 228 |
f"Byte_order must be one of (big, little) not {byte_order}" |
| 229 |
) |
| 230 |
|
| 231 |
return int.from_bytes(raw_string, byte_order, signed=signed) |
| 232 |
|
| 233 |
|
| 234 |
class _OpensshWriter: |
| 235 |
"""Writes SSH encoded values to a bytes-like buffer |
| 236 |
|
| 237 |
.. warning:: |
| 238 |
This class is a private API and must not be exported outside of the openssh module_utils. |
| 239 |
It is not to be used to construct Openssh objects, but rather as a utility to assist |
| 240 |
in validating parsed material. |
| 241 |
""" |
| 242 |
|
| 243 |
def __init__(self, *, buffer: bytearray | None = None): |
| 244 |
if buffer is not None: |
| 245 |
if not isinstance(buffer, bytearray): |
| 246 |
raise TypeError(f"Buffer must be a bytearray, not {type(buffer)}") |
| 247 |
else: |
| 248 |
buffer = bytearray() |
| 249 |
|
| 250 |
self._buff: bytearray = buffer |
| 251 |
|
| 252 |
def boolean(self, value: bool) -> t.Self: |
| 253 |
if not isinstance(value, bool): |
| 254 |
raise TypeError(f"Value must be of type bool not {type(value)}") |
| 255 |
|
| 256 |
self._buff.extend(_BOOLEAN.pack(value)) |
| 257 |
|
| 258 |
return self |
| 259 |
|
| 260 |
def uint32(self, value: int) -> t.Self: |
| 261 |
if not isinstance(value, int): |
| 262 |
raise TypeError(f"Value must be of type int not {type(value)}") |
| 263 |
if value < 0 or value > _UINT32_MAX: |
| 264 |
raise ValueError( |
| 265 |
f"Value must be a positive integer less than {_UINT32_MAX}" |
| 266 |
) |
| 267 |
|
| 268 |
self._buff.extend(_UINT32.pack(value)) |
| 269 |
|
| 270 |
return self |
| 271 |
|
| 272 |
def uint64(self, value: int) -> t.Self: |
| 273 |
if not isinstance(value, int): |
| 274 |
raise TypeError(f"Value must be of type int not {type(value)}") |
| 275 |
if value < 0 or value > _UINT64_MAX: |
| 276 |
raise ValueError( |
| 277 |
f"Value must be a positive integer less than {_UINT64_MAX}" |
| 278 |
) |
| 279 |
|
| 280 |
self._buff.extend(_UINT64.pack(value)) |
| 281 |
|
| 282 |
return self |
| 283 |
|
| 284 |
def string(self, value: bytes | bytearray) -> t.Self: |
| 285 |
if not isinstance(value, (bytes, bytearray)): |
| 286 |
raise TypeError(f"Value must be bytes-like not {type(value)}") |
| 287 |
self.uint32(len(value)) |
| 288 |
self._buff.extend(value) |
| 289 |
|
| 290 |
return self |
| 291 |
|
| 292 |
def mpint(self, value: int) -> t.Self: |
| 293 |
if not isinstance(value, int): |
| 294 |
raise TypeError(f"Value must be of type int not {type(value)}") |
| 295 |
|
| 296 |
self.string(self._int_to_mpint(value)) |
| 297 |
|
| 298 |
return self |
| 299 |
|
| 300 |
def name_list(self, value: list[str]) -> t.Self: |
| 301 |
if not isinstance(value, list): |
| 302 |
raise TypeError(f"Value must be a list of byte strings not {type(value)}") |
| 303 |
|
| 304 |
try: |
| 305 |
self.string(",".join(value).encode("ASCII")) |
| 306 |
except UnicodeEncodeError as e: |
| 307 |
raise ValueError( |
| 308 |
f"Name-list's must consist of US-ASCII characters: {e}" |
| 309 |
) from e |
| 310 |
|
| 311 |
return self |
| 312 |
|
| 313 |
def string_list(self, value: list[bytes]) -> t.Self: |
| 314 |
if not isinstance(value, list): |
| 315 |
raise TypeError(f"Value must be a list of byte string not {type(value)}") |
| 316 |
|
| 317 |
writer = _OpensshWriter() |
| 318 |
for s in value: |
| 319 |
writer.string(s) |
| 320 |
|
| 321 |
self.string(writer.bytes()) |
| 322 |
|
| 323 |
return self |
| 324 |
|
| 325 |
def option_list(self, value: list[tuple[bytes, bytes]]) -> t.Self: |
| 326 |
if not isinstance(value, list) or (value and not isinstance(value[0], tuple)): |
| 327 |
raise TypeError("Value must be a list of tuples") |
| 328 |
|
| 329 |
writer = _OpensshWriter() |
| 330 |
for name, data in value: |
| 331 |
writer.string(name) |
| 332 |
# SSH option data is encoded twice though this behavior is not documented |
| 333 |
writer.string(_OpensshWriter().string(data).bytes() if data else b"") |
| 334 |
|
| 335 |
self.string(writer.bytes()) |
| 336 |
|
| 337 |
return self |
| 338 |
|
| 339 |
@staticmethod |
| 340 |
def _int_to_mpint(num: int) -> bytes: |
| 341 |
byte_length = (num.bit_length() + 7) // 8 |
| 342 |
try: |
| 343 |
return num.to_bytes(byte_length, "big", signed=True) |
| 344 |
# Handles values which require \x00 or \xFF to pad sign-bit |
| 345 |
except OverflowError: |
| 346 |
return num.to_bytes(byte_length + 1, "big", signed=True) |
| 347 |
|
| 348 |
def bytes(self) -> bytes: |
| 349 |
return bytes(self._buff) |
| 350 |
|
| 351 |
|
| 352 |
__all__ = ( |
| 353 |
"OpensshParser", |
| 354 |
"any_in", |
| 355 |
"file_mode", |
| 356 |
"parse_openssh_version", |
| 357 |
"secure_open", |
| 358 |
"secure_write", |
| 359 |
) |