| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright: (c) 2022, Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
"""Signature verification helpers.""" |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from ansible.errors import AnsibleError |
| 8 |
from ansible.galaxy.user_agent import user_agent |
| 9 |
from ansible.module_utils.urls import open_url |
| 10 |
|
| 11 |
import contextlib |
| 12 |
import inspect |
| 13 |
import os |
| 14 |
import subprocess |
| 15 |
import typing as t |
| 16 |
|
| 17 |
from dataclasses import dataclass, fields as dc_fields |
| 18 |
from urllib.error import HTTPError, URLError |
| 19 |
|
| 20 |
if t.TYPE_CHECKING: |
| 21 |
from ansible.utils.display import Display |
| 22 |
|
| 23 |
|
| 24 |
def get_signature_from_source( |
| 25 |
source: str, |
| 26 |
display: Display | None = None, |
| 27 |
) -> str: |
| 28 |
if display is not None: |
| 29 |
display.vvvv(f"Using signature at {source}") |
| 30 |
try: |
| 31 |
with open_url( |
| 32 |
source, |
| 33 |
http_agent=user_agent(), |
| 34 |
validate_certs=True, |
| 35 |
follow_redirects='safe' |
| 36 |
) as resp: |
| 37 |
signature = resp.read() |
| 38 |
except (HTTPError, URLError) as e: |
| 39 |
raise AnsibleError( |
| 40 |
f"Failed to get signature for collection verification from '{source}': {e}" |
| 41 |
) from e |
| 42 |
|
| 43 |
return signature |
| 44 |
|
| 45 |
|
| 46 |
def run_gpg_verify( |
| 47 |
manifest_file: str, |
| 48 |
signature: str, |
| 49 |
keyring: str, |
| 50 |
display: Display, |
| 51 |
) -> tuple[str, int]: |
| 52 |
status_fd_read, status_fd_write = os.pipe() |
| 53 |
|
| 54 |
# running the gpg command will create the keyring if it does not exist |
| 55 |
remove_keybox = not os.path.exists(keyring) |
| 56 |
|
| 57 |
cmd = [ |
| 58 |
'gpg', |
| 59 |
f'--status-fd={status_fd_write}', |
| 60 |
'--verify', |
| 61 |
'--batch', |
| 62 |
'--no-tty', |
| 63 |
'--no-default-keyring', |
| 64 |
f'--keyring={keyring}', |
| 65 |
'-', |
| 66 |
manifest_file, |
| 67 |
] |
| 68 |
cmd_str = ' '.join(cmd) |
| 69 |
display.vvvv(f"Running command '{cmd}'") |
| 70 |
|
| 71 |
try: |
| 72 |
p = subprocess.Popen( |
| 73 |
cmd, |
| 74 |
stdin=subprocess.PIPE, |
| 75 |
stdout=subprocess.PIPE, |
| 76 |
stderr=subprocess.PIPE, |
| 77 |
pass_fds=(status_fd_write,), |
| 78 |
encoding='utf8', |
| 79 |
) |
| 80 |
except (FileNotFoundError, subprocess.SubprocessError) as err: |
| 81 |
raise AnsibleError( |
| 82 |
f"Failed during GnuPG verification with command '{cmd_str}': {err}" |
| 83 |
) from err |
| 84 |
else: |
| 85 |
stdout, stderr = p.communicate(input=signature) |
| 86 |
finally: |
| 87 |
os.close(status_fd_write) |
| 88 |
|
| 89 |
if remove_keybox: |
| 90 |
with contextlib.suppress(OSError): |
| 91 |
os.remove(keyring) |
| 92 |
|
| 93 |
with os.fdopen(status_fd_read) as f: |
| 94 |
stdout = f.read() |
| 95 |
display.vvvv( |
| 96 |
f"stdout: \n{stdout}\nstderr: \n{stderr}\n(exit code {p.returncode})" |
| 97 |
) |
| 98 |
return stdout, p.returncode |
| 99 |
|
| 100 |
|
| 101 |
def parse_gpg_errors(status_out: str) -> t.Iterator[GpgBaseError]: |
| 102 |
for line in status_out.splitlines(): |
| 103 |
if not line: |
| 104 |
continue |
| 105 |
try: |
| 106 |
_dummy, status, remainder = line.split(maxsplit=2) |
| 107 |
except ValueError: |
| 108 |
_dummy, status = line.split(maxsplit=1) |
| 109 |
remainder = None |
| 110 |
|
| 111 |
try: |
| 112 |
cls = GPG_ERROR_MAP[status] |
| 113 |
except KeyError: |
| 114 |
continue |
| 115 |
|
| 116 |
fields = [status] |
| 117 |
if remainder: |
| 118 |
fields.extend( |
| 119 |
remainder.split( |
| 120 |
None, |
| 121 |
len(dc_fields(cls)) - 2 |
| 122 |
) |
| 123 |
) |
| 124 |
|
| 125 |
yield cls(*fields) |
| 126 |
|
| 127 |
|
| 128 |
@dataclass(frozen=True, slots=True) |
| 129 |
class GpgBaseError(Exception): |
| 130 |
status: str |
| 131 |
|
| 132 |
@classmethod |
| 133 |
def get_gpg_error_description(cls) -> str: |
| 134 |
"""Return the current class description.""" |
| 135 |
if cls.__doc__ is None: |
| 136 |
raise RuntimeError( |
| 137 |
f'{cls!r} was expected to have a docstring but it does not.', |
| 138 |
) |
| 139 |
|
| 140 |
return ' '.join(cls.__doc__.split()) |
| 141 |
|
| 142 |
def __post_init__(self) -> None: |
| 143 |
for field_name, field_type in inspect.get_annotations(type(self), eval_str=True).items(): |
| 144 |
super(GpgBaseError, self).__setattr__(field_name, field_type(getattr(self, field_name))) |
| 145 |
|
| 146 |
|
| 147 |
@dataclass(frozen=True, slots=True) |
| 148 |
class GpgExpSig(GpgBaseError): |
| 149 |
"""The signature with the keyid is good, but the signature is expired.""" |
| 150 |
keyid: str |
| 151 |
username: str |
| 152 |
|
| 153 |
|
| 154 |
@dataclass(frozen=True, slots=True) |
| 155 |
class GpgExpKeySig(GpgBaseError): |
| 156 |
"""The signature with the keyid is good, but the signature was made by an expired key.""" |
| 157 |
keyid: str |
| 158 |
username: str |
| 159 |
|
| 160 |
|
| 161 |
@dataclass(frozen=True, slots=True) |
| 162 |
class GpgRevKeySig(GpgBaseError): |
| 163 |
"""The signature with the keyid is good, but the signature was made by a revoked key.""" |
| 164 |
keyid: str |
| 165 |
username: str |
| 166 |
|
| 167 |
|
| 168 |
@dataclass(frozen=True, slots=True) |
| 169 |
class GpgBadSig(GpgBaseError): |
| 170 |
"""The signature with the keyid has not been verified okay.""" |
| 171 |
keyid: str |
| 172 |
username: str |
| 173 |
|
| 174 |
|
| 175 |
@dataclass(frozen=True, slots=True) |
| 176 |
class GpgErrSig(GpgBaseError): |
| 177 |
""""It was not possible to check the signature. This may be caused by |
| 178 |
a missing public key or an unsupported algorithm. A RC of 4 |
| 179 |
indicates unknown algorithm, a 9 indicates a missing public |
| 180 |
key. |
| 181 |
""" |
| 182 |
keyid: str |
| 183 |
pkalgo: int |
| 184 |
hashalgo: int |
| 185 |
sig_class: str |
| 186 |
time: int |
| 187 |
rc: int |
| 188 |
fpr: str |
| 189 |
|
| 190 |
|
| 191 |
@dataclass(frozen=True, slots=True) |
| 192 |
class GpgNoPubkey(GpgBaseError): |
| 193 |
"""The public key is not available.""" |
| 194 |
keyid: str |
| 195 |
|
| 196 |
|
| 197 |
@dataclass(frozen=True, slots=True) |
| 198 |
class GpgMissingPassPhrase(GpgBaseError): |
| 199 |
"""No passphrase was supplied.""" |
| 200 |
|
| 201 |
|
| 202 |
@dataclass(frozen=True, slots=True) |
| 203 |
class GpgBadPassphrase(GpgBaseError): |
| 204 |
"""The supplied passphrase was wrong or not given.""" |
| 205 |
keyid: str |
| 206 |
|
| 207 |
|
| 208 |
@dataclass(frozen=True, slots=True) |
| 209 |
class GpgNoData(GpgBaseError): |
| 210 |
"""No data has been found. Codes for WHAT are: |
| 211 |
- 1 :: No armored data. |
| 212 |
- 2 :: Expected a packet but did not find one. |
| 213 |
- 3 :: Invalid packet found, this may indicate a non OpenPGP |
| 214 |
message. |
| 215 |
- 4 :: Signature expected but not found. |
| 216 |
""" |
| 217 |
what: str |
| 218 |
|
| 219 |
|
| 220 |
@dataclass(frozen=True, slots=True) |
| 221 |
class GpgUnexpected(GpgBaseError): |
| 222 |
"""No data has been found. Codes for WHAT are: |
| 223 |
- 1 :: No armored data. |
| 224 |
- 2 :: Expected a packet but did not find one. |
| 225 |
- 3 :: Invalid packet found, this may indicate a non OpenPGP |
| 226 |
message. |
| 227 |
- 4 :: Signature expected but not found. |
| 228 |
""" |
| 229 |
what: str |
| 230 |
|
| 231 |
|
| 232 |
@dataclass(frozen=True, slots=True) |
| 233 |
class GpgError(GpgBaseError): |
| 234 |
"""This is a generic error status message, it might be followed by error location specific data.""" |
| 235 |
location: str |
| 236 |
code: int |
| 237 |
more: str = "" |
| 238 |
|
| 239 |
|
| 240 |
@dataclass(frozen=True, slots=True) |
| 241 |
class GpgFailure(GpgBaseError): |
| 242 |
"""This is the counterpart to SUCCESS and used to indicate a program failure.""" |
| 243 |
location: str |
| 244 |
code: int |
| 245 |
|
| 246 |
|
| 247 |
@dataclass(frozen=True, slots=True) |
| 248 |
class GpgBadArmor(GpgBaseError): |
| 249 |
"""The ASCII armor is corrupted.""" |
| 250 |
|
| 251 |
|
| 252 |
@dataclass(frozen=True, slots=True) |
| 253 |
class GpgKeyExpired(GpgBaseError): |
| 254 |
"""The key has expired.""" |
| 255 |
timestamp: int |
| 256 |
|
| 257 |
|
| 258 |
@dataclass(frozen=True, slots=True) |
| 259 |
class GpgKeyRevoked(GpgBaseError): |
| 260 |
"""The used key has been revoked by its owner.""" |
| 261 |
|
| 262 |
|
| 263 |
@dataclass(frozen=True, slots=True) |
| 264 |
class GpgNoSecKey(GpgBaseError): |
| 265 |
"""The secret key is not available.""" |
| 266 |
keyid: str |
| 267 |
|
| 268 |
|
| 269 |
GPG_ERROR_MAP = { |
| 270 |
'EXPSIG': GpgExpSig, |
| 271 |
'EXPKEYSIG': GpgExpKeySig, |
| 272 |
'REVKEYSIG': GpgRevKeySig, |
| 273 |
'BADSIG': GpgBadSig, |
| 274 |
'ERRSIG': GpgErrSig, |
| 275 |
'NO_PUBKEY': GpgNoPubkey, |
| 276 |
'MISSING_PASSPHRASE': GpgMissingPassPhrase, |
| 277 |
'BAD_PASSPHRASE': GpgBadPassphrase, |
| 278 |
'NODATA': GpgNoData, |
| 279 |
'UNEXPECTED': GpgUnexpected, |
| 280 |
'ERROR': GpgError, |
| 281 |
'FAILURE': GpgFailure, |
| 282 |
'BADARMOR': GpgBadArmor, |
| 283 |
'KEYEXPIRED': GpgKeyExpired, |
| 284 |
'KEYREVOKED': GpgKeyRevoked, |
| 285 |
'NO_SECKEY': GpgNoSecKey, |
| 286 |
} |