debkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,266 @@
1
+ """Compression codecs for Debian index files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import bz2
6
+ import gzip
7
+ import lzma
8
+ import re
9
+ import subprocess
10
+ import threading
11
+ import zlib
12
+ from collections.abc import Buffer, Callable
13
+ from functools import partial
14
+ from typing import IO, TYPE_CHECKING, NamedTuple, Protocol
15
+
16
+ from txstore import StorageException
17
+
18
+ from debkit._env import child_env
19
+
20
+ if TYPE_CHECKING:
21
+ from txstore import Storage
22
+
23
+
24
+ class SizeLimitError(ValueError):
25
+ """Decoded data exceeds the size limit the caller set."""
26
+
27
+
28
+ class CorruptStreamError(ValueError):
29
+ """Encoded data is truncated or does not decode."""
30
+
31
+
32
+ # the read size of `read_capped`; the cap, not the chunk, bounds what is buffered
33
+ _READ_CHUNK = 1 << 20
34
+
35
+
36
+ def read_capped(storage: Storage, path: str, limit: int) -> bytes:
37
+ """Read a stored object, refusing it as soon as it passes `limit` bytes.
38
+
39
+ Unlike `Storage.get`, which buffers the whole body, at most `limit + 1` bytes are read,
40
+ so an oversized object is refused before it is verified or buffered in full
41
+ -> [VALIDATION.md](VALIDATION.md#object-sizes).
42
+
43
+ Args:
44
+ storage: The storage holding the object.
45
+ path: The object path.
46
+ limit: The largest size accepted, in bytes.
47
+
48
+ Raises:
49
+ SizeLimitError: The object is larger than `limit`.
50
+ StorageException: The object cannot be opened or read.
51
+
52
+ Returns:
53
+ The object content.
54
+ """
55
+ out = bytearray()
56
+ with storage.get_stream(path) as stream:
57
+ while len(out) <= limit:
58
+ try:
59
+ chunk = stream.read(min(_READ_CHUNK, limit + 1 - len(out)))
60
+ except OSError as exc:
61
+ # as txstore's own `get` maps it -> [ROADMAP.md](ROADMAP.md#known-deviations)
62
+ storage.metrics.read_errors_inc()
63
+ raise StorageException(f"Error reading {path}: {exc}") from exc
64
+ size = len(out)
65
+ out += chunk
66
+ # a stream that yields no bytes has ended
67
+ if len(out) == size:
68
+ break
69
+ storage.metrics.read_bytes_inc(len(out))
70
+ if len(out) > limit:
71
+ raise SizeLimitError(f"{path} is larger than {limit} bytes")
72
+ return bytes(out)
73
+
74
+
75
+ class Codec(NamedTuple):
76
+ """How an index file named with `suffix` is encoded and decoded.
77
+
78
+ Attributes:
79
+ suffix: File name suffix, empty for the uncompressed index.
80
+ compress: Encoder.
81
+ decompress: Decoder; refuses output larger than its second argument with
82
+ `SizeLimitError` and a truncated or undecodable stream with `CorruptStreamError`.
83
+ """
84
+
85
+ suffix: str
86
+ compress: Callable[[bytes], bytes]
87
+ decompress: Callable[[bytes, int], bytes]
88
+
89
+
90
+ class _Decoder(Protocol):
91
+ """The incremental decoder shape `lzma`, `bz2` and `zlib` share."""
92
+
93
+ @property
94
+ def eof(self) -> bool:
95
+ """Whether the end-of-stream marker was reached."""
96
+
97
+ @property
98
+ def unused_data(self) -> bytes:
99
+ """Input found after the end of the stream."""
100
+
101
+ def decompress(self, data: Buffer, max_length: int, /) -> bytes:
102
+ """Decode `data`, returning at most `max_length` bytes."""
103
+
104
+
105
+ # each chunk is at most the bytes already read in this stream plus the first chunk, so the
106
+ # bytes read past a stream's end stay within that stream's size (linear in total), and a
107
+ # large stream still needs few decoder calls
108
+ _FIRST_CHUNK = 256
109
+ _LARGEST_CHUNK = 1 << 20
110
+ _NON_NUL = re.compile(rb"[^\0]")
111
+
112
+
113
+ def _bounded(new_decoder: Callable[[], _Decoder], data: bytes, max_size: int) -> bytes:
114
+ """Decode every concatenated stream in `data` without producing more than `max_size` bytes.
115
+
116
+ Each decoder call is capped one byte past what is left, so a bomb stops as soon as it
117
+ overflows instead of after it is fully inflated. Any run of NUL bytes between or after
118
+ streams is skipped for every codec, a deliberate superset of xz's 4-byte stream padding
119
+ and of what the one-shot `gzip.decompress` strips. The input is walked by offset in
120
+ growing chunks, so many concatenated streams decode in linear time instead of copying
121
+ the rest of the input at every stream end.
122
+
123
+ Args:
124
+ new_decoder: Factory of a fresh decoder per stream.
125
+ data: The encoded data.
126
+ max_size: The largest decoded size accepted.
127
+
128
+ Raises:
129
+ SizeLimitError: The decoded data exceeds `max_size`.
130
+ CorruptStreamError: A stream ends before its end-of-stream marker or does not decode.
131
+
132
+ Returns:
133
+ The decoded data of every stream, concatenated.
134
+ """
135
+ view = memoryview(data)
136
+ out = bytearray()
137
+ offset = 0
138
+ while offset < len(data):
139
+ decoder = new_decoder()
140
+ step = _FIRST_CHUNK
141
+ while True:
142
+ chunk = view[offset : offset + step]
143
+ try:
144
+ out += decoder.decompress(chunk, max_size + 1 - len(out))
145
+ except (lzma.LZMAError, OSError, zlib.error) as exc:
146
+ # bz2 reports garbage as OSError; the decoder does no I/O
147
+ raise CorruptStreamError(str(exc)) from exc
148
+ if len(out) > max_size:
149
+ raise SizeLimitError(f"decoded data exceeds {max_size} bytes")
150
+ # under the cap the decoder consumed the whole chunk unless the stream ended in
151
+ # it; at the cap zlib keeps input in `unconsumed_tail`, which the offset
152
+ # arithmetic below would skip, hence the cap check runs first
153
+ if decoder.eof:
154
+ offset += len(chunk) - len(decoder.unused_data)
155
+ break
156
+ offset += len(chunk)
157
+ if offset >= len(data):
158
+ raise CorruptStreamError("compressed data ended before the end-of-stream marker")
159
+ step = min(step * 2, _LARGEST_CHUNK)
160
+ match = _NON_NUL.search(data, offset)
161
+ offset = match.start() if match else len(data)
162
+ return bytes(out)
163
+
164
+
165
+ def _identity(data: bytes) -> bytes:
166
+ """Return an uncompressed index as is."""
167
+ return data
168
+
169
+
170
+ def _identity_bounded(data: bytes, max_size: int) -> bytes:
171
+ """Return an uncompressed index as is, refusing one larger than `max_size`.
172
+
173
+ Raises:
174
+ SizeLimitError: `data` exceeds `max_size`.
175
+ """
176
+ if len(data) > max_size:
177
+ raise SizeLimitError(f"data exceeds {max_size} bytes")
178
+ return data
179
+
180
+
181
+ # preset -9 needs a 64 MiB dictionary; a larger one cannot help under `MAX_INDICES_BYTES`,
182
+ # so a stream asking for more fails as corrupt instead of allocating it
183
+ _LZMA_MEMLIMIT = 128 << 20
184
+
185
+ # `.lzma` is the legacy LZMA-alone format; decoding auto-detects, so an `.lzma`
186
+ # written in xz format by an older debkit still reads
187
+ _lzma_decompress = partial(
188
+ _bounded, partial(lzma.LZMADecompressor, lzma.FORMAT_AUTO, memlimit=_LZMA_MEMLIMIT)
189
+ )
190
+
191
+ # discovery order: the preferred compression first, the uncompressed index last
192
+ # -> [VALIDATION.md](VALIDATION.md#repository-index-paths)
193
+ CODECS: tuple[Codec, ...] = (
194
+ Codec(".xz", lzma.compress, _lzma_decompress),
195
+ Codec(".lzma", partial(lzma.compress, format=lzma.FORMAT_ALONE), _lzma_decompress),
196
+ Codec(".bz2", bz2.compress, partial(_bounded, bz2.BZ2Decompressor)),
197
+ # wbits=31 makes zlib parse the gzip header and check its trailer
198
+ Codec(".gz", gzip.compress, partial(_bounded, partial(zlib.decompressobj, wbits=31))),
199
+ Codec("", _identity, _identity_bounded),
200
+ )
201
+
202
+
203
+ def _feed(stdin: IO[bytes], data: bytes) -> None:
204
+ """Write `data` to a decoder's stdin, which closes early once the output passes its cap."""
205
+ try:
206
+ stdin.write(data)
207
+ stdin.close()
208
+ except BrokenPipeError:
209
+ pass
210
+
211
+
212
+ def zstd_decompress(data: bytes, max_size: int) -> bytes:
213
+ """Decode zstd `data` through the `zstd` binary without producing more than `max_size` bytes.
214
+
215
+ The standard library before Python 3.14 has no zstd decoder. The output is read one byte
216
+ past `max_size` at most, and the decoder is killed there, so a bomb never inflates in full
217
+ -> [VALIDATION.md](VALIDATION.md#object-sizes).
218
+
219
+ Args:
220
+ data: The encoded data.
221
+ max_size: The largest decoded size accepted.
222
+
223
+ Raises:
224
+ SizeLimitError: The decoded data exceeds `max_size`.
225
+ CorruptStreamError: The data does not decode, or `zstd` cannot run.
226
+
227
+ Returns:
228
+ The decoded data.
229
+ """
230
+ try:
231
+ proc = subprocess.Popen(
232
+ ["zstd", "-dc", "-q"],
233
+ stdin=subprocess.PIPE,
234
+ stdout=subprocess.PIPE,
235
+ stderr=subprocess.DEVNULL,
236
+ env=child_env(),
237
+ )
238
+ except OSError as exc:
239
+ raise CorruptStreamError(f"cannot run zstd: {exc}") from exc
240
+ assert proc.stdin is not None
241
+ assert proc.stdout is not None
242
+ writer = threading.Thread(target=_feed, args=(proc.stdin, data), daemon=True)
243
+ writer.start()
244
+ out = proc.stdout.read(max_size + 1)
245
+ if len(out) > max_size:
246
+ proc.kill()
247
+ proc.stdout.close()
248
+ returncode = proc.wait()
249
+ writer.join()
250
+ if len(out) > max_size:
251
+ raise SizeLimitError(f"zstd data decodes past {max_size} bytes")
252
+ if returncode != 0:
253
+ raise CorruptStreamError(f"zstd exited with status {returncode}")
254
+ return out
255
+
256
+
257
+ def codec_for(path: str) -> Codec:
258
+ """Return the codec an index path's suffix names.
259
+
260
+ Args:
261
+ path: Index file path.
262
+
263
+ Returns:
264
+ The matching codec; the uncompressed one when no suffix matches.
265
+ """
266
+ return next(codec for codec in CODECS if path.endswith(codec.suffix))
debkit/repo/debfile.py ADDED
@@ -0,0 +1,207 @@
1
+ """Class containing ``.deb`` file data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import lzma
7
+ import re
8
+ import tarfile
9
+ import zlib
10
+ from collections.abc import Callable
11
+ from io import BytesIO, UnsupportedOperation
12
+ from typing import IO, TYPE_CHECKING
13
+
14
+ from debian import debfile
15
+ from debian.arfile import ArError
16
+ from txstore import StorageException, is_unsafe_path
17
+
18
+ from debkit.repo.compress import CODECS, CorruptStreamError, SizeLimitError, zstd_decompress
19
+ from debkit.repo.package import Package
20
+ from debkit.repo.params import pool_path
21
+
22
+ if TYPE_CHECKING:
23
+ from txstore import Storage
24
+
25
+ logger = logging.getLogger(__name__)
26
+ logger.addHandler(logging.NullHandler())
27
+
28
+ # Debian Policy 5.6.1 and 5.6.7: the `Source` field, or `Package` without one, becomes a pool
29
+ # directory, so both are held to the policy name -> [VALIDATION.md](VALIDATION.md#filename-safety)
30
+ _PACKAGE_NAME = re.compile(r"[a-z0-9][a-z0-9+.-]+")
31
+
32
+ # A binary package built from a source of another version names it as `Source: <name> (<version>)`
33
+ _SOURCE_VERSION = re.compile(r"\s+\([^()]*\)$")
34
+
35
+ # Debian Policy 5.6.12: `[epoch:]upstream[-revision]`, upstream starting alphanumeric (dpkg only
36
+ # warns on a letter) and a hyphen always followed by a revision; a published stanza with no
37
+ # usable Version is one apt cannot install -> [VALIDATION.md](VALIDATION.md#filename-safety)
38
+ _VERSION = re.compile(r"(?:[0-9]+:)?[A-Za-z0-9][A-Za-z0-9.+~-]*(?<!-)")
39
+
40
+
41
+ class DebFileException(Exception):
42
+ """Exception raised for errors inspecting a ``.deb`` file."""
43
+
44
+ def __init__(self, message: str) -> None:
45
+ """Initialize with error message."""
46
+ super().__init__(f"DebFile: {message}")
47
+
48
+
49
+ # Largest compressed `control.tar` member and `control` file read from an upload, and the
50
+ # largest `control.tar` they decode to; all are held in memory before the package is
51
+ # transferred -> [VALIDATION.md](VALIDATION.md#object-sizes)
52
+ MAX_CONTROL_BYTES = 4 * 1024 * 1024
53
+ MAX_CONTROL_TAR_BYTES = 64 * 1024 * 1024
54
+
55
+ # `control.tar` compressions dpkg writes, each decoded under a size limit
56
+ _CONTROL_DECODERS: dict[str, Callable[[bytes, int], bytes]] = {
57
+ **{codec.suffix: codec.decompress for codec in CODECS},
58
+ ".zst": zstd_decompress,
59
+ }
60
+
61
+
62
+ def _control_of(fp: IO[bytes], path: str) -> bytes | None:
63
+ """Return the ``control`` file of the ``.deb`` read from `fp`, refusing an oversized one.
64
+
65
+ The ``control.tar`` member is decoded under `MAX_CONTROL_TAR_BYTES` and walked as a stream,
66
+ so neither a compression bomb nor a tar of many members is inflated in full.
67
+
68
+ Args:
69
+ fp: The open ``.deb``.
70
+ path: Its storage path, for messages.
71
+
72
+ Raises:
73
+ DebFileException: The ``control.tar`` member, its decoded tar, or the ``control`` file
74
+ passes its size limit, or the member is in an unknown compression or does not
75
+ decode.
76
+ DebError: The ``control`` file is missing.
77
+
78
+ Returns:
79
+ The ``control`` file content, or None when it is not a regular file.
80
+ """
81
+ deb = debfile.DebFile(fileobj=fp) # type: ignore[arg-type]
82
+ # python-debian refuses a .deb without exactly one known `control.tar*` member, so one is
83
+ # always found; the first is read, and an unknown one placed ahead is refused below
84
+ part = next(member for member in deb.getmembers() if member.name.startswith("control.tar"))
85
+ if part.size > MAX_CONTROL_BYTES:
86
+ raise DebFileException(f"{part.name} of {path} is larger than {MAX_CONTROL_BYTES} bytes")
87
+ decode = _CONTROL_DECODERS.get(part.name.removeprefix("control.tar"))
88
+ if decode is None:
89
+ raise DebFileException(f"{part.name} of {path} has an unknown compression")
90
+ try:
91
+ tar_data = decode(part.read(), MAX_CONTROL_TAR_BYTES)
92
+ except SizeLimitError as exc:
93
+ raise DebFileException(
94
+ f"{part.name} of {path} decodes past {MAX_CONTROL_TAR_BYTES} bytes"
95
+ ) from exc
96
+ except CorruptStreamError as exc:
97
+ raise DebFileException(f"Invalid .deb file {path}: {part.name}: {exc}") from exc
98
+
99
+ with tarfile.open(fileobj=BytesIO(tar_data), mode="r|") as tar:
100
+ for member in tar:
101
+ if member.name not in ("./control", "control"):
102
+ continue
103
+ if member.size > MAX_CONTROL_BYTES:
104
+ raise DebFileException(
105
+ f"control file of {path} is larger than {MAX_CONTROL_BYTES} bytes"
106
+ )
107
+ handle = tar.extractfile(member)
108
+ return handle.read() if handle is not None else None
109
+ raise debfile.DebError("File not found inside package")
110
+
111
+
112
+ class DebFile:
113
+ """Read-side wrapper around a ``.deb`` package on a `Storage` backend.
114
+
115
+ The control file is read once at construction; the storage handle is closed before the
116
+ constructor returns, whether it succeeds or fails.
117
+
118
+ Attributes:
119
+ storage: Storage backend the file lives on.
120
+ path: Path of the ``.deb`` file inside ``storage``.
121
+ comp: Component name the package belongs to, or None for a pool without one.
122
+ control: Content of the ``control`` file in ``control.tar``.
123
+ """
124
+
125
+ def __init__(self, storage: Storage, path: str, comp: str | None = None) -> None:
126
+ """Initialize DebFile object.
127
+
128
+ Args:
129
+ storage: Storage backend.
130
+ path: Path to the Debian package file.
131
+ comp: Component name. Defaults to None.
132
+
133
+ Raises:
134
+ DebFileException: If the underlying ``.deb`` cannot be read or parsed.
135
+ """
136
+ self.storage = storage
137
+ self.path = path
138
+ self.comp = comp
139
+ try:
140
+ self.control = self._read_control()
141
+ except StorageException as exc:
142
+ raise DebFileException(f"Cannot read .deb file {path}: {exc}") from exc
143
+ # `ArError` is the base of `DebError`; a truncated ar header raises a bare `OSError`, a
144
+ # truncated `control.tar` member an `EOFError` or a `TarError`, and one whose compressed
145
+ # data does not decode past its first tar header an `LZMAError` or a `zlib.error`
146
+ except (ArError, tarfile.TarError, EOFError, OSError, lzma.LZMAError, zlib.error) as exc:
147
+ raise DebFileException(f"Invalid .deb file {path}: {exc}") from exc
148
+
149
+ def _read_control(self) -> bytes | None:
150
+ """Read the ``control`` file, streaming when the backend can seek.
151
+
152
+ Returns:
153
+ The ``control`` file content.
154
+ """
155
+ try:
156
+ with self.storage.get_stream(self.path) as fp:
157
+ return _control_of(fp, self.path)
158
+ except UnsupportedOperation as exc:
159
+ logger.debug("%s cannot stream (%s); reading it into memory.", self.path, exc)
160
+ with BytesIO(self.storage.get(self.path)) as fp:
161
+ return _control_of(fp, self.path)
162
+
163
+ def get_package(self) -> Package:
164
+ """Get control data from the Debian package.
165
+
166
+ The control file comes from the upload, so its `Package`, `Source`, and `Version` fields
167
+ and the upload path are checked before they are published; nothing has been transferred
168
+ yet.
169
+
170
+ Raises:
171
+ DebFileException: If the control file is not a bytes object.
172
+ DebFileException: If the control file is not UTF-8.
173
+ DebFileException: If the `Package` field is missing or not a policy name.
174
+ DebFileException: If the `Source` field, without its version, is not a policy name.
175
+ DebFileException: If the `Version` field is missing or not a Debian version.
176
+ DebFileException: If the pool key would be an unsafe storage path.
177
+
178
+ Returns:
179
+ Package object with control data.
180
+ """
181
+ control = self.control
182
+ if not isinstance(control, bytes):
183
+ raise DebFileException(f"control file of {self.path} is not a bytes object")
184
+ # Debian Policy 5.1: control data is UTF-8
185
+ # -> [VALIDATION.md](VALIDATION.md#control-file-encoding)
186
+ try:
187
+ control_lines = control.decode("utf-8")
188
+ except UnicodeDecodeError as exc:
189
+ raise DebFileException(f"control file of {self.path} is not UTF-8: {exc}") from exc
190
+ package: Package = Package(fields={"Filename": "", "Size": "0"})
191
+ package.parse(control_lines, controls_only=True)
192
+ pkg_name = package.fields.get("Package")
193
+ if not isinstance(pkg_name, str) or not _PACKAGE_NAME.fullmatch(pkg_name):
194
+ raise DebFileException(f"{self.path} names no valid Package: {pkg_name!r}")
195
+ source = _SOURCE_VERSION.sub("", str(package.fields.get("Source", pkg_name)))
196
+ if not _PACKAGE_NAME.fullmatch(source):
197
+ raise DebFileException(f"{self.path} names no valid Source: {source!r}")
198
+ version = package.fields.get("Version")
199
+ if not isinstance(version, str) or not _VERSION.fullmatch(version):
200
+ raise DebFileException(f"{self.path} names no valid Version: {version!r}")
201
+
202
+ filename = pool_path(self.comp, source, self.path)
203
+ if is_unsafe_path(filename):
204
+ raise DebFileException(f"unsafe pool path for {self.path}: {filename!r}")
205
+ package.set_filename(filename)
206
+
207
+ return package
debkit/repo/gnupg.py ADDED
@@ -0,0 +1,215 @@
1
+ """GnuPG signatures verify / create."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import tempfile
9
+
10
+ import gnupg
11
+
12
+ from debkit._env import child_env
13
+
14
+ logger = logging.getLogger(__name__)
15
+ logger.addHandler(logging.NullHandler())
16
+
17
+
18
+ CLEARSIGN_BEGIN = "-----BEGIN PGP SIGNED MESSAGE-----"
19
+ SIGNATURE_BEGIN = "-----BEGIN PGP SIGNATURE-----"
20
+ SIGNATURE_END = "-----END PGP SIGNATURE-----"
21
+ ARMOR_HEADER_RE = re.compile(r"[A-Za-z]+: ")
22
+ # No gpg run fetches, locates, or imports a key, whatever a config file says; for verify this
23
+ # backs up `VERIFY_ARGS`, which already skips gpg.conf -> [CRYPTO.md](CRYPTO.md#gpg).
24
+ GPG_OPTIONS = ("--no-auto-key-retrieve", "--no-auto-key-locate", "--no-auto-key-import")
25
+ # Verify reads no gpg.conf, whose `keyring` lines would add keys that authenticate; signing still
26
+ # reads it for `default-key` -> [CRYPTO.md](CRYPTO.md#gpg).
27
+ VERIFY_ARGS = ("--no-options",)
28
+
29
+
30
+ class GPGVerifyException(Exception):
31
+ """Exception raised for errors in verify the repository via GPG or checksum."""
32
+
33
+ def __init__(self, message: str) -> None:
34
+ """Initialize with error message."""
35
+ super().__init__(f"Repo verify: {message}")
36
+
37
+
38
+ def cleartext_body(data: bytes) -> bytes:
39
+ """Get the signed body of a cleartext signed message without checking its signature.
40
+
41
+ gpg authenticates only the body between the armor headers and the signature,
42
+ and hashes each line with trailing spaces, tabs and CR stripped. Every line is
43
+ canonicalized the same way before parsing, so no unsigned byte reaches the
44
+ caller and nothing may follow the signature -> [CRYPTO.md](CRYPTO.md#gpg).
45
+ Works on bytes like `canonical_text`, so the body keeps its encoding and each
46
+ caller decodes it as it decodes an unsigned file.
47
+
48
+ Args:
49
+ data: Signed message
50
+
51
+ Raises:
52
+ GPGVerifyException: Signed message is not in correct format, has invalid
53
+ armor headers, an unescaped dash line, or data after the signature.
54
+
55
+ Returns:
56
+ The canonical signed body, dash-escaping undone, each line ending in a newline.
57
+ """
58
+ # latin-1 maps every byte to one character and back, so no input fails to decode
59
+ lines = [line.rstrip(" \t\r") for line in data.decode("latin-1").split("\n")]
60
+ if lines[0] != CLEARSIGN_BEGIN:
61
+ raise GPGVerifyException("Signed message is not in correct format.")
62
+
63
+ try:
64
+ body_start = lines.index("", 1) + 1
65
+ sig_start = lines.index(SIGNATURE_BEGIN, body_start)
66
+ sig_end = lines.index(SIGNATURE_END, sig_start + 1)
67
+ except ValueError:
68
+ raise GPGVerifyException("Signed message is not in correct format.") from None
69
+
70
+ if not all(ARMOR_HEADER_RE.match(line) for line in lines[1 : body_start - 1]):
71
+ raise GPGVerifyException("Signed message has invalid armor headers.")
72
+ if any(line.strip() for line in lines[sig_end + 1 :]):
73
+ raise GPGVerifyException("Signed message has unsigned data after the signature.")
74
+
75
+ body: list[str] = []
76
+ for line in lines[body_start:sig_start]:
77
+ if line.startswith("- "):
78
+ line = line[2:]
79
+ elif line.startswith("-"):
80
+ raise GPGVerifyException("Signed message has an unescaped dash line.")
81
+ body.append(f"{line}\n")
82
+
83
+ return "".join(body).encode("latin-1")
84
+
85
+
86
+ def canonical_text(data: bytes) -> bytes:
87
+ """Canonicalize text the way `cleartext_body` returns a signed body.
88
+
89
+ Trailing spaces, tabs and CR are stripped from every line and each line ends in a
90
+ newline, so a detached `Release` compares equal to the body of an `InRelease`
91
+ clearsigned from it -> [CRYPTO.md](CRYPTO.md#gpg). Works on bytes, so a Release in
92
+ any ASCII-compatible encoding compares alike.
93
+
94
+ Args:
95
+ data: Text to canonicalize.
96
+
97
+ Returns:
98
+ The canonical text, each line ending in a newline.
99
+ """
100
+ lines = [line.rstrip(b" \t\r") for line in data.split(b"\n")]
101
+ if lines[-1] == b"":
102
+ lines.pop()
103
+ return b"".join(line + b"\n" for line in lines)
104
+
105
+
106
+ class GnuPG:
107
+ """Object for GPG signatures operations.
108
+
109
+ Attributes:
110
+ gnupg: The python-gnupg `GPG` object.
111
+ passphrase: The passphrase for the signing key; None when empty.
112
+ sign_key: The key that signs, a fingerprint, key ID, or user ID; None leaves the
113
+ choice to gpg.
114
+ """
115
+
116
+ def __init__(
117
+ self, home: str, keyring: str, passphrase: str | None, sign_key: str | None = None
118
+ ) -> None:
119
+ """Open the keyring `keyring` in the GnuPG home `home`.
120
+
121
+ Args:
122
+ home: GnuPG home directory; a leading `~` is expanded, as a shell would.
123
+ keyring: Keyring file, relative to `home`.
124
+ passphrase: Passphrase of the signing key; empty or None sends none.
125
+ sign_key: The key that signs; empty or None leaves the choice to gpg
126
+ -> [CRYPTO.md](CRYPTO.md#gpg).
127
+
128
+ Raises:
129
+ GPGVerifyException: If the keyring cannot be opened or the gpg binary cannot be run.
130
+ """
131
+ try:
132
+ self.gnupg = gnupg.GPG(
133
+ gnupghome=os.path.expanduser(home),
134
+ keyring=keyring,
135
+ options=list(GPG_OPTIONS),
136
+ env=child_env(),
137
+ )
138
+ except ValueError as exc:
139
+ raise GPGVerifyException(f"Keyring error. {exc}") from exc
140
+ except OSError as exc:
141
+ raise GPGVerifyException(f"Cannot run gpg; is GnuPG installed? {exc}") from exc
142
+
143
+ # An empty string would make python-gnupg pass `--passphrase-fd 0` without writing a
144
+ # passphrase, so gpg reads the first line of the signed data as one and drops it.
145
+ self.passphrase: str | None = passphrase or None
146
+ self.sign_key: str | None = sign_key or None
147
+
148
+ def verify(self, data: bytes, detach_sign: bytes | None = None) -> bytes:
149
+ """Verifying GPG signature.
150
+
151
+ Args:
152
+ data: Signed message
153
+ detach_sign: Detached signature. If None, data should be from InRelease file. Defaults
154
+ to None.
155
+
156
+ Raises:
157
+ GPGVerifyException: GPG not valid signature!
158
+
159
+ Returns:
160
+ Original text
161
+ """
162
+ if detach_sign is None:
163
+ # data should be from InRelease
164
+ verified = self.gnupg.verify(data, extra_args=list(VERIFY_ARGS))
165
+ else:
166
+ # python-gnupg's `verify_data` reads the detached signature from a path, so it is
167
+ # staged in a file closed before gpg opens it and removed when the context exits,
168
+ # a failed write included
169
+ with tempfile.NamedTemporaryFile(suffix=".gpg", delete_on_close=False) as tmp:
170
+ tmp.write(detach_sign)
171
+ tmp.close()
172
+ try:
173
+ verified = self.gnupg.verify_data(tmp.name, data, extra_args=list(VERIFY_ARGS))
174
+ except AttributeError as exc:
175
+ raise GPGVerifyException("GPG gnupg_home data error.") from exc
176
+
177
+ if not verified:
178
+ # the `gnupg` logger is held quiet at debug, so the reason is logged here
179
+ logger.debug("gpg verification failed: %s", getattr(verified, "status", None))
180
+ raise GPGVerifyException("GPG not valid signature!")
181
+
182
+ logger.info("GPG verified. Signed by %s", verified.username)
183
+
184
+ if detach_sign is None:
185
+ return cleartext_body(data)
186
+
187
+ return data
188
+
189
+ def sign(self, data: bytes, detach: bool = False) -> str:
190
+ """Create GPG signature.
191
+
192
+ Args:
193
+ data: Data to sign.
194
+ detach: Detach signature. Defaults to False.
195
+
196
+ Returns:
197
+ GPG signature; empty when gpg created none, e.g. on a wrong passphrase.
198
+ """
199
+ if detach:
200
+ logger.info("Generate detached GPG signature.")
201
+ else:
202
+ logger.info("Generate GPG signed data.")
203
+
204
+ # python-gnupg's `keyid` is gpg's `--default-key`, which falls back to another key when
205
+ # the named one is unusable; `--local-user` signs with that key or with none
206
+ extra_args = ["--local-user", self.sign_key] if self.sign_key else None
207
+ signed_data = self.gnupg.sign(
208
+ data, detach=detach, passphrase=self.passphrase, extra_args=extra_args
209
+ )
210
+ # a failed clearsign still prints the armor header and body, so the text alone does
211
+ # not tell a signature; python-gnupg is true only once gpg reported one created
212
+ if not signed_data:
213
+ logger.debug("gpg created no signature: %s", getattr(signed_data, "status", None))
214
+ return ""
215
+ return str(signed_data)