1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
|
# (c) 2018 Mantas Mikulėnas <grawity@gmail.com>
# (c) 2024 E. Castedo Ellerman <castedo@castedo.com>
# Released under the MIT License (https://spdx.org/licenses/MIT)
from __future__ import annotations
import binascii
import hashlib
import io
from collections.abc import ByteString, Iterable
from typing import BinaryIO, ClassVar
from .binary_io import SshReader, SshWriter
from .ssh_public_key import PublicKey
from .unexceptional import cast_or_raise, unexceptional
# SSHSIG armored, blob, and signed data formats are documented in a file named
# `PROTOCOL.sshsig` which is archived from https://github.com/openssh/openssh-portable at
# https://archive.softwareheritage.org/swh:1:cnt:78457ddfc653519c056e36c79525712dafba4e6e
class InvalidSignature(Exception):
pass
def ssh_enarmor_sshsig(raw: bytes) -> str:
lines = ["-----BEGIN SSH SIGNATURE-----"]
buf = binascii.b2a_base64(raw, newline=False).decode()
for i in range(0, len(buf), 76):
lines.append(buf[i : i + 76])
lines += ["-----END SSH SIGNATURE-----", ""]
return "\n".join(lines)
def ssh_dearmor_sshsig(buf: str | bytes) -> bytes:
if isinstance(buf, bytes):
buf = buf.decode('ascii')
acc = ""
match = False
# TODO: stricter format check
for line in buf.splitlines():
if line == "-----BEGIN SSH SIGNATURE-----":
match = True
elif line == "-----END SSH SIGNATURE-----":
break
elif line and match:
acc += line
return binascii.a2b_base64(acc)
class SshsigWrapper:
"""The inner 'to-be-signed' data."""
def __init__(
self,
*,
namespace: bytes = b"",
reserved: bytes = b"",
hash_algo: bytes,
hash: bytes,
) -> None:
self.namespace = namespace
self.reserved = reserved
self.hash_algo = hash_algo
self.hash = hash
@staticmethod
def from_bytes(buf: ByteString) -> SshsigWrapper:
pkt = SshReader.from_bytes(buf)
magic = pkt.read(6)
if magic != b"SSHSIG":
raise ValueError("magic preamble not found")
return SshsigWrapper(
namespace=pkt.read_string(),
reserved=pkt.read_string(),
hash_algo=pkt.read_string(),
hash=pkt.read_string(),
)
def to_bytes(self) -> bytes:
pkt = SshWriter(io.BytesIO())
pkt.write(b"SSHSIG")
pkt.write_string(self.namespace)
pkt.write_string(self.reserved)
pkt.write_string(self.hash_algo)
pkt.write_string(self.hash)
return pkt.output_fh.getvalue()
def __bytes__(self) -> bytes:
return self.to_bytes()
class SshsigSignature:
VERSION: ClassVar[int] = 0x1
public_key: bytes
namespace: bytes
hash_algo: bytes
signature: bytes
def __init__(self, buf: ByteString):
pkt = SshReader.from_bytes(buf)
if pkt.read(6) != b"SSHSIG":
raise ValueError("SSH Signature magic preamble not found.")
version = pkt.read_uint32()
if version != SshsigSignature.VERSION:
raise NotImplementedError(f"SSH Signature format version {version}.")
self.public_key = pkt.read_string()
self.namespace = pkt.read_string()
pkt.read_string() # reserved field to be ignored
self.hash_algo = pkt.read_string()
self.signature = pkt.read_string()
def __bytes__(self) -> bytes:
pkt = SshWriter(io.BytesIO())
pkt.write(b"SSHSIG")
pkt.write_uint32(SshsigSignature.VERSION)
pkt.write_string(self.public_key)
pkt.write_string(self.namespace)
pkt.write_string(b"") # reserved field to be ignored
pkt.write_string(self.hash_algo)
pkt.write_string(self.signature)
return pkt.output_fh.getvalue()
@staticmethod
def from_armored(buf: str | bytes) -> SshsigSignature:
return SshsigSignature(ssh_dearmor_sshsig(buf))
def to_armored(self) -> str:
return ssh_enarmor_sshsig(bytes(self))
def hash_file(msg_file: BinaryIO, hash_algo_name: str | bytes) -> bytes:
return cast_or_raise(do_hash_file(msg_file, hash_algo_name))
def do_hash_file(
msg_file: BinaryIO, hash_algo_name: str | bytes
) -> bytes | NotImplementedError:
if isinstance(hash_algo_name, bytes):
hash_algo_name = hash_algo_name.decode("ascii")
hash_algo = hash_algo_name.lower()
if hash_algo not in hashlib.algorithms_guaranteed:
msg = "Signature hash algo '{}' not supported across platforms by Python."
return unexceptional(NotImplementedError(msg.format(hash_algo)))
hobj = hashlib.new(hash_algo)
while data := msg_file.read(8192):
hobj.update(data)
return hobj.digest()
def do_sshsig_verify(
sshsig_outer: SshsigSignature,
msg_file: BinaryIO,
namespace: str,
) -> PublicKey | InvalidSignature | NotImplementedError:
"""Verify the SSHSIG signature is for the input message and namespace.
The SSHSIG signature is verified to be for the namespace and the embedded
public key signature is valid for the provided input message.
Returns:
If no error, the cryptographic PublicKey embedded inside the SSHSIG signature.
ValueError: If the input string is not a valid format or encoding.
NotImplementedError: If a signature encoding feature is not supported.
"""
# The intention of this implementation is to reproduce (approximately)
# the behaviour of the sshsig_verify_fd function of the ssh-keygen C file:
# sshsig.c
# https://archive.softwareheritage.org/
# swh:1:cnt:470b286a3a982875a48a5262b7057c4710b17fed
_namespace = namespace.encode("ascii")
if _namespace != sshsig_outer.namespace:
errmsg = "Namespace of signature {} != {}"
return unexceptional(
InvalidSignature(errmsg.format(sshsig_outer.namespace, _namespace))
)
msg_hash = do_hash_file(msg_file, sshsig_outer.hash_algo)
if isinstance(msg_hash, NotImplementedError):
return msg_hash
toverify = SshsigWrapper(
namespace=_namespace, hash_algo=sshsig_outer.hash_algo, hash=msg_hash
).to_bytes()
pub_key = PublicKey.do_from_ssh_encoding(sshsig_outer.public_key)
if isinstance(pub_key, NotImplementedError):
return pub_key
if isinstance(pub_key, ValueError):
return unexceptional(InvalidSignature(pub_key))
if err := pub_key.do_verify(sshsig_outer.signature, toverify):
return unexceptional(InvalidSignature(err))
return pub_key
def check_signature(
msg_in: str | bytes | BinaryIO,
armored_signature: str | bytes,
namespace: str = "git",
) -> PublicKey:
"""Check that an ssh-keygen signature is a digital signature of the input message.
This function implements functionality provided by:
```
ssh-keygen -Y check-novalidate -n namespace -s armored_signature_file < msg_in
```
Returns:
The cryptographic PublicKey embedded inside the SSHSIG signature.
Raises:
InvalidSignature: If signature is not valid for the input message.
NotImplementedError: If a signature encoding feature is not supported.
"""
return cast_or_raise(do_check_signature(msg_in, armored_signature, namespace))
def do_check_signature(
msg_in: str | bytes | BinaryIO,
armored_signature: str | bytes,
namespace: str = "git",
) -> PublicKey | InvalidSignature | NotImplementedError:
"""Implementation of check_signature returning unexceptional Exception objects."""
if isinstance(msg_in, str):
msg_in = msg_in.encode()
msg_file = io.BytesIO(msg_in) if isinstance(msg_in, bytes) else msg_in
try:
sshsig_outer = SshsigSignature.from_armored(armored_signature)
except ValueError as ex:
return unexceptional(InvalidSignature(ex))
return do_sshsig_verify(sshsig_outer, msg_file, namespace)
def verify(
msg_in: str | bytes | BinaryIO,
armored_signature: str | bytes,
allowed_signers: Iterable[PublicKey],
namespace: str = "git",
) -> PublicKey:
r"""Verify a signature generated by ssh-keygen, the OpenSSH authentication key utility.
This function implements a _SUBSET_ of functionality provided by:
```sh
ssh-keygen -Y verify \
-f allowed_signers_file \
-I '*' \
-n namespace \
-s armored_signature_file \
< msg_in
```
when the allowed_signers_file is in a sub-format with only lines starting:
`* namespaces="X" ...`
where X equals the namespace argument.
Returns:
The cryptographic PublicKey embedded inside the SSHSIG signature.
Raises:
InvalidSignature: If signature is not valid for the input message.
NotImplementedError: If a signature encoding feature is not supported.
"""
return cast_or_raise(
do_verify(msg_in, armored_signature, allowed_signers, namespace)
)
def do_verify(
msg_in: str | bytes | BinaryIO,
armored_signature: str | bytes,
allowed_signers: Iterable[PublicKey],
namespace: str = "git",
) -> PublicKey | InvalidSignature | NotImplementedError:
"""Implementation of verify returning unexceptional Exception objects."""
ret = do_check_signature(msg_in, armored_signature, namespace)
if not isinstance(ret, PublicKey):
return ret
if all(key != ret for key in allowed_signers):
msg = "Signature public key not of allowed signer."
return unexceptional(InvalidSignature(msg))
return ret
|