security_packages.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """Optional security executables. Acquisition and publication belong to PM."""
  2. from __future__ import annotations
  3. import logging
  4. import shutil
  5. import subprocess
  6. import tempfile
  7. from pathlib import Path
  8. from urllib.parse import urlparse
  9. from pm import paths
  10. from pm.filesystem import native
  11. from pm.lock import Lockfile
  12. from pm.package import InstallError
  13. from pm.packages import BinaryPackage, _RUST_TRIPLE
  14. from pm.registry import register
  15. from pm.store import MUSL_TARGETS, flatten_single_dir
  16. @register
  17. class Bws(BinaryPackage):
  18. name = "bws"
  19. optional = True
  20. binary_rel = {"posix": "bws", "win32": "bws.exe"}
  21. gaps = {"linux-arm64-bionic": "upstream does not ship an Android binary"}
  22. def fetch_url(self, version: str, target: str) -> str:
  23. # The static musl build runs on glibc too. One portable Linux artifact
  24. # removes the consumer's ldd probe without losing musl support.
  25. triple = _RUST_TRIPLE[target].replace("linux-gnu", "linux-musl")
  26. platform = "macos-universal" if target.startswith("darwin") else triple
  27. return f"https://github.com/bitwarden/sdk-sm/releases/download/bws-v{version}/bws-{platform}-{version}.zip"
  28. def stage(self, store, staged: Path, version: str, target: str) -> None:
  29. super().stage(store, staged, version, target)
  30. binary = self.binary(staged, target)
  31. if binary is not None and binary.is_file():
  32. binary.chmod(0o755)
  33. class _SignedBinary(BinaryPackage):
  34. """The same PM artifact transaction also acquires pinned provenance files.
  35. The consumer owns signature semantics, not a second downloader. Checksum
  36. signatures must cover the *archive* pinned by PM, not an unrelated blob.
  37. Every locked provenance artifact is required even without a verifier on
  38. PATH. This intentionally strengthens cold-install availability: a missing
  39. or corrupt signature/key/certificate cannot silently reduce the pinned
  40. closure. Verifier execution remains optional; explicit rejection is fatal.
  41. """
  42. optional = True
  43. gaps = {
  44. "win32-x64": "this integration requires a Linux/macOS host (or WSL)",
  45. "win32-arm64": "this integration requires a Linux/macOS host (or WSL)",
  46. "linux-arm64-bionic": "upstream does not ship an Android binary",
  47. }
  48. def unpack(self, archive: Path, staged: Path, target: str) -> None:
  49. if archive.name.endswith((".txt", ".sig", ".pem", ".asc")):
  50. directory = staged / ".provenance"
  51. directory.mkdir(parents=True)
  52. shutil.copyfile(archive, directory / archive.name)
  53. else:
  54. super().unpack(archive, staged, target)
  55. flatten_single_dir(staged)
  56. def stage(self, store, staged: Path, version: str, target: str) -> None:
  57. binary = self.binary(staged, target)
  58. if binary is None or not binary.is_file() or binary.is_symlink():
  59. raise InstallError(self.name, "archive binary is not a regular file")
  60. binary.chmod(0o755)
  61. provenance = staged / ".provenance"
  62. artifacts = Lockfile(paths.lockfile_path()).artifacts(self.name, target)
  63. archive = artifacts[0]
  64. filename = Path(urlparse(archive["url"]).path).name
  65. rows = (line.split() for line in (provenance / "checksums.txt").read_text(encoding="utf-8-sig").splitlines())
  66. expected = next((row[0] for row in rows if len(row) == 2 and row[1].lstrip("*") == filename), None)
  67. if expected != archive["sha256"]:
  68. raise InstallError(self.name, "release checksums do not cover the pinned archive")
  69. self.verify_provenance(provenance)
  70. def verify_provenance(self, directory: Path) -> None:
  71. raise NotImplementedError
  72. @register
  73. class IronProxy(_SignedBinary):
  74. name = "iron-proxy"
  75. binary_rel = {"posix": "iron-proxy"}
  76. # The release omits its public key asset; pin the key from its source commit.
  77. signing_key_url = "https://raw.githubusercontent.com/paradigmxyz/iron-proxy/be5f255d0d9d10d8573bd65f480dd48a07772bf1/public-key.asc"
  78. def _probe_env(self) -> dict:
  79. from agent.proxy_sources.iron_proxy import allowlisted_env
  80. return allowlisted_env()
  81. def fetch_url(self, version: str, target: str) -> str:
  82. # Linux releases are built with CGO_ENABLED=0, so the same signed
  83. # archive is portable across glibc and musl userlands.
  84. lookup_target = target.removesuffix("-musl") if target in MUSL_TARGETS else target
  85. platform, arch = lookup_target.split("-")
  86. arch = "amd64" if arch == "x64" else arch
  87. return f"https://github.com/paradigmxyz/iron-proxy/releases/download/v{version}/iron-proxy_{version}_{platform}_{arch}.tar.gz"
  88. def fetch_urls(self, version: str, target: str) -> list[str]:
  89. archive = self.fetch_url(version, target)
  90. base = archive.rsplit("/", 1)[0]
  91. return [archive, f"{base}/checksums.txt", f"{base}/checksums.txt.asc", self.signing_key_url]
  92. def verify_provenance(self, directory: Path) -> None:
  93. # Keep package provenance inside PM rather than calling a private
  94. # helper in the running proxy (which also owns runtime subprocesses).
  95. gpg = shutil.which("gpg")
  96. if not gpg:
  97. logging.getLogger(__name__).warning("gpg unavailable; iron-proxy archive checksum remains enforced")
  98. return
  99. with tempfile.TemporaryDirectory(prefix="hermes-iron-signature-") as home:
  100. args = [gpg, "--homedir", home, "--batch", "--no-tty"]
  101. signature = directory / "checksums.txt.asc"
  102. key = directory / "public-key.asc"
  103. if not signature.is_file() or not key.is_file():
  104. raise InstallError(self.name, "pinned signature assets missing")
  105. imported = subprocess.run([*args, "--import", native(key)], stdin=subprocess.DEVNULL,
  106. capture_output=True, timeout=60, check=False)
  107. if imported.returncode:
  108. logging.getLogger(__name__).warning("Could not import iron-proxy signing key; archive checksum remains enforced")
  109. return
  110. verified = subprocess.run([*args, "--verify", native(signature), native(directory / "checksums.txt")],
  111. stdin=subprocess.DEVNULL, capture_output=True, timeout=60, check=False)
  112. if verified.returncode:
  113. raise InstallError(self.name, "GPG signature verification failed")