2021-08-25 11:53:07 -05:00
|
|
|
#!/usr/bin/env python
|
2021-10-16 17:50:34 -05:00
|
|
|
#
|
|
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
from argparse import ArgumentParser
|
2021-08-25 11:53:07 -05:00
|
|
|
from collections import defaultdict
|
2021-10-20 13:16:33 -05:00
|
|
|
from collections.abc import Iterable
|
|
|
|
from collections.abc import Iterator
|
2021-10-16 17:50:34 -05:00
|
|
|
from contextlib import contextmanager
|
2021-10-23 19:16:25 -05:00
|
|
|
from datetime import datetime
|
|
|
|
from functools import reduce
|
2021-10-20 13:15:42 -05:00
|
|
|
from itertools import chain
|
2021-10-18 05:58:23 -05:00
|
|
|
from logging import DEBUG
|
|
|
|
from logging import basicConfig
|
|
|
|
from logging import debug
|
|
|
|
from os import chdir
|
|
|
|
from os import getcwd
|
2021-08-25 11:53:07 -05:00
|
|
|
from pathlib import Path
|
2021-10-18 05:58:23 -05:00
|
|
|
from re import escape
|
2021-10-22 20:01:06 -05:00
|
|
|
from re import match
|
2021-10-18 05:58:23 -05:00
|
|
|
from re import split
|
|
|
|
from re import sub
|
2021-10-04 12:25:24 -05:00
|
|
|
from shutil import copytree
|
2021-10-18 05:58:23 -05:00
|
|
|
from subprocess import PIPE
|
|
|
|
from subprocess import CalledProcessError
|
|
|
|
from subprocess import check_output
|
|
|
|
from sys import exit
|
|
|
|
from sys import stderr
|
|
|
|
from tempfile import TemporaryDirectory
|
|
|
|
from tempfile import mkdtemp
|
2021-10-21 14:51:02 -05:00
|
|
|
from tempfile import mkstemp
|
2021-10-21 13:18:21 -05:00
|
|
|
from traceback import print_stack
|
2021-10-18 05:58:23 -05:00
|
|
|
from typing import Dict
|
|
|
|
from typing import List
|
2021-10-19 10:35:59 -05:00
|
|
|
from typing import NewType
|
2021-10-18 05:58:23 -05:00
|
|
|
from typing import Optional
|
|
|
|
from typing import Set
|
|
|
|
from typing import Tuple
|
|
|
|
from typing import Union
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-19 14:11:37 -05:00
|
|
|
Fingerprint = NewType("Fingerprint", str)
|
|
|
|
Uid = NewType("Uid", str)
|
|
|
|
Username = NewType("Username", str)
|
2021-10-19 10:35:59 -05:00
|
|
|
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
@contextmanager
|
2021-10-12 12:35:18 -05:00
|
|
|
def cwd(new_dir: Path) -> Iterator[None]:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Change to a new current working directory in a context and go back to the previous dir after the context is done
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
new_dir: A path to change to
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
previous_dir = getcwd()
|
|
|
|
chdir(new_dir)
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
chdir(previous_dir)
|
|
|
|
|
|
|
|
|
|
|
|
def natural_sort_path(_list: Iterable[Path]) -> Iterable[Path]:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Sort an Iterable of Paths naturally
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
_list: An iterable containing paths to be sorted
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Return
|
|
|
|
------
|
2021-10-22 15:08:11 -05:00
|
|
|
An Iterable of paths that are naturally sorted
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-19 11:23:08 -05:00
|
|
|
def convert_text_chunk(text: str) -> Union[int, str]:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Convert input text to int or str
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
text: An input string
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
Either an integer if text is a digit, else text in lower-case representation
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
return int(text) if text.isdigit() else text.lower()
|
|
|
|
|
2021-10-11 06:00:48 -05:00
|
|
|
def alphanum_key(key: Path) -> List[Union[int, str]]:
|
|
|
|
"""Retrieve an alphanumeric key from a Path, that can be used in sorted()
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
key: A path for which to create a key
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
A list of either int or str objects that may serve as 'key' argument for sorted()
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-19 11:23:08 -05:00
|
|
|
return [convert_text_chunk(c) for c in split("([0-9]+)", str(key.name))]
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
return sorted(_list, key=alphanum_key)
|
|
|
|
|
|
|
|
|
2021-10-21 14:05:03 -05:00
|
|
|
def system(cmd: List[str], exit_on_error: bool = False) -> str:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Execute a command using check_output
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
cmd: A list of strings to be fed to check_output
|
|
|
|
exit_on_error: Whether to exit the script when encountering an error (defaults to False)
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
2021-10-22 15:08:11 -05:00
|
|
|
CalledProcessError: If not exit_on_error and `check_output()` encounters an error
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The output of cmd
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
try:
|
|
|
|
return check_output(cmd, stderr=PIPE).decode()
|
|
|
|
except CalledProcessError as e:
|
|
|
|
stderr.buffer.write(e.stderr)
|
2021-10-21 13:18:21 -05:00
|
|
|
print_stack()
|
2021-08-25 11:53:07 -05:00
|
|
|
if exit_on_error:
|
|
|
|
exit(e.returncode)
|
|
|
|
raise e
|
|
|
|
|
|
|
|
|
2021-10-22 20:01:06 -05:00
|
|
|
def is_pgp_fingerprint(string: str) -> bool:
|
|
|
|
"""Returns whether the passed string looks like a PGP (long) fingerprint
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
string: Input to consider as a fingerprint
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
RWhether string is a fingerprint
|
|
|
|
"""
|
|
|
|
if len(string) not in [16, 40]:
|
|
|
|
return False
|
|
|
|
return match("^[A-F0-9]+$", string) is not None
|
|
|
|
|
|
|
|
|
2021-10-22 13:17:50 -05:00
|
|
|
def get_cert_paths(paths: Iterable[Path]) -> Set[Path]:
|
|
|
|
"""Walks a list of paths and resolves all discovered certificate paths
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
paths: A list of paths to walk and resolve to certificate paths.
|
2021-10-22 13:17:50 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The list of paths to certificates
|
2021-10-22 13:17:50 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
# depth first search certificate paths
|
|
|
|
cert_paths: Set[Path] = set()
|
|
|
|
visit: List[Path] = list(paths)
|
|
|
|
while visit:
|
|
|
|
path = visit.pop()
|
2021-10-23 09:40:32 -05:00
|
|
|
if not path.exists():
|
|
|
|
continue
|
2021-10-22 13:17:50 -05:00
|
|
|
# this level contains a certificate, abort depth search
|
|
|
|
if list(path.glob("*.asc")):
|
|
|
|
cert_paths.add(path)
|
|
|
|
continue
|
|
|
|
visit.extend([path for path in path.iterdir() if path.is_dir()])
|
|
|
|
return cert_paths
|
|
|
|
|
|
|
|
|
2021-10-23 10:13:46 -05:00
|
|
|
def transform_username_to_keyring_path(keyring_dir: Path, paths: List[Path]) -> None:
|
|
|
|
"""Mutates the input sources by transforming passed usernames to keyring paths
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
keyring_dir: The directory underneath the username needs to exist
|
|
|
|
paths: A list of paths to mutate and replace usernames to keyring paths
|
|
|
|
"""
|
|
|
|
for index, source in enumerate(paths):
|
|
|
|
if source.exists():
|
|
|
|
continue
|
|
|
|
packager_source = keyring_dir / source.name
|
|
|
|
if not packager_source.exists():
|
|
|
|
continue
|
|
|
|
paths[index] = packager_source
|
|
|
|
|
|
|
|
|
|
|
|
def transform_fingerprint_to_keyring_path(keyring_root: Path, paths: List[Path]) -> None:
|
|
|
|
"""Mutates the input sources by transforming passed fingerprints to keyring paths
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
keyring_root: The keyring root directory to look up fingerprints in
|
|
|
|
paths: A list of paths to mutate and replace fingerprints to keyring paths
|
|
|
|
"""
|
|
|
|
for index, source in enumerate(paths):
|
|
|
|
if source.exists():
|
|
|
|
continue
|
|
|
|
if not is_pgp_fingerprint(source.name):
|
|
|
|
continue
|
|
|
|
fingerprint_paths = list(keyring_root.glob(f"*/*/*{source.name}"))
|
|
|
|
if not fingerprint_paths:
|
|
|
|
continue
|
|
|
|
paths[index] = fingerprint_paths[0].parent
|
|
|
|
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
# TODO: simplify to lower complexity
|
|
|
|
def convert_certificate( # noqa: ignore=C901
|
|
|
|
working_dir: Path,
|
|
|
|
certificate: Path,
|
2021-10-19 12:10:51 -05:00
|
|
|
keyring_dir: Path,
|
2021-10-19 14:03:53 -05:00
|
|
|
name_override: Optional[Username] = None,
|
2021-10-19 10:35:59 -05:00
|
|
|
fingerprint_filter: Optional[Set[Fingerprint]] = None,
|
2021-10-16 17:50:34 -05:00
|
|
|
) -> Path:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Convert a single file public key certificate into a decomposed directory structure of multiple PGP packets
|
|
|
|
|
2021-10-19 12:10:51 -05:00
|
|
|
The output directory structure is created per user. The username is derived from the certificate via
|
|
|
|
`derive_username_from_fingerprint` or overridden via `name_override`.
|
2021-10-19 11:41:58 -05:00
|
|
|
Below the username directory a directory tree describes the public keys components split up into certifications
|
2021-10-11 06:00:48 -05:00
|
|
|
and revocations, as well as per subkey and per uid certifications and revocations.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: The path of the working directory below which to create split certificates
|
|
|
|
certificate: The path to a public key certificate
|
|
|
|
keyring_dir: The path of the keyring used to try to derive the username from the public key fingerprint
|
|
|
|
name_override: An optional string to override the username in the to be created output directory structure
|
|
|
|
fingerprint_filter: Optional list of fingerprints of PGP public keys that all certifications will be filtered with
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
2021-10-22 15:08:11 -05:00
|
|
|
Exception: If required PGP packets are not found
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The path of the user_dir (which is located below working_dir)
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-19 10:35:59 -05:00
|
|
|
# root packets
|
|
|
|
certificate_fingerprint: Optional[Fingerprint] = None
|
2021-08-25 11:53:07 -05:00
|
|
|
pubkey: Optional[Path] = None
|
2021-10-23 19:16:25 -05:00
|
|
|
# TODO: direct key certifications are not yet selecting the latest sig, owner may have multiple
|
|
|
|
# TODO: direct key certifications are not yet single packet per file
|
2021-10-19 13:08:32 -05:00
|
|
|
direct_sigs: Dict[Fingerprint, List[Path]] = defaultdict(list)
|
|
|
|
direct_revocations: Dict[Fingerprint, List[Path]] = defaultdict(list)
|
2021-10-19 10:35:59 -05:00
|
|
|
|
|
|
|
# subkey packets
|
2021-10-19 11:26:50 -05:00
|
|
|
subkeys: Dict[Fingerprint, Path] = {}
|
2021-10-23 19:16:25 -05:00
|
|
|
subkey_bindings: Dict[Fingerprint, List[Path]] = defaultdict(list)
|
|
|
|
subkey_revocations: Dict[Fingerprint, List[Path]] = defaultdict(list)
|
2021-10-19 10:35:59 -05:00
|
|
|
|
|
|
|
# uid packets
|
|
|
|
uids: Dict[Uid, Path] = {}
|
2021-10-23 19:16:25 -05:00
|
|
|
certifications: Dict[Uid, Dict[Fingerprint, List[Path]]] = defaultdict(lambda: defaultdict(list))
|
|
|
|
revocations: Dict[Uid, Dict[Fingerprint, List[Path]]] = defaultdict(lambda: defaultdict(list))
|
2021-10-19 10:35:59 -05:00
|
|
|
|
|
|
|
# intermediate variables
|
2021-08-25 11:53:07 -05:00
|
|
|
current_packet_mode: Optional[str] = None
|
2021-10-19 10:35:59 -05:00
|
|
|
current_packet_fingerprint: Optional[Fingerprint] = None
|
|
|
|
current_packet_uid: Optional[Uid] = None
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
# XXX: PrimaryKeyBinding
|
|
|
|
|
|
|
|
# TODO: remove 3rd party direct key signatures, seems to be leaked by export-clean
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
debug(f"Processing certificate {certificate}")
|
2021-10-03 13:05:11 -05:00
|
|
|
|
2021-10-04 15:12:33 -05:00
|
|
|
for packet in packet_split(working_dir=working_dir, certificate=certificate):
|
2021-10-16 17:50:34 -05:00
|
|
|
debug(f"Processing packet {packet.name}")
|
|
|
|
if packet.name.endswith("--PublicKey"):
|
|
|
|
current_packet_mode = "pubkey"
|
2021-10-19 10:35:59 -05:00
|
|
|
current_packet_fingerprint = Fingerprint(packet_dump_field(packet, "Fingerprint"))
|
|
|
|
current_packet_uid = None
|
|
|
|
|
|
|
|
certificate_fingerprint = current_packet_fingerprint
|
|
|
|
pubkey = packet
|
2021-10-16 17:50:34 -05:00
|
|
|
elif packet.name.endswith("--UserID"):
|
|
|
|
current_packet_mode = "uid"
|
2021-10-19 10:35:59 -05:00
|
|
|
current_packet_fingerprint = None
|
|
|
|
current_packet_uid = simplify_user_id(Uid(packet_dump_field(packet, "Value")))
|
|
|
|
|
|
|
|
uids[current_packet_uid] = packet
|
2021-10-16 17:50:34 -05:00
|
|
|
elif packet.name.endswith("--PublicSubkey"):
|
|
|
|
current_packet_mode = "subkey"
|
2021-10-19 10:35:59 -05:00
|
|
|
current_packet_fingerprint = Fingerprint(packet_dump_field(packet, "Fingerprint"))
|
|
|
|
current_packet_uid = None
|
2021-10-09 05:56:33 -05:00
|
|
|
|
2021-10-19 11:26:50 -05:00
|
|
|
subkeys[current_packet_fingerprint] = packet
|
2021-10-16 17:50:34 -05:00
|
|
|
elif packet.name.endswith("--Signature"):
|
2021-08-25 11:53:07 -05:00
|
|
|
if not certificate_fingerprint:
|
|
|
|
raise Exception('missing certificate fingerprint for "{packet.name}"')
|
|
|
|
|
2021-10-19 13:08:32 -05:00
|
|
|
issuer: Fingerprint = Fingerprint(packet_dump_field(packet, "Issuer"))
|
2021-10-16 17:50:34 -05:00
|
|
|
signature_type = packet_dump_field(packet, "Type")
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
if current_packet_mode == "pubkey":
|
2021-10-19 10:35:59 -05:00
|
|
|
if not current_packet_fingerprint:
|
|
|
|
raise Exception('missing current packet fingerprint for "{packet.name}"')
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
if signature_type == "KeyRevocation" and certificate_fingerprint.endswith(issuer):
|
2021-10-19 11:26:50 -05:00
|
|
|
direct_revocations[issuer].append(packet)
|
2021-10-16 17:50:34 -05:00
|
|
|
elif signature_type in ["DirectKey", "GenericCertification"]:
|
2021-10-19 11:26:50 -05:00
|
|
|
direct_sigs[issuer].append(packet)
|
2021-08-25 11:53:07 -05:00
|
|
|
else:
|
2021-10-16 17:50:34 -05:00
|
|
|
raise Exception(f"unknown signature type: {signature_type}")
|
|
|
|
elif current_packet_mode == "uid":
|
2021-10-19 10:35:59 -05:00
|
|
|
if not current_packet_uid:
|
|
|
|
raise Exception('missing current packet uid for "{packet.name}"')
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
if signature_type == "CertificationRevocation":
|
2021-10-23 19:16:25 -05:00
|
|
|
revocations[current_packet_uid][issuer].append(packet)
|
2021-10-16 17:50:34 -05:00
|
|
|
elif signature_type.endswith("Certification"):
|
2021-10-18 05:47:12 -05:00
|
|
|
if fingerprint_filter is not None and any([fp.endswith(issuer) for fp in fingerprint_filter]):
|
|
|
|
debug(f"The certification by issuer {issuer} is appended as it is found in the filter.")
|
2021-10-23 19:16:25 -05:00
|
|
|
certifications[current_packet_uid][issuer].append(packet)
|
2021-10-18 05:47:12 -05:00
|
|
|
else:
|
|
|
|
debug(f"The certification by issuer {issuer} is not appended because it is not in the filter")
|
2021-10-09 16:42:13 -05:00
|
|
|
else:
|
2021-10-16 17:50:34 -05:00
|
|
|
raise Exception(f"unknown signature type: {signature_type}")
|
|
|
|
elif current_packet_mode == "subkey":
|
2021-10-19 10:35:59 -05:00
|
|
|
if not current_packet_fingerprint:
|
|
|
|
raise Exception('missing current packet fingerprint for "{packet.name}"')
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
if signature_type == "SubkeyBinding":
|
2021-10-23 19:16:25 -05:00
|
|
|
subkey_bindings[current_packet_fingerprint].append(packet)
|
2021-10-16 17:50:34 -05:00
|
|
|
elif signature_type == "SubkeyRevocation":
|
2021-10-23 19:16:25 -05:00
|
|
|
subkey_revocations[certificate_fingerprint].append(packet)
|
2021-08-25 11:53:07 -05:00
|
|
|
else:
|
2021-10-16 17:50:34 -05:00
|
|
|
raise Exception(f"unknown signature type: {signature_type}")
|
2021-08-25 11:53:07 -05:00
|
|
|
else:
|
|
|
|
raise Exception(f'unknown signature root for "{packet.name}"')
|
|
|
|
else:
|
|
|
|
raise Exception(f'unknown packet type "{packet.name}"')
|
|
|
|
|
|
|
|
if not certificate_fingerprint:
|
2021-10-16 17:50:34 -05:00
|
|
|
raise Exception("missing certificate fingerprint")
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
if not pubkey:
|
2021-10-16 17:50:34 -05:00
|
|
|
raise Exception("missing certificate public-key")
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-19 14:11:37 -05:00
|
|
|
name_override = (
|
|
|
|
name_override
|
|
|
|
or derive_username_from_fingerprint(keyring_dir=keyring_dir, certificate_fingerprint=certificate_fingerprint)
|
|
|
|
or Username(certificate.stem)
|
|
|
|
)
|
2021-10-19 12:10:51 -05:00
|
|
|
|
|
|
|
user_dir = working_dir / name_override
|
2021-10-16 17:50:34 -05:00
|
|
|
key_dir = user_dir / certificate_fingerprint
|
2021-10-09 05:56:33 -05:00
|
|
|
key_dir.mkdir(parents=True, exist_ok=True)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-09 16:42:13 -05:00
|
|
|
persist_public_key(
|
2021-10-03 08:06:33 -05:00
|
|
|
certificate_fingerprint=certificate_fingerprint,
|
|
|
|
pubkey=pubkey,
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir=key_dir,
|
2021-10-09 16:42:13 -05:00
|
|
|
)
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
persist_direct_key_certifications(
|
|
|
|
direct_key_certifications=direct_sigs,
|
|
|
|
key_dir=key_dir,
|
|
|
|
)
|
|
|
|
|
|
|
|
persist_direct_key_revocations(
|
|
|
|
direct_key_revocations=direct_revocations,
|
2021-10-09 16:42:13 -05:00
|
|
|
key_dir=key_dir,
|
2021-10-03 08:06:33 -05:00
|
|
|
)
|
|
|
|
|
2021-10-09 05:56:33 -05:00
|
|
|
persist_subkeys(
|
|
|
|
key_dir=key_dir,
|
|
|
|
subkeys=subkeys,
|
2021-10-23 15:08:04 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
persist_subkey_bindings(
|
|
|
|
key_dir=key_dir,
|
|
|
|
subkey_bindings=subkey_bindings,
|
2021-10-09 05:56:33 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
persist_subkey_revocations(
|
|
|
|
key_dir=key_dir,
|
|
|
|
subkey_revocations=subkey_revocations,
|
|
|
|
)
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
persist_uids(
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir=key_dir,
|
2021-10-23 08:49:11 -05:00
|
|
|
uids=uids,
|
2021-10-03 13:05:11 -05:00
|
|
|
)
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
persist_uid_certifications(
|
2021-10-03 08:06:33 -05:00
|
|
|
certifications=certifications,
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir=key_dir,
|
2021-10-03 08:06:33 -05:00
|
|
|
)
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
persist_uid_revocations(
|
2021-10-03 08:06:33 -05:00
|
|
|
revocations=revocations,
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir=key_dir,
|
2021-10-03 08:06:33 -05:00
|
|
|
)
|
|
|
|
|
2021-10-03 14:41:09 -05:00
|
|
|
return user_dir
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
|
2021-10-09 16:42:13 -05:00
|
|
|
def persist_public_key(
|
2021-10-19 10:35:59 -05:00
|
|
|
certificate_fingerprint: Fingerprint,
|
2021-10-03 08:06:33 -05:00
|
|
|
pubkey: Path,
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir: Path,
|
2021-10-03 08:06:33 -05:00
|
|
|
) -> None:
|
2021-10-09 16:42:13 -05:00
|
|
|
"""Persist the Public-Key packet
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
certificate_fingerprint: The unique fingerprint of the public key
|
|
|
|
pubkey: The path to the public key of the root key
|
|
|
|
key_dir: The root directory below which the basic key material is persisted
|
2021-10-03 08:06:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
packets: List[Path] = [pubkey]
|
2021-10-16 17:50:34 -05:00
|
|
|
output_file = key_dir / f"{certificate_fingerprint}.asc"
|
2021-10-12 17:09:58 -05:00
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
2021-10-16 17:50:34 -05:00
|
|
|
debug(f"Writing file {output_file} from {[str(packet) for packet in packets]}")
|
2021-10-21 16:49:40 -05:00
|
|
|
packet_join(packets, output_file, force=True)
|
2021-10-09 05:56:33 -05:00
|
|
|
|
|
|
|
|
2021-10-09 16:42:13 -05:00
|
|
|
def persist_uids(
|
|
|
|
key_dir: Path,
|
2021-10-19 10:35:59 -05:00
|
|
|
uids: Dict[Uid, Path],
|
2021-10-09 16:42:13 -05:00
|
|
|
) -> None:
|
|
|
|
"""Persist the User IDs that belong to a PublicKey
|
|
|
|
|
2021-10-23 15:08:04 -05:00
|
|
|
The User ID material consists of a single User ID Packet.
|
2021-10-12 16:57:20 -05:00
|
|
|
The files are written to a UID specific directory and file below key_dir/uid.
|
2021-10-09 16:42:13 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
key_dir: The root directory below which the basic key material is persisted
|
|
|
|
uids: The User IDs of a Public-Key (the root key)
|
2021-10-09 16:42:13 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-23 15:08:04 -05:00
|
|
|
for uid, uid_packet in uids.items():
|
|
|
|
output_file = key_dir / "uid" / uid / f"{uid}.asc"
|
2021-10-12 17:09:58 -05:00
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
2021-10-23 15:08:04 -05:00
|
|
|
debug(f"Writing file {output_file} from {uid_packet}")
|
|
|
|
packet_join(packets=[uid_packet], output=output_file, force=True)
|
2021-10-09 16:42:13 -05:00
|
|
|
|
|
|
|
|
2021-10-09 05:56:33 -05:00
|
|
|
def persist_subkeys(
|
|
|
|
key_dir: Path,
|
2021-10-19 11:26:50 -05:00
|
|
|
subkeys: Dict[Fingerprint, Path],
|
2021-10-09 05:56:33 -05:00
|
|
|
) -> None:
|
2021-10-23 15:08:04 -05:00
|
|
|
"""Persist all Public-Subkeys of a root key file to file(s)
|
2021-10-09 05:56:33 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
key_dir: The root directory below which the basic key material is persisted
|
|
|
|
subkeys: The PublicSubkeys of a key
|
2021-10-09 05:56:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-19 11:26:50 -05:00
|
|
|
for fingerprint, subkey in subkeys.items():
|
|
|
|
output_file = key_dir / "subkey" / fingerprint / f"{fingerprint}.asc"
|
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
2021-10-23 15:08:04 -05:00
|
|
|
debug(f"Writing file {output_file} from {str(subkey)}")
|
|
|
|
packet_join(packets=[subkey], output=output_file, force=True)
|
|
|
|
|
|
|
|
|
|
|
|
def persist_subkey_bindings(
|
|
|
|
key_dir: Path,
|
2021-10-23 19:16:25 -05:00
|
|
|
subkey_bindings: Dict[Fingerprint, List[Path]],
|
2021-10-23 15:08:04 -05:00
|
|
|
) -> None:
|
|
|
|
"""Persist all SubkeyBinding of a root key file to file(s)
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
key_dir: The root directory below which the basic key material is persisted
|
|
|
|
subkey_bindings: The SubkeyBinding signatures of a Public-Subkey
|
|
|
|
"""
|
|
|
|
|
2021-10-23 19:16:25 -05:00
|
|
|
for fingerprint, bindings in subkey_bindings.items():
|
|
|
|
subkey_binding = latest_certification(bindings)
|
2021-10-23 15:08:04 -05:00
|
|
|
issuer = packet_dump_field(subkey_binding, "Issuer")
|
|
|
|
output_file = key_dir / "subkey" / fingerprint / "certification" / f"{issuer}.asc"
|
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
debug(f"Writing file {output_file} from {str(subkey_binding)}")
|
|
|
|
packet_join(packets=[subkey_binding], output=output_file, force=True)
|
2021-10-09 05:56:33 -05:00
|
|
|
|
|
|
|
|
|
|
|
def persist_subkey_revocations(
|
|
|
|
key_dir: Path,
|
2021-10-23 19:16:25 -05:00
|
|
|
subkey_revocations: Dict[Fingerprint, List[Path]],
|
2021-10-09 05:56:33 -05:00
|
|
|
) -> None:
|
|
|
|
"""Persist the SubkeyRevocations of all Public-Subkeys of a root key to file(s)
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
key_dir: The root directory below which the basic key material is persisted
|
|
|
|
subkey_revocations: The SubkeyRevocations of PublicSubkeys of a key
|
2021-10-09 05:56:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-23 19:16:25 -05:00
|
|
|
for fingerprint, revocations in subkey_revocations.items():
|
|
|
|
revocation = latest_certification(revocations)
|
2021-10-19 11:26:50 -05:00
|
|
|
issuer = packet_dump_field(revocation, "Issuer")
|
|
|
|
output_file = key_dir / "subkey" / fingerprint / "revocation" / f"{issuer}.asc"
|
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
debug(f"Writing file {output_file} from {revocation}")
|
2021-10-21 16:49:40 -05:00
|
|
|
packet_join(packets=[revocation], output=output_file, force=True)
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
def persist_direct_key_certifications(
|
|
|
|
direct_key_certifications: Dict[Fingerprint, List[Path]],
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir: Path,
|
2021-10-03 08:06:33 -05:00
|
|
|
) -> None:
|
2021-10-03 12:24:49 -05:00
|
|
|
"""Persist the signatures directly on a root key (such as DirectKeys or *Certifications without a User ID) to
|
|
|
|
file(s)
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-23 08:49:11 -05:00
|
|
|
direct_key_certifications: The direct key certifications to write to file
|
2021-10-22 15:08:11 -05:00
|
|
|
key_dir: The root directory below which the Directkeys are persisted
|
2021-10-03 08:06:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
for issuer, certifications in direct_key_certifications.items():
|
|
|
|
output_file = key_dir / "certification" / f"{issuer}.asc"
|
2021-10-19 11:26:50 -05:00
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
debug(f"Writing file {output_file} from {[str(cert) for cert in certifications]}")
|
2021-10-23 08:49:11 -05:00
|
|
|
packet_join(packets=certifications, output=output_file, force=True)
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
def persist_direct_key_revocations(
|
|
|
|
direct_key_revocations: Dict[Fingerprint, List[Path]],
|
|
|
|
key_dir: Path,
|
|
|
|
) -> None:
|
|
|
|
"""Persist the revocations directly on a root key (such as KeyRevocation) to file(s)
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
direct_key_revocations: The direct key revocations to write to file
|
|
|
|
key_dir: The root directory below which the Directkeys are persisted
|
|
|
|
"""
|
|
|
|
|
|
|
|
for issuer, certifications in direct_key_revocations.items():
|
|
|
|
output_file = key_dir / "revocation" / f"{issuer}.asc"
|
|
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
debug(f"Writing file {output_file} from {[str(cert) for cert in certifications]}")
|
|
|
|
packet_join(packets=certifications, output=output_file, force=True)
|
|
|
|
|
|
|
|
|
|
|
|
def persist_uid_certifications(
|
2021-10-23 19:16:25 -05:00
|
|
|
certifications: Dict[Uid, Dict[Fingerprint, List[Path]]],
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir: Path,
|
2021-10-03 08:06:33 -05:00
|
|
|
) -> None:
|
|
|
|
"""Persist the certifications of a root key to file(s)
|
|
|
|
|
|
|
|
The certifications include all CasualCertifications, GenericCertifications, PersonaCertifications and
|
|
|
|
PositiveCertifications for all User IDs of the given root key.
|
2021-10-03 14:41:09 -05:00
|
|
|
All certifications are persisted in per User ID certification directories below key_dir.
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
certifications: The certifications to write to file
|
|
|
|
key_dir: The root directory below which certifications are persisted
|
2021-10-03 08:06:33 -05:00
|
|
|
"""
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-23 19:16:25 -05:00
|
|
|
for uid, uid_certifications in certifications.items():
|
|
|
|
for issuer, issuer_certifications in uid_certifications.items():
|
|
|
|
certification_dir = key_dir / "uid" / uid / "certification"
|
2021-08-25 11:53:07 -05:00
|
|
|
certification_dir.mkdir(parents=True, exist_ok=True)
|
2021-10-23 19:16:25 -05:00
|
|
|
certification = latest_certification(issuer_certifications)
|
2021-10-23 08:49:11 -05:00
|
|
|
output_file = certification_dir / f"{issuer}.asc"
|
|
|
|
debug(f"Writing file {output_file} from {certification}")
|
|
|
|
packet_join(packets=[certification], output=output_file, force=True)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-03 08:06:33 -05:00
|
|
|
|
2021-10-23 08:49:11 -05:00
|
|
|
def persist_uid_revocations(
|
2021-10-23 19:16:25 -05:00
|
|
|
revocations: Dict[Uid, Dict[Fingerprint, List[Path]]],
|
2021-10-03 14:41:09 -05:00
|
|
|
key_dir: Path,
|
2021-10-03 08:06:33 -05:00
|
|
|
) -> None:
|
|
|
|
"""Persist the revocations of a root key to file(s)
|
|
|
|
|
|
|
|
The revocations include all CertificationRevocations for all User IDs of the given root key.
|
2021-10-03 14:41:09 -05:00
|
|
|
All revocations are persisted in per User ID 'revocation' directories below key_dir.
|
2021-10-03 08:06:33 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
revocations: The revocations to write to file
|
|
|
|
key_dir: The root directory below which revocations will be persisted
|
2021-10-03 08:06:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-23 19:16:25 -05:00
|
|
|
for uid, uid_revocations in revocations.items():
|
|
|
|
for issuer, issuer_revocations in uid_revocations.items():
|
|
|
|
revocation_dir = key_dir / "uid" / uid / "revocation"
|
2021-08-25 11:53:07 -05:00
|
|
|
revocation_dir.mkdir(parents=True, exist_ok=True)
|
2021-10-23 19:16:25 -05:00
|
|
|
revocation = latest_certification(issuer_revocations)
|
2021-10-16 17:50:34 -05:00
|
|
|
output_file = revocation_dir / f"{issuer}.asc"
|
|
|
|
debug(f"Writing file {output_file} from {revocation}")
|
2021-10-23 08:49:11 -05:00
|
|
|
packet_join(packets=[revocation], output=output_file, force=True)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
|
|
|
|
def packet_dump(packet: Path) -> str:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Dump a PGP packet to string
|
|
|
|
|
|
|
|
The `sq packet dump` command is used to retrieve a dump of information from a PGP packet
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
packet: The path to the PGP packet to retrieve the value from
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The contents of the packet dump
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
return system(["sq", "packet", "dump", str(packet)])
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
|
|
|
|
def packet_dump_field(packet: Path, field: str) -> str:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Retrieve the value of a field from a PGP packet
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
packet: The path to the PGP packet to retrieve the value from
|
|
|
|
field: The name of the field
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
2021-10-22 15:08:11 -05:00
|
|
|
Exception: If the field is not found in the PGP packet
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The value of the field found in packet
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
dump = packet_dump(packet)
|
|
|
|
lines = [line.strip() for line in dump.splitlines()]
|
2021-10-23 19:16:25 -05:00
|
|
|
lines = list(filter(lambda line: line.strip().startswith(f"{field}: "), lines))
|
2021-08-25 11:53:07 -05:00
|
|
|
if not lines:
|
|
|
|
raise Exception(f'Packet has no field "{field}"')
|
2021-10-23 19:16:25 -05:00
|
|
|
return lines[0].split(sep=": ", maxsplit=1)[1]
|
|
|
|
|
|
|
|
|
|
|
|
def packet_signature_creation_time(packet: Path) -> datetime:
|
|
|
|
"""Retrieve the signature creation time field as datetime
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
packet: The path to the PGP packet to retrieve the value from
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
The signature creation time as datetime
|
|
|
|
"""
|
|
|
|
return datetime.strptime(packet_dump_field(packet, "Signature creation time"), "%Y-%m-%d %H:%M:%S %Z")
|
|
|
|
|
|
|
|
|
|
|
|
def latest_certification(certifications: Iterable[Path]) -> Path:
|
|
|
|
"""Returns the latest certification based on the signature creation time from a list of packets.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
certifications: List of certification from which to choose the latest from
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
The latest certification from a list of packets
|
|
|
|
"""
|
|
|
|
return reduce(
|
|
|
|
lambda a, b: a if packet_signature_creation_time(a) > packet_signature_creation_time(b) else b,
|
|
|
|
certifications,
|
|
|
|
)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
|
2021-10-21 17:58:52 -05:00
|
|
|
def keyring_split(working_dir: Path, keyring: Path, preserve_filename: bool = False) -> Iterable[Path]:
|
2021-10-12 12:20:33 -05:00
|
|
|
"""Split a file containing a PGP keyring into separate certificate files
|
2021-10-04 15:12:33 -05:00
|
|
|
|
2021-10-19 19:16:10 -05:00
|
|
|
The original keyring filename is preserved if the split only yields a single certificate.
|
2021-10-21 17:58:52 -05:00
|
|
|
If preserve_filename is True, all keyrings are placed into separate directories while preserving
|
|
|
|
the filename.
|
|
|
|
|
2021-10-19 19:16:10 -05:00
|
|
|
The file is split using sq.
|
2021-10-11 06:00:48 -05:00
|
|
|
|
2021-10-04 15:12:33 -05:00
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: The path of the working directory below which to create the output files
|
|
|
|
keyring: The path of a file containing a PGP keyring
|
|
|
|
preserve_filename: If True, all keyrings are placed into separate directories while preserving the filename
|
2021-10-04 15:12:33 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
An iterable over the naturally sorted list of certificate files derived from a keyring
|
2021-10-04 15:12:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
keyring_dir = Path(mkdtemp(dir=working_dir, prefix="keyring-")).absolute()
|
2021-10-12 12:20:33 -05:00
|
|
|
|
|
|
|
with cwd(keyring_dir):
|
2021-10-16 17:50:34 -05:00
|
|
|
system(["sq", "keyring", "split", "--prefix", "", str(keyring)])
|
2021-10-19 19:16:10 -05:00
|
|
|
|
|
|
|
keyrings: List[Path] = list(natural_sort_path(keyring_dir.iterdir()))
|
|
|
|
|
2021-10-21 17:58:52 -05:00
|
|
|
if 1 == len(keyrings) or preserve_filename:
|
|
|
|
for index, key in enumerate(keyrings):
|
|
|
|
keyring_sub_dir = Path(mkdtemp(dir=keyring_dir, prefix=f"{keyring.name}-")).absolute()
|
|
|
|
keyrings[index] = key.rename(keyring_sub_dir / keyring.name)
|
2021-10-19 19:16:10 -05:00
|
|
|
|
|
|
|
return keyrings
|
2021-10-04 15:12:33 -05:00
|
|
|
|
|
|
|
|
2021-10-21 14:03:02 -05:00
|
|
|
def keyring_merge(certificates: List[Path], output: Optional[Path] = None, force: bool = False) -> str:
|
2021-10-21 13:34:07 -05:00
|
|
|
"""Merge multiple certificates into a keyring
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
certificates: List of paths to certificates to merge into a keyring
|
|
|
|
output: Path to a file which the keyring is written, return the result instead if None
|
|
|
|
force: Whether to force overwriting existing files (defaults to False)
|
2021-10-21 13:34:07 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The result if no output file has been used
|
2021-10-21 13:34:07 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
cmd = ["sq", "keyring", "merge"]
|
2021-10-21 14:03:02 -05:00
|
|
|
if force:
|
|
|
|
cmd.insert(1, "--force")
|
2021-10-21 13:34:07 -05:00
|
|
|
if output:
|
|
|
|
cmd += ["--output", str(output)]
|
|
|
|
cmd += [str(cert) for cert in sorted(certificates)]
|
|
|
|
|
2021-10-21 14:05:03 -05:00
|
|
|
return system(cmd)
|
2021-10-21 13:34:07 -05:00
|
|
|
|
|
|
|
|
2021-10-04 15:12:33 -05:00
|
|
|
def packet_split(working_dir: Path, certificate: Path) -> Iterable[Path]:
|
|
|
|
"""Split a file containing a PGP certificate into separate packet files
|
|
|
|
|
|
|
|
The files are split using sq
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: The path of the working directory below which to create the output files
|
|
|
|
certificate: The absolute path of a file containing one PGP certificate
|
2021-10-04 15:12:33 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
An iterable over the naturally sorted list of packet files derived from certificate
|
2021-10-04 15:12:33 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
packet_dir = Path(mkdtemp(dir=working_dir, prefix="packet-")).absolute()
|
2021-10-04 15:12:33 -05:00
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
with cwd(packet_dir):
|
2021-10-16 17:50:34 -05:00
|
|
|
system(["sq", "packet", "split", "--prefix", "", str(certificate)])
|
2021-08-25 11:53:07 -05:00
|
|
|
return natural_sort_path(packet_dir.iterdir())
|
|
|
|
|
|
|
|
|
2021-10-21 13:19:33 -05:00
|
|
|
def packet_join(packets: List[Path], output: Optional[Path] = None, force: bool = False) -> str:
|
2021-10-05 11:31:31 -05:00
|
|
|
"""Join PGP packet data in files to a single output file
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
packets: A list of paths to files that contain PGP packet data
|
|
|
|
output: Path to a file to which all PGP packet data is written, return the result instead if None
|
|
|
|
force: Whether to force overwriting existing files (defaults to False)
|
2021-10-21 13:19:33 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The result if no output file has been used
|
2021-10-05 11:31:31 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
cmd = ["sq", "packet", "join"]
|
2021-10-05 11:31:31 -05:00
|
|
|
if force:
|
2021-10-16 17:50:34 -05:00
|
|
|
cmd.insert(1, "--force")
|
2021-08-25 11:53:07 -05:00
|
|
|
packets_str = list(map(lambda path: str(path), packets))
|
|
|
|
cmd.extend(packets_str)
|
2021-10-16 17:50:34 -05:00
|
|
|
cmd.extend(["--output", str(output)])
|
2021-10-21 14:05:03 -05:00
|
|
|
return system(cmd)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
|
2021-10-22 13:21:27 -05:00
|
|
|
def inspect(
|
|
|
|
packet: Path, certifications: bool = True, fingerprints: Optional[Dict[Fingerprint, Username]] = None
|
|
|
|
) -> str:
|
2021-10-21 14:51:02 -05:00
|
|
|
"""Inspect PGP packet data and return the result
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
packet: Path to a file that contain PGP data
|
|
|
|
certifications: Whether to print third-party certifications
|
|
|
|
fingerprints: Optional dict of fingerprints to usernames to enrich the output with
|
2021-10-21 14:51:02 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The result of the inspection
|
2021-10-21 14:51:02 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
cmd = ["sq", "inspect"]
|
|
|
|
if certifications:
|
|
|
|
cmd.append("--certifications")
|
|
|
|
cmd.append(str(packet))
|
2021-10-22 13:21:27 -05:00
|
|
|
result: str = system(cmd)
|
|
|
|
|
|
|
|
if fingerprints:
|
|
|
|
for fingerprint, username in fingerprints.items():
|
|
|
|
result = sub(f"{fingerprint}", f"{fingerprint} {username}", result)
|
|
|
|
result = sub(f" {fingerprint[24:]}", f" {fingerprint[24:]} {username}", result)
|
|
|
|
|
|
|
|
return result
|
2021-10-21 14:51:02 -05:00
|
|
|
|
|
|
|
|
2021-10-19 10:35:59 -05:00
|
|
|
def simplify_user_id(user_id: Uid) -> Uid:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Simplify the User ID string to contain more filesystem friendly characters
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
user_id: A User ID string (e.g. 'Foobar McFooface <foobar@foo.face>')
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The simplified representation of user_id
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-19 10:35:59 -05:00
|
|
|
user_id_str: str = user_id.replace("@", "_at_")
|
|
|
|
user_id_str = sub("[<>]", "", user_id_str)
|
|
|
|
user_id_str = sub("[" + escape(r" !@#$%^&*()_-+=[]{}\|;:,.<>/?") + "]", "_", user_id_str)
|
|
|
|
return Uid(user_id_str)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
|
2021-10-19 14:03:53 -05:00
|
|
|
def derive_username_from_fingerprint(keyring_dir: Path, certificate_fingerprint: Fingerprint) -> Optional[Username]:
|
2021-10-19 12:10:51 -05:00
|
|
|
"""Attempt to derive the username of a public key fingerprint from a keyring directory
|
2021-10-17 05:58:19 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
keyring_dir: The directory in which to look up a username
|
|
|
|
certificate_fingerprint: The public key fingerprint to derive the username from
|
2021-10-17 05:58:19 -05:00
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
2021-10-22 15:08:11 -05:00
|
|
|
Exception: If more than one username is found (a public key can only belong to one individual)
|
2021-10-17 05:58:19 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
A string representing the username a public key certificate belongs to, None otherwise
|
2021-10-17 05:58:19 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-19 12:12:48 -05:00
|
|
|
matches = list(keyring_dir.glob(f"*/*{certificate_fingerprint}"))
|
2021-10-17 05:58:19 -05:00
|
|
|
|
|
|
|
if len(matches) > 1:
|
|
|
|
raise Exception(
|
2021-10-19 14:11:37 -05:00
|
|
|
f"More than one username found in {keyring_dir} when probing for fingerprint '{certificate_fingerprint}': "
|
|
|
|
f"{matches}"
|
2021-10-17 05:58:19 -05:00
|
|
|
)
|
2021-10-19 12:10:51 -05:00
|
|
|
elif not matches:
|
|
|
|
debug(f"Can not derive username from target directory for fingerprint {certificate_fingerprint}")
|
2021-10-17 05:58:19 -05:00
|
|
|
return None
|
|
|
|
else:
|
|
|
|
username = matches[0].parent.stem
|
2021-10-19 14:11:37 -05:00
|
|
|
debug(
|
|
|
|
f"Successfully derived username '{username}' from target directory for fingerprint "
|
|
|
|
f"{certificate_fingerprint}"
|
|
|
|
)
|
2021-10-19 14:03:53 -05:00
|
|
|
return Username(username)
|
2021-10-17 05:58:19 -05:00
|
|
|
|
|
|
|
|
2021-10-03 14:41:09 -05:00
|
|
|
def convert(
|
|
|
|
working_dir: Path,
|
2021-10-22 14:34:53 -05:00
|
|
|
keyring_root: Path,
|
2021-10-20 13:15:42 -05:00
|
|
|
source: Iterable[Path],
|
2021-10-04 12:25:24 -05:00
|
|
|
target_dir: Path,
|
2021-10-19 14:03:53 -05:00
|
|
|
name_override: Optional[Username] = None,
|
2021-10-03 14:41:09 -05:00
|
|
|
) -> Path:
|
2021-10-12 12:20:33 -05:00
|
|
|
"""Convert a path containing PGP certificate material to a decomposed directory structure
|
2021-10-11 06:00:48 -05:00
|
|
|
|
2021-10-12 12:20:33 -05:00
|
|
|
Any input is first split by `keyring_split()` into individual certificates.
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: A directory to use for temporary files
|
|
|
|
keyring_root: The keyring root directory to look up accepted fingerprints for certifications
|
|
|
|
source: A path to a file or directory to decompose
|
|
|
|
target_dir: A directory path to write the new directory structure to
|
|
|
|
name_override: An optional username override for the call to `convert_certificate()`
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The directory that contains the resulting directory structure (target_dir)
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
directories: List[Path] = []
|
2021-10-20 13:15:42 -05:00
|
|
|
keys: Iterable[Path] = set(chain.from_iterable(map(lambda s: s.iterdir() if s.is_dir() else [s], source)))
|
2021-10-12 12:42:22 -05:00
|
|
|
|
2021-10-22 14:34:53 -05:00
|
|
|
fingerprint_filter = set(
|
|
|
|
get_fingerprints(
|
|
|
|
working_dir=working_dir,
|
|
|
|
sources=source,
|
|
|
|
paths=[keyring_root],
|
|
|
|
).keys()
|
|
|
|
)
|
|
|
|
|
2021-10-12 12:42:22 -05:00
|
|
|
for key in keys:
|
2021-10-21 17:58:52 -05:00
|
|
|
for cert in keyring_split(working_dir=working_dir, keyring=key, preserve_filename=True):
|
2021-10-18 05:47:12 -05:00
|
|
|
directories.append(
|
|
|
|
convert_certificate(
|
|
|
|
working_dir=working_dir,
|
|
|
|
certificate=cert,
|
2021-10-19 12:10:51 -05:00
|
|
|
keyring_dir=target_dir,
|
|
|
|
name_override=name_override,
|
2021-10-18 05:47:12 -05:00
|
|
|
fingerprint_filter=fingerprint_filter,
|
|
|
|
)
|
|
|
|
)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
for path in directories:
|
2021-10-16 17:12:57 -05:00
|
|
|
(target_dir / path.name).mkdir(parents=True, exist_ok=True)
|
2021-10-04 12:25:24 -05:00
|
|
|
copytree(src=path, dst=(target_dir / path.name), dirs_exist_ok=True)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
|
|
|
return target_dir
|
|
|
|
|
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
def get_trusted_and_revoked_certs(certs: List[Path]) -> Tuple[List[Fingerprint], List[Fingerprint]]:
|
|
|
|
"""Get the fingerprints of all trusted and all self revoked public keys in a directory
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
certs: The certificates to trust
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
A tuple with the first item containing the fingerprints of all public keys and the second item containing the
|
|
|
|
fingerprints of all self-revoked public keys
|
2021-10-10 11:28:30 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
all_certs: List[Fingerprint] = []
|
|
|
|
revoked_certs: List[Fingerprint] = []
|
2021-10-19 10:35:59 -05:00
|
|
|
|
|
|
|
# TODO: what about direct key revocations/signatures?
|
2021-10-10 11:28:30 -05:00
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
debug(f"Retrieving trusted and self-revoked certificates from {[str(cert_dir) for cert_dir in certs]}")
|
2021-10-10 11:28:30 -05:00
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
for cert_dir in sorted(get_cert_paths(certs)):
|
|
|
|
cert_fingerprint = Fingerprint(cert_dir.stem)
|
|
|
|
all_certs.append(cert_fingerprint)
|
|
|
|
for revocation_cert in cert_dir.glob("revocation/*.asc"):
|
|
|
|
if cert_fingerprint.endswith(revocation_cert.stem):
|
|
|
|
debug(f"Revoking {cert_fingerprint} due to self-revocation")
|
|
|
|
revoked_certs.append(cert_fingerprint)
|
|
|
|
|
|
|
|
trusted_keys = [cert for cert in all_certs if cert not in revoked_certs]
|
|
|
|
|
|
|
|
return trusted_keys, revoked_certs
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
|
2021-10-19 10:35:59 -05:00
|
|
|
def export_ownertrust(certs: List[Path], output: Path) -> Tuple[List[Fingerprint], List[Fingerprint]]:
|
2021-10-22 14:13:52 -05:00
|
|
|
"""Export ownertrust from a set of keys and return the trusted and revoked fingerprints
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
The output file format is compatible with `gpg --import-ownertrust` and lists the main fingerprint ID of all
|
|
|
|
non-revoked keys as fully trusted.
|
|
|
|
The exported file is used by pacman-key when importing a keyring (see
|
|
|
|
https://man.archlinux.org/man/pacman-key.8#PROVIDING_A_KEYRING_FOR_IMPORT).
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
certs: The certificates to trust
|
|
|
|
output: The file path to write to
|
2021-10-10 11:28:30 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
trusted_certs, revoked_certs = get_trusted_and_revoked_certs(certs=certs)
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
with open(file=output, mode="w") as trusted_certs_file:
|
2021-10-22 14:13:52 -05:00
|
|
|
for cert in sorted(set(trusted_certs)):
|
2021-10-10 11:28:30 -05:00
|
|
|
debug(f"Writing {cert} to {output}")
|
|
|
|
trusted_certs_file.write(f"{cert}:4:\n")
|
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
return trusted_certs, revoked_certs
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
|
2021-10-19 10:35:59 -05:00
|
|
|
def export_revoked(certs: List[Path], main_keys: List[Fingerprint], output: Path, min_revoker: int = 2) -> None:
|
2021-10-10 11:28:30 -05:00
|
|
|
"""Export the PGP revoked status from a set of keys
|
|
|
|
|
|
|
|
The output file contains the fingerprints of all self-revoked keys and all keys for which at least two revocations
|
|
|
|
by any main key exist.
|
|
|
|
The exported file is used by pacman-key when importing a keyring (see
|
|
|
|
https://man.archlinux.org/man/pacman-key.8#PROVIDING_A_KEYRING_FOR_IMPORT).
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
certs: A list of directories with keys to check for their revocation status
|
|
|
|
main_keys: A list of strings representing the fingerprints of (current and/or revoked) main keys
|
|
|
|
output: The file path to write to
|
|
|
|
min_revoker: The minimum amount of revocation certificates on a User ID from any main key to deem a public key as
|
|
|
|
revoked
|
2021-10-10 11:28:30 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
trusted_certs, revoked_certs = get_trusted_and_revoked_certs(certs=certs)
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
debug(f"Retrieving certificates revoked by main keys from {[str(cert_dir) for cert_dir in certs]}")
|
2021-10-22 14:13:52 -05:00
|
|
|
foreign_revocations: Dict[Fingerprint, Set[Fingerprint]] = defaultdict(set)
|
|
|
|
for cert_dir in sorted(get_cert_paths(certs)):
|
|
|
|
fingerprint = Fingerprint(cert_dir.name)
|
|
|
|
debug(f"Inspecting public key {fingerprint}")
|
|
|
|
for revocation_cert in cert_dir.glob("uid/*/revocation/*.asc"):
|
|
|
|
revocation_fingerprint = Fingerprint(revocation_cert.stem)
|
|
|
|
foreign_revocations[fingerprint].update(
|
|
|
|
[revocation_fingerprint for main_key in main_keys if main_key.endswith(revocation_fingerprint)]
|
|
|
|
)
|
|
|
|
|
|
|
|
# TODO: find a better (less naive) approach, as this would also match on public certificates,
|
|
|
|
# where some UIDs are signed and others are revoked
|
|
|
|
if len(foreign_revocations[fingerprint]) >= min_revoker:
|
|
|
|
debug(
|
2021-10-22 14:34:53 -05:00
|
|
|
f"Revoking {cert_dir.name} due to {set(foreign_revocations[fingerprint])} " "being main key revocations"
|
2021-10-22 14:13:52 -05:00
|
|
|
)
|
|
|
|
revoked_certs.append(fingerprint)
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
with open(file=output, mode="w") as trusted_certs_file:
|
2021-10-22 14:13:52 -05:00
|
|
|
for cert in sorted(set(revoked_certs)):
|
2021-10-10 11:28:30 -05:00
|
|
|
debug(f"Writing {cert} to {output}")
|
|
|
|
trusted_certs_file.write(f"{cert}\n")
|
|
|
|
|
|
|
|
|
2021-10-22 14:34:53 -05:00
|
|
|
def get_fingerprints_from_keyring_files(working_dir: Path, source: Iterable[Path]) -> Dict[Fingerprint, Username]:
|
2021-10-18 05:47:12 -05:00
|
|
|
"""Get all fingerprints of PGP public keys from import file(s)
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: A directory to use for temporary files
|
|
|
|
source: The path to a source file or directory containing keyrings
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
A dict of all fingerprints and their usernames of PGP public keys below path
|
2021-10-18 05:47:12 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-22 13:21:27 -05:00
|
|
|
fingerprints: Dict[Fingerprint, Username] = {}
|
2021-10-20 13:15:42 -05:00
|
|
|
keys: Iterable[Path] = set(chain.from_iterable(map(lambda s: s.iterdir() if s.is_dir() else [s], source)))
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
for key in keys:
|
2021-10-22 13:21:27 -05:00
|
|
|
for certificate in keyring_split(working_dir=working_dir, keyring=key, preserve_filename=True):
|
2021-10-18 05:47:12 -05:00
|
|
|
for packet in packet_split(working_dir=working_dir, certificate=certificate):
|
|
|
|
if packet.name.endswith("--PublicKey"):
|
2021-10-22 13:21:27 -05:00
|
|
|
fingerprints[Fingerprint(packet_dump_field(packet, "Fingerprint"))] = Username(certificate.stem)
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
debug(f"Fingerprints of PGP public keys in {source}: {fingerprints}")
|
|
|
|
return fingerprints
|
|
|
|
|
|
|
|
|
2021-10-23 10:35:42 -05:00
|
|
|
def get_fingerprints_from_certificate_directory(
|
|
|
|
paths: List[Path], prefix: str = "", postfix: str = ""
|
|
|
|
) -> Dict[Fingerprint, Username]:
|
2021-10-22 14:34:53 -05:00
|
|
|
"""Get all fingerprints of PGP public keys from decomposed directory structures
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
paths: The path to a decomposed directory structure
|
2021-10-23 10:35:42 -05:00
|
|
|
prefix: Prefix to add to each username
|
|
|
|
postfix: Postfix to add to each username
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
A dict of all fingerprints and their usernames of PGP public keys below path
|
2021-10-18 05:47:12 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-22 13:21:27 -05:00
|
|
|
fingerprints: Dict[Fingerprint, Username] = {}
|
2021-10-22 14:34:53 -05:00
|
|
|
for cert in sorted(get_cert_paths(paths)):
|
2021-10-23 10:35:42 -05:00
|
|
|
fingerprints[Fingerprint(cert.name)] = Username(f"{prefix}{cert.parent.name}{postfix}")
|
2021-10-22 13:21:27 -05:00
|
|
|
|
2021-10-22 14:34:53 -05:00
|
|
|
debug(f"Fingerprints of PGP public keys in {paths}: {fingerprints}")
|
2021-10-18 05:47:12 -05:00
|
|
|
return fingerprints
|
|
|
|
|
|
|
|
|
2021-10-22 14:34:53 -05:00
|
|
|
def get_fingerprints(working_dir: Path, sources: Iterable[Path], paths: List[Path]) -> Dict[Fingerprint, Username]:
|
2021-10-18 05:47:12 -05:00
|
|
|
"""Get the fingerprints of PGP public keys from input paths and decomposed directory structures
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: A directory to use for temporary files
|
|
|
|
sources: A list of directories or files from which to read PGP keyring information
|
|
|
|
paths: A list of paths that identify decomposed PGP data in directory structures
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
A dict of all fingerprints and their usernames of PGP public keys below path
|
2021-10-18 05:47:12 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-22 13:21:27 -05:00
|
|
|
fingerprints: Dict[Fingerprint, Username] = {}
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
fingerprints.update(
|
2021-10-22 14:34:53 -05:00
|
|
|
get_fingerprints_from_keyring_files(
|
2021-10-18 05:47:12 -05:00
|
|
|
working_dir=working_dir,
|
2021-10-22 14:34:53 -05:00
|
|
|
source=sources,
|
2021-10-18 05:47:12 -05:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2021-10-22 14:34:53 -05:00
|
|
|
fingerprints.update(get_fingerprints_from_certificate_directory(paths=paths))
|
2021-10-18 05:47:12 -05:00
|
|
|
|
|
|
|
return fingerprints
|
|
|
|
|
|
|
|
|
2021-10-23 15:08:04 -05:00
|
|
|
def get_packets_from_path(path: Path) -> List[Path]:
|
|
|
|
"""Collects packets from one level by appending the root, certifications and revocations.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
path: Filesystem path used to collect the packets from
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
A list of packets ordered by root, certification, revocation
|
|
|
|
"""
|
|
|
|
if not path.exists():
|
|
|
|
return []
|
|
|
|
|
|
|
|
packets: List[Path] = []
|
|
|
|
packets += sorted(path.glob("*.asc"))
|
|
|
|
certifications = path / "certification"
|
|
|
|
if certifications.exists():
|
|
|
|
packets += sorted(certifications.glob("*.asc"))
|
|
|
|
revocations = path / "revocation"
|
|
|
|
if revocations.exists():
|
|
|
|
packets += sorted(revocations.glob("*.asc"))
|
|
|
|
return packets
|
|
|
|
|
|
|
|
|
|
|
|
def get_packets_from_listing(path: Path) -> List[Path]:
|
|
|
|
"""Collects packets from a listing of directories holding one level each by calling `get_get_packets_from_path`.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
path: Filesystem path used as listing to collect the packets from
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
A list of packets ordered by root, certification, revocation for each level
|
|
|
|
"""
|
|
|
|
if not path.exists():
|
|
|
|
return []
|
|
|
|
|
|
|
|
packets: List[Path] = []
|
|
|
|
for sub_path in sorted(path.iterdir()):
|
|
|
|
packets += get_packets_from_path(sub_path)
|
|
|
|
return packets
|
|
|
|
|
|
|
|
|
2021-10-21 13:34:48 -05:00
|
|
|
def export(
|
|
|
|
working_dir: Path,
|
|
|
|
keyring_root: Path,
|
|
|
|
sources: Optional[List[Path]] = None,
|
|
|
|
output: Optional[Path] = None,
|
|
|
|
) -> str:
|
|
|
|
"""Export all provided PGP packet files to a single output file
|
|
|
|
|
|
|
|
If sources contains directories, any .asc files below them are considered.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: A directory to use for temporary files
|
|
|
|
keyring_root: The keyring root directory to look up username shorthand sources
|
2021-10-22 20:01:06 -05:00
|
|
|
sources: A list of username, fingerprint or directories from which to read PGP packet information
|
|
|
|
(defaults to `keyring_root`)
|
2021-10-22 15:08:11 -05:00
|
|
|
output: An output file that all PGP packet data is written to, return the result instead if None
|
2021-10-21 13:34:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The result if no output file has been used
|
2021-10-21 13:34:48 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
if not sources:
|
|
|
|
sources = [keyring_root]
|
|
|
|
|
2021-10-23 10:13:46 -05:00
|
|
|
# transform shorthand paths to actual keyring paths
|
|
|
|
transform_username_to_keyring_path(keyring_dir=keyring_root / "packager", paths=sources)
|
|
|
|
transform_fingerprint_to_keyring_path(keyring_root=keyring_root, paths=sources)
|
2021-10-21 13:34:48 -05:00
|
|
|
|
|
|
|
temp_dir = Path(mkdtemp(dir=working_dir, prefix="arch-keyringctl-export-join-")).absolute()
|
2021-10-22 13:17:50 -05:00
|
|
|
cert_paths: Set[Path] = get_cert_paths(sources)
|
|
|
|
certificates: List[Path] = []
|
2021-10-21 13:34:48 -05:00
|
|
|
|
2021-10-22 13:17:50 -05:00
|
|
|
for cert_dir in sorted(cert_paths):
|
2021-10-23 15:08:04 -05:00
|
|
|
packets: List[Path] = []
|
|
|
|
packets += get_packets_from_path(cert_dir)
|
|
|
|
packets += get_packets_from_listing(cert_dir / "subkey")
|
|
|
|
packets += get_packets_from_listing(cert_dir / "uid")
|
|
|
|
|
|
|
|
output_path = temp_dir / f"{cert_dir.name}.asc"
|
|
|
|
debug(f"Joining {cert_dir} in {output_path}")
|
2021-10-21 13:34:48 -05:00
|
|
|
packet_join(
|
2021-10-23 15:08:04 -05:00
|
|
|
packets=packets,
|
|
|
|
output=output_path,
|
2021-10-21 13:34:48 -05:00
|
|
|
force=True,
|
|
|
|
)
|
2021-10-23 15:08:04 -05:00
|
|
|
certificates.append(output_path)
|
2021-10-21 13:34:48 -05:00
|
|
|
|
2021-10-21 14:04:16 -05:00
|
|
|
return keyring_merge(certificates, output, force=True)
|
2021-10-21 13:34:48 -05:00
|
|
|
|
|
|
|
|
2021-10-21 14:04:16 -05:00
|
|
|
def build(
|
2021-10-10 11:28:30 -05:00
|
|
|
working_dir: Path,
|
2021-10-21 14:04:16 -05:00
|
|
|
keyring_root: Path,
|
|
|
|
target_dir: Path,
|
2021-10-10 11:28:30 -05:00
|
|
|
) -> None:
|
2021-10-21 14:04:16 -05:00
|
|
|
"""Build keyring PGP artifacts alongside ownertrust and revoked status files
|
2021-10-10 11:28:30 -05:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: A directory to use for temporary files
|
|
|
|
keyring_root: The keyring root directory to build the artifacts from
|
|
|
|
target_dir: Output directory that all artifacts are written to
|
2021-10-10 11:28:30 -05:00
|
|
|
"""
|
|
|
|
|
2021-10-21 14:04:16 -05:00
|
|
|
target_dir.mkdir(parents=True, exist_ok=True)
|
2021-10-10 11:28:30 -05:00
|
|
|
|
2021-10-21 14:04:16 -05:00
|
|
|
keyring: Path = target_dir / Path("archlinux.gpg")
|
|
|
|
export(working_dir=working_dir, keyring_root=keyring_root, output=keyring)
|
2021-10-10 11:28:30 -05:00
|
|
|
|
2021-10-22 14:13:52 -05:00
|
|
|
[trusted_main_keys, revoked_main_keys] = export_ownertrust(
|
2021-10-21 14:04:16 -05:00
|
|
|
certs=[keyring_root / "main"],
|
|
|
|
output=target_dir / "archlinux-trusted",
|
|
|
|
)
|
|
|
|
export_revoked(
|
2021-10-22 14:13:52 -05:00
|
|
|
certs=[keyring_root],
|
|
|
|
main_keys=trusted_main_keys + revoked_main_keys,
|
2021-10-21 14:04:16 -05:00
|
|
|
output=target_dir / "archlinux-revoked",
|
|
|
|
)
|
2021-10-10 11:28:30 -05:00
|
|
|
|
2021-10-05 11:31:31 -05:00
|
|
|
|
2021-10-21 14:13:35 -05:00
|
|
|
def list_keyring(keyring_root: Path, sources: Optional[List[Path]] = None, main_keys: bool = False) -> None:
|
|
|
|
"""List certificates in the keyring
|
|
|
|
|
|
|
|
If sources contains directories, all certificate below them are considered.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-23 10:13:46 -05:00
|
|
|
keyring_root: The keyring root directory to look up username shorthand sources
|
2021-10-22 20:01:06 -05:00
|
|
|
sources: A list of username, fingerprint or directories from which to read PGP packet information
|
2021-10-22 15:08:11 -05:00
|
|
|
(defaults to `keyring_root`)
|
|
|
|
main_keys: List main keys instead of packager keys (defaults to False)
|
2021-10-21 14:13:35 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
keyring_dir = keyring_root / ("main" if main_keys else "packager")
|
|
|
|
|
|
|
|
if not sources:
|
2021-10-23 09:07:34 -05:00
|
|
|
sources = list(sorted(keyring_dir.iterdir(), key=lambda path: path.name.casefold()))
|
2021-10-21 14:13:35 -05:00
|
|
|
|
2021-10-23 10:13:46 -05:00
|
|
|
# transform shorthand paths to actual keyring paths
|
|
|
|
transform_username_to_keyring_path(keyring_dir=keyring_dir, paths=sources)
|
|
|
|
transform_fingerprint_to_keyring_path(keyring_root=keyring_root, paths=sources)
|
2021-10-21 14:13:35 -05:00
|
|
|
|
|
|
|
username_length = max([len(source.name) for source in sources])
|
|
|
|
|
2021-10-23 10:13:46 -05:00
|
|
|
for user_path in sources:
|
|
|
|
if is_pgp_fingerprint(user_path.name):
|
|
|
|
user_path = user_path.parent
|
|
|
|
certificates = [cert.name for cert in user_path.iterdir()]
|
|
|
|
print(f"{user_path.name:<{username_length}} {' '.join(certificates)}")
|
2021-10-21 14:13:35 -05:00
|
|
|
|
|
|
|
|
2021-10-21 14:51:02 -05:00
|
|
|
def inspect_keyring(working_dir: Path, keyring_root: Path, sources: Optional[List[Path]]) -> str:
|
|
|
|
"""Inspect certificates in the keyring and pretty print the data
|
|
|
|
|
|
|
|
If sources contains directories, all certificate below them are considered.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
working_dir: A directory to use for temporary files
|
|
|
|
keyring_root: The keyring root directory to look up username shorthand sources
|
2021-10-22 20:01:06 -05:00
|
|
|
sources: A list of username, fingerprint or directories from which to read PGP packet information
|
2021-10-22 15:08:11 -05:00
|
|
|
(defaults to `keyring_root`)
|
2021-10-21 14:51:02 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The result of the inspect
|
2021-10-21 14:51:02 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
if not sources:
|
|
|
|
sources = [keyring_root]
|
|
|
|
|
2021-10-23 10:13:46 -05:00
|
|
|
# transform shorthand paths to actual keyring paths
|
|
|
|
transform_username_to_keyring_path(keyring_dir=keyring_root / "packager", paths=sources)
|
|
|
|
transform_fingerprint_to_keyring_path(keyring_root=keyring_root, paths=sources)
|
2021-10-21 14:51:02 -05:00
|
|
|
|
|
|
|
keyring = Path(mkstemp(dir=working_dir, prefix="packet-", suffix=".asc")[1]).absolute()
|
|
|
|
export(working_dir=working_dir, keyring_root=keyring_root, sources=sources, output=keyring)
|
|
|
|
|
2021-10-23 10:35:42 -05:00
|
|
|
fingerprints: Dict[Fingerprint, Username] = get_fingerprints_from_certificate_directory(
|
|
|
|
paths=[keyring_root / "packager"]
|
|
|
|
) | get_fingerprints_from_certificate_directory(paths=[keyring_root / "main"], postfix=" (main)")
|
|
|
|
|
2021-10-22 13:21:27 -05:00
|
|
|
return inspect(
|
2021-10-22 15:08:11 -05:00
|
|
|
packet=keyring,
|
|
|
|
certifications=True,
|
2021-10-23 10:35:42 -05:00
|
|
|
fingerprints=fingerprints,
|
2021-10-22 13:21:27 -05:00
|
|
|
)
|
2021-10-21 14:51:02 -05:00
|
|
|
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
def absolute_path(path: str) -> Path:
|
2021-10-11 06:00:48 -05:00
|
|
|
"""Return the absolute path of a given str
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-10-22 15:08:11 -05:00
|
|
|
path: A string representing a path
|
2021-10-11 06:00:48 -05:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-10-22 15:08:11 -05:00
|
|
|
The absolute path representation of path
|
2021-10-11 06:00:48 -05:00
|
|
|
"""
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
return Path(path).absolute()
|
|
|
|
|
|
|
|
|
2021-10-16 17:50:34 -05:00
|
|
|
if __name__ == "__main__":
|
2021-08-25 11:53:07 -05:00
|
|
|
parser = ArgumentParser()
|
2021-10-05 11:31:31 -05:00
|
|
|
parser.add_argument(
|
2021-10-16 17:50:34 -05:00
|
|
|
"-v", "--verbose", action="store_true", help="Causes to print debugging messages about the progress"
|
|
|
|
)
|
|
|
|
parser.add_argument("--wait", action="store_true", help="Block before cleaning up the temp directory")
|
|
|
|
parser.add_argument(
|
|
|
|
"-f",
|
|
|
|
"--force",
|
|
|
|
action="store_true",
|
2021-10-05 11:31:31 -05:00
|
|
|
default=False,
|
2021-10-16 17:50:34 -05:00
|
|
|
help="force the execution of subcommands (e.g. overwriting of files)",
|
2021-10-05 11:31:31 -05:00
|
|
|
)
|
2021-08-25 11:53:07 -05:00
|
|
|
subcommands = parser.add_subparsers(dest="subcommand")
|
|
|
|
|
2021-10-03 08:06:33 -05:00
|
|
|
convert_parser = subcommands.add_parser(
|
2021-10-16 17:50:34 -05:00
|
|
|
"convert",
|
2021-10-20 13:02:08 -05:00
|
|
|
help="convert one or multiple PGP public keys to a decomposed directory structure",
|
2021-10-03 08:06:33 -05:00
|
|
|
)
|
2021-10-20 13:15:42 -05:00
|
|
|
convert_parser.add_argument("source", type=absolute_path, nargs="+", help="Files or directorie to convert")
|
2021-10-20 13:08:26 -05:00
|
|
|
convert_parser.add_argument("--target", type=absolute_path, help="Target directory instead of a random tmpdir")
|
2021-10-03 14:41:09 -05:00
|
|
|
convert_parser.add_argument(
|
2021-10-16 17:50:34 -05:00
|
|
|
"--name",
|
2021-10-19 14:03:53 -05:00
|
|
|
type=Username,
|
2021-10-03 14:41:09 -05:00
|
|
|
default=None,
|
2021-10-16 17:50:34 -05:00
|
|
|
help="override the username to use (only useful when using a single file as source)",
|
2021-10-03 14:41:09 -05:00
|
|
|
)
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-20 13:02:08 -05:00
|
|
|
import_parser = subcommands.add_parser(
|
|
|
|
"import",
|
|
|
|
help="import one or several PGP keys to the keyring directory structure",
|
2021-10-16 17:12:57 -05:00
|
|
|
)
|
2021-10-20 13:15:42 -05:00
|
|
|
import_parser.add_argument("source", type=absolute_path, nargs="+", help="Files or directories to import")
|
2021-10-20 13:02:08 -05:00
|
|
|
import_parser.add_argument(
|
2021-10-16 17:50:34 -05:00
|
|
|
"--name",
|
2021-10-19 14:03:53 -05:00
|
|
|
type=Username,
|
2021-10-16 17:12:57 -05:00
|
|
|
default=None,
|
2021-10-16 17:50:34 -05:00
|
|
|
help="override the username to use (only useful when using a single file as source)",
|
2021-10-16 17:12:57 -05:00
|
|
|
)
|
2021-10-20 13:02:08 -05:00
|
|
|
import_parser.add_argument("--main", action="store_true", help="Import a main signing key into the keyring")
|
2021-10-16 17:12:57 -05:00
|
|
|
|
2021-10-05 11:31:31 -05:00
|
|
|
export_parser = subcommands.add_parser(
|
2021-10-16 17:50:34 -05:00
|
|
|
"export",
|
2021-10-05 11:31:31 -05:00
|
|
|
help="export a directory structure of PGP packet data to a combined file",
|
|
|
|
)
|
2021-10-21 13:34:48 -05:00
|
|
|
export_parser.add_argument("-o", "--output", type=absolute_path, help="file to write PGP packet data to")
|
2021-10-05 11:31:31 -05:00
|
|
|
export_parser.add_argument(
|
2021-10-21 13:34:48 -05:00
|
|
|
"source",
|
|
|
|
nargs="*",
|
2021-10-22 20:01:06 -05:00
|
|
|
help="username, fingerprint or directories containing certificates",
|
2021-10-05 11:31:31 -05:00
|
|
|
type=absolute_path,
|
|
|
|
)
|
|
|
|
|
2021-10-21 14:04:16 -05:00
|
|
|
build_parser = subcommands.add_parser(
|
|
|
|
"build",
|
|
|
|
help="build keyring PGP artifacts alongside ownertrust and revoked status files",
|
|
|
|
)
|
|
|
|
|
2021-10-21 14:13:35 -05:00
|
|
|
list_parser = subcommands.add_parser(
|
|
|
|
"list",
|
|
|
|
help="list the certificates in the keyring",
|
|
|
|
)
|
|
|
|
list_parser.add_argument("--main", action="store_true", help="List main signing keys instead of packager keys")
|
|
|
|
list_parser.add_argument(
|
|
|
|
"source",
|
|
|
|
nargs="*",
|
2021-10-22 20:01:06 -05:00
|
|
|
help="username, fingerprint or directories containing certificates",
|
2021-10-21 14:13:35 -05:00
|
|
|
type=absolute_path,
|
|
|
|
)
|
|
|
|
|
2021-10-21 14:51:02 -05:00
|
|
|
inspect_parser = subcommands.add_parser(
|
|
|
|
"inspect",
|
|
|
|
help="inspect certificates in the keyring and pretty print the data",
|
|
|
|
)
|
|
|
|
inspect_parser.add_argument(
|
|
|
|
"source",
|
|
|
|
nargs="*",
|
2021-10-22 20:01:06 -05:00
|
|
|
help="username, fingerprint or directories containing certificates",
|
2021-10-21 14:51:02 -05:00
|
|
|
type=absolute_path,
|
|
|
|
)
|
|
|
|
|
2021-08-25 11:53:07 -05:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
if args.verbose:
|
|
|
|
basicConfig(level=DEBUG)
|
|
|
|
|
|
|
|
# temporary working directory that gets auto cleaned
|
2021-10-16 17:50:34 -05:00
|
|
|
with TemporaryDirectory(prefix="arch-keyringctl-") as tempdir:
|
2021-10-19 18:41:04 -05:00
|
|
|
keyring_root = Path("keyring").absolute()
|
2021-08-25 11:53:07 -05:00
|
|
|
working_dir = Path(tempdir)
|
2021-10-16 17:50:34 -05:00
|
|
|
debug(f"Working directory: {working_dir}")
|
2021-10-12 12:22:30 -05:00
|
|
|
with cwd(working_dir):
|
2021-10-16 17:50:34 -05:00
|
|
|
if "convert" == args.subcommand:
|
2021-10-20 13:08:26 -05:00
|
|
|
target_dir = args.target or Path(mkdtemp(prefix="arch-keyringctl-")).absolute()
|
2021-10-22 14:34:53 -05:00
|
|
|
print(
|
|
|
|
convert(
|
|
|
|
working_dir=working_dir,
|
|
|
|
keyring_root=keyring_root,
|
|
|
|
source=args.source,
|
|
|
|
target_dir=target_dir,
|
|
|
|
name_override=args.name,
|
|
|
|
)
|
|
|
|
)
|
2021-10-20 13:02:08 -05:00
|
|
|
elif "import" == args.subcommand:
|
|
|
|
target_dir = "main" if args.main else "packager"
|
2021-10-16 17:12:57 -05:00
|
|
|
print(
|
|
|
|
convert(
|
|
|
|
working_dir=working_dir,
|
2021-10-22 14:34:53 -05:00
|
|
|
keyring_root=keyring_root,
|
2021-10-16 17:12:57 -05:00
|
|
|
source=args.source,
|
2021-10-20 13:02:08 -05:00
|
|
|
target_dir=keyring_root / target_dir,
|
2021-10-16 17:12:57 -05:00
|
|
|
name_override=args.name,
|
|
|
|
)
|
|
|
|
)
|
2021-10-16 17:50:34 -05:00
|
|
|
elif "export" == args.subcommand:
|
2021-10-21 13:34:48 -05:00
|
|
|
print(
|
|
|
|
export(
|
|
|
|
working_dir=working_dir,
|
|
|
|
keyring_root=keyring_root,
|
|
|
|
sources=args.source,
|
|
|
|
output=args.output,
|
|
|
|
),
|
|
|
|
end="",
|
2021-10-12 12:22:30 -05:00
|
|
|
)
|
2021-10-21 14:04:16 -05:00
|
|
|
elif "build" == args.subcommand:
|
|
|
|
build(
|
|
|
|
working_dir=working_dir,
|
|
|
|
keyring_root=keyring_root,
|
|
|
|
target_dir=keyring_root.parent / "build",
|
|
|
|
)
|
2021-10-21 14:13:35 -05:00
|
|
|
elif "list" == args.subcommand:
|
|
|
|
list_keyring(
|
|
|
|
keyring_root=keyring_root,
|
|
|
|
sources=args.source,
|
|
|
|
main_keys=args.main,
|
|
|
|
)
|
2021-10-21 14:51:02 -05:00
|
|
|
elif "inspect" == args.subcommand:
|
|
|
|
print(
|
|
|
|
inspect_keyring(
|
|
|
|
working_dir=working_dir,
|
|
|
|
keyring_root=keyring_root,
|
|
|
|
sources=args.source,
|
|
|
|
),
|
|
|
|
end="",
|
|
|
|
)
|
2021-10-20 13:04:02 -05:00
|
|
|
else:
|
|
|
|
parser.print_help()
|
2021-08-25 11:53:07 -05:00
|
|
|
|
2021-10-12 12:22:30 -05:00
|
|
|
if args.wait:
|
2021-10-16 17:50:34 -05:00
|
|
|
print("Press [ENTER] to continue")
|
2021-10-12 12:22:30 -05:00
|
|
|
input()
|