mirror of
https://github.com/BigBodyCobain/Shadowbroker.git
synced 2026-12-05 09:03:39 +01:00
Let ZIP installs trust signed releases
The fail-closed source updater only trusts MESH_UPDATE_SHA256 or a digest already shipped in the install, so an install could never update to a release newer than itself. Releases now sign the source ZIP with the desktop updater key (cargo tauri signer sign), and the updater verifies <asset>.sig against the public key shipped in the code. A signature that is present but does not verify, names another file, or comes from another key refuses the update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5a6492d702
commit
508d428476
3 files changed
+314
-8
No files matched your search
+120
-8
@@ -16,6 +16,7 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import zipfile
|
||||
import base64
|
||||
import hashlib
|
||||
from urllib.parse import urlparse
|
||||
from datetime import datetime
|
||||
@@ -42,6 +43,16 @@ _RELEASE_DIGESTS_FILE = (
|
||||
# authorize executable source replacement.
|
||||
_SOURCE_ASSET_PATTERN = re.compile(r"^ShadowBroker_v\d", re.IGNORECASE)
|
||||
_SHA256SUMS_ASSET_NAME = "SHA256SUMS.txt"
|
||||
# Release signing key (minisign, as written by ``cargo tauri signer``). This is
|
||||
# the same key the desktop updater trusts (``tauri.conf.json`` ->
|
||||
# ``plugins.updater.pubkey``). Its private half never touches the release
|
||||
# channel, so a ``ShadowBroker_vX.Y.Z.zip.sig`` that verifies against it is an
|
||||
# independent trust source for releases newer than this install.
|
||||
_RELEASE_SIGNING_PUBLIC_KEY = (
|
||||
"dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDVEMTFERDdCNjhBRTk3MDcKUldRSGw2NW9lOTBSWGRjS1ZobFN5TkZsd3NkZ2g2L09WZzU4aytTR2FtN3ZtR0ZKejlNNldTbFUK"
|
||||
)
|
||||
_SIGNATURE_SUFFIX = ".sig"
|
||||
_MAX_SIGNATURE_BYTES = 4096
|
||||
|
||||
|
||||
def _is_docker() -> bool:
|
||||
@@ -138,8 +149,8 @@ def _download_release(temp_dir: str) -> tuple:
|
||||
stable filename can be matched against a pre-pinned digest.
|
||||
|
||||
Returns (zip_path, version_tag, download_url, release_url, asset_name,
|
||||
sha256sums_url) — the last two are empty strings when the release does not
|
||||
publish a named asset.
|
||||
sha256sums_url, signature_url) — the last three are empty strings when the
|
||||
release does not publish them.
|
||||
"""
|
||||
logger.info("Fetching latest release info from GitHub...")
|
||||
_validate_update_url(GITHUB_RELEASES_URL)
|
||||
@@ -156,6 +167,7 @@ def _download_release(temp_dir: str) -> tuple:
|
||||
asset_name = ""
|
||||
asset_url = ""
|
||||
sha256sums_url = ""
|
||||
signature_urls: dict[str, str] = {}
|
||||
for a in assets:
|
||||
name = str(a.get("name") or "").strip()
|
||||
download = str(a.get("browser_download_url") or "").strip()
|
||||
@@ -166,13 +178,17 @@ def _download_release(temp_dir: str) -> tuple:
|
||||
asset_url = download
|
||||
elif name == _SHA256SUMS_ASSET_NAME:
|
||||
sha256sums_url = download
|
||||
elif name.lower().endswith(_SIGNATURE_SUFFIX):
|
||||
signature_urls[name] = download
|
||||
signature_url = signature_urls.get(f"{asset_name}{_SIGNATURE_SUFFIX}", "") if asset_name else ""
|
||||
|
||||
if asset_url:
|
||||
zip_url = asset_url
|
||||
logger.info(
|
||||
"Using release asset %s (sha256sums=%s)",
|
||||
"Using release asset %s (sha256sums=%s, signature=%s)",
|
||||
asset_name,
|
||||
"yes" if sha256sums_url else "no",
|
||||
"yes" if signature_url else "no",
|
||||
)
|
||||
else:
|
||||
zip_url = str(release.get("zipball_url") or "").strip()
|
||||
@@ -201,7 +217,7 @@ def _download_release(temp_dir: str) -> tuple:
|
||||
|
||||
size_mb = os.path.getsize(zip_path) / (1024 * 1024)
|
||||
logger.info(f"Downloaded {size_mb:.1f} MB — ZIP validated OK")
|
||||
return zip_path, tag, zip_url, release_url, asset_name, sha256sums_url
|
||||
return zip_path, tag, zip_url, release_url, asset_name, sha256sums_url, signature_url
|
||||
|
||||
|
||||
def _compute_sha256(zip_path: str) -> str:
|
||||
@@ -238,6 +254,91 @@ def _load_baked_in_release_digests() -> dict:
|
||||
return cleaned
|
||||
|
||||
|
||||
def _decode_minisign_public_key(encoded: str) -> tuple[bytes, bytes]:
|
||||
"""Return (key_id, ed25519_public_key) from a Tauri/minisign public key."""
|
||||
text = base64.b64decode(encoded).decode("utf-8")
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
raw = base64.b64decode(lines[-1])
|
||||
if len(raw) != 42 or raw[:2] != b"Ed":
|
||||
raise ValueError("unsupported release signing public key")
|
||||
return raw[2:10], raw[10:42]
|
||||
|
||||
|
||||
def _verify_release_signature(zip_path: str, signature: str, asset_name: str) -> str:
|
||||
"""Verify a ``cargo tauri signer`` signature over the downloaded archive.
|
||||
|
||||
``signature`` is the content of the release's ``<asset>.sig`` file: a
|
||||
base64-wrapped minisign signature. Both the archive signature and the
|
||||
signed trusted comment must verify, and the trusted comment must name
|
||||
this asset, so a signature made for another file cannot be reused.
|
||||
Raises RuntimeError on any failure; returns the signed file name.
|
||||
"""
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
|
||||
try:
|
||||
key_id, public_key = _decode_minisign_public_key(_RELEASE_SIGNING_PUBLIC_KEY)
|
||||
text = base64.b64decode(signature.strip(), validate=True).decode("utf-8")
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if len(lines) < 4 or not lines[2].startswith("trusted comment: "):
|
||||
raise ValueError("malformed signature")
|
||||
sig_raw = base64.b64decode(lines[1], validate=True)
|
||||
global_sig = base64.b64decode(lines[3], validate=True)
|
||||
trusted_comment = lines[2][len("trusted comment: "):]
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
raise RuntimeError(f"Update signature is malformed: {exc}") from exc
|
||||
if len(sig_raw) != 74 or sig_raw[:2] not in (b"Ed", b"ED") or len(global_sig) != 64:
|
||||
raise RuntimeError("Update signature is malformed")
|
||||
if sig_raw[2:10] != key_id:
|
||||
raise RuntimeError("Update signature was made with an unknown key")
|
||||
|
||||
if sig_raw[:2] == b"ED":
|
||||
digest = hashlib.blake2b(digest_size=64)
|
||||
with open(zip_path, "rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 128), b""):
|
||||
digest.update(chunk)
|
||||
message = digest.digest()
|
||||
else:
|
||||
with open(zip_path, "rb") as handle:
|
||||
message = handle.read()
|
||||
|
||||
verifier = Ed25519PublicKey.from_public_bytes(public_key)
|
||||
try:
|
||||
verifier.verify(sig_raw[10:], message)
|
||||
verifier.verify(global_sig, sig_raw[10:] + trusted_comment.encode("utf-8"))
|
||||
except InvalidSignature as exc:
|
||||
raise RuntimeError("Update signature does not match the archive") from exc
|
||||
|
||||
signed_name = ""
|
||||
for field in trusted_comment.split(" "):
|
||||
if field.startswith("file:"):
|
||||
signed_name = field[len("file:"):].strip()
|
||||
if not asset_name or signed_name != asset_name:
|
||||
raise RuntimeError(
|
||||
f"Update signature names {signed_name or 'no file'}, not {asset_name or 'this archive'}"
|
||||
)
|
||||
return signed_name
|
||||
|
||||
|
||||
def _fetch_release_signature(signature_url: str) -> str:
|
||||
"""Download a small ``.sig`` release asset; '' when it cannot be fetched."""
|
||||
if not signature_url:
|
||||
return ""
|
||||
try:
|
||||
_validate_update_url(signature_url)
|
||||
resp = requests.get(signature_url, timeout=15)
|
||||
resp.raise_for_status()
|
||||
_validate_update_url(resp.url)
|
||||
except Exception as exc:
|
||||
logger.warning("Release signature fetch failed: %s", exc)
|
||||
return ""
|
||||
body = resp.content[: _MAX_SIGNATURE_BYTES + 1]
|
||||
if len(body) > _MAX_SIGNATURE_BYTES:
|
||||
logger.warning("Release signature is larger than %d bytes; ignoring it", _MAX_SIGNATURE_BYTES)
|
||||
return ""
|
||||
return body.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def _fetch_sha256sums(sha256sums_url: str) -> dict[str, str]:
|
||||
"""Download a SHA256SUMS.txt and return {filename: digest_hex_lower}."""
|
||||
try:
|
||||
@@ -277,13 +378,17 @@ def _validate_zip_hash(
|
||||
asset_name: str = "",
|
||||
sha256sums_url: str = "",
|
||||
release_tag: str = "",
|
||||
signature: str = "",
|
||||
) -> str:
|
||||
"""Verify an executable source update against an independent trust source.
|
||||
|
||||
Authorization order:
|
||||
|
||||
1. ``MESH_UPDATE_SHA256`` — explicit operator pin.
|
||||
2. ``backend/data/release_digests.json`` — a digest already shipped in
|
||||
2. The release's ``<asset>.sig``, signed with the release key whose
|
||||
public half ships in this install. A signature that is present but
|
||||
does not verify refuses the update.
|
||||
3. ``backend/data/release_digests.json`` — a digest already shipped in
|
||||
the installed application.
|
||||
|
||||
A release ``SHA256SUMS.txt`` is fetched only as a consistency diagnostic.
|
||||
@@ -305,6 +410,10 @@ def _validate_zip_hash(
|
||||
f"expected={override[:16]}..."
|
||||
)
|
||||
|
||||
if signature:
|
||||
signed_name = _verify_release_signature(zip_path, signature, asset_name)
|
||||
return f"verified via release signature for {signed_name} ({actual[:16]}...)"
|
||||
|
||||
baked = _load_baked_in_release_digests()
|
||||
baked_expected = ""
|
||||
if release_tag and asset_name:
|
||||
@@ -331,8 +440,8 @@ def _validate_zip_hash(
|
||||
raise RuntimeError(
|
||||
"Update refused: no independent archive digest is trusted for "
|
||||
f"release={release_tag or 'unknown'} asset={asset_name or 'unknown'}."
|
||||
f"{release_checksum_note} Pin MESH_UPDATE_SHA256 or ship a matching "
|
||||
"backend/data/release_digests.json entry before enabling in-place installation."
|
||||
f"{release_checksum_note} The release needs a signed {asset_name or 'archive'}.sig, "
|
||||
"or pin MESH_UPDATE_SHA256."
|
||||
)
|
||||
|
||||
|
||||
@@ -504,7 +613,9 @@ def perform_update(project_root: str) -> dict:
|
||||
temp_dir = tempfile.mkdtemp(prefix="sb_update_")
|
||||
manual_url = GITHUB_RELEASES_PAGE_URL
|
||||
try:
|
||||
zip_path, version, url, release_url, asset_name, sha256sums_url = _download_release(temp_dir)
|
||||
downloaded = _download_release(temp_dir)
|
||||
zip_path, version, url, release_url, asset_name, sha256sums_url = downloaded[:6]
|
||||
signature_url = downloaded[6] if len(downloaded) > 6 else ""
|
||||
manual_url = release_url or manual_url
|
||||
|
||||
if in_docker:
|
||||
@@ -541,6 +652,7 @@ def perform_update(project_root: str) -> dict:
|
||||
asset_name=asset_name,
|
||||
sha256sums_url=sha256sums_url,
|
||||
release_tag=version,
|
||||
signature=_fetch_release_signature(signature_url),
|
||||
)
|
||||
logger.info("Update archive %s", verification_note)
|
||||
backup_path = _backup_current(project_root, temp_dir)
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Signed source updates.
|
||||
|
||||
A ZIP install can only trust a newer release through something the release
|
||||
channel cannot forge. The release ZIP is signed with the same key as the
|
||||
desktop installers (``cargo tauri signer sign``); the updater checks that
|
||||
signature against the public key shipped in the installed code.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||
|
||||
from services import updater
|
||||
|
||||
ASSET = "ShadowBroker_v9.9.9.zip"
|
||||
KEY_ID = bytes.fromhex("0102030405060708")
|
||||
|
||||
|
||||
def _public_key_text(private: Ed25519PrivateKey, key_id: bytes = KEY_ID) -> str:
|
||||
raw = private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
|
||||
body = base64.b64encode(b"Ed" + key_id + raw).decode()
|
||||
text = f"untrusted comment: minisign public key: {key_id.hex().upper()}\n{body}\n"
|
||||
return base64.b64encode(text.encode()).decode()
|
||||
|
||||
|
||||
def _sign(private: Ed25519PrivateKey, data: bytes, file_name: str, key_id: bytes = KEY_ID) -> str:
|
||||
"""Build a signature the way ``cargo tauri signer sign`` writes it."""
|
||||
sig = private.sign(hashlib.blake2b(data, digest_size=64).digest())
|
||||
trusted = f"timestamp:{int(time.time())}\tfile:{file_name}"
|
||||
global_sig = private.sign(sig + trusted.encode())
|
||||
text = (
|
||||
"untrusted comment: signature from tauri secret key\n"
|
||||
f"{base64.b64encode(b'ED' + key_id + sig).decode()}\n"
|
||||
f"trusted comment: {trusted}\n"
|
||||
f"{base64.b64encode(global_sig).decode()}\n"
|
||||
)
|
||||
return base64.b64encode(text.encode()).decode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def release(tmp_path, monkeypatch):
|
||||
private = Ed25519PrivateKey.generate()
|
||||
monkeypatch.setattr(updater, "_RELEASE_SIGNING_PUBLIC_KEY", _public_key_text(private))
|
||||
monkeypatch.delenv("MESH_UPDATE_SHA256", raising=False)
|
||||
monkeypatch.setattr(updater, "_load_baked_in_release_digests", lambda: {})
|
||||
monkeypatch.setattr(updater, "_fetch_sha256sums", lambda _url: {})
|
||||
archive = tmp_path / ASSET
|
||||
archive.write_bytes(b"release archive bytes")
|
||||
return private, archive
|
||||
|
||||
|
||||
def test_signed_archive_is_trusted(release):
|
||||
private, archive = release
|
||||
note = updater._validate_zip_hash(
|
||||
str(archive),
|
||||
asset_name=ASSET,
|
||||
release_tag="v9.9.9",
|
||||
signature=_sign(private, archive.read_bytes(), ASSET),
|
||||
)
|
||||
assert "release signature" in note
|
||||
|
||||
|
||||
def test_tampered_archive_is_refused(release):
|
||||
private, archive = release
|
||||
signature = _sign(private, archive.read_bytes(), ASSET)
|
||||
archive.write_bytes(b"release archive bytes, plus a payload")
|
||||
with pytest.raises(RuntimeError, match="does not match"):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature=signature)
|
||||
|
||||
|
||||
def test_signature_for_another_file_is_refused(release):
|
||||
private, archive = release
|
||||
signature = _sign(private, archive.read_bytes(), "ShadowBroker_v9.9.8.zip")
|
||||
with pytest.raises(RuntimeError, match="names ShadowBroker_v9.9.8.zip"):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature=signature)
|
||||
|
||||
|
||||
def test_signature_from_another_key_is_refused(release):
|
||||
_private, archive = release
|
||||
other = Ed25519PrivateKey.generate()
|
||||
signature = _sign(other, archive.read_bytes(), ASSET, key_id=bytes.fromhex("0807060504030201"))
|
||||
with pytest.raises(RuntimeError, match="unknown key"):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature=signature)
|
||||
forged = _sign(other, archive.read_bytes(), ASSET) # right key id, wrong key
|
||||
with pytest.raises(RuntimeError, match="does not match"):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature=forged)
|
||||
|
||||
|
||||
def test_malformed_signature_is_refused(release):
|
||||
_private, archive = release
|
||||
with pytest.raises(RuntimeError, match="malformed"):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature="not base64!")
|
||||
|
||||
|
||||
def test_bad_signature_refuses_even_with_a_baked_digest(release, monkeypatch):
|
||||
private, archive = release
|
||||
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
|
||||
monkeypatch.setattr(updater, "_load_baked_in_release_digests", lambda: {"v9.9.9": {ASSET: digest}})
|
||||
signature = _sign(Ed25519PrivateKey.generate(), archive.read_bytes(), ASSET)
|
||||
with pytest.raises(RuntimeError):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature=signature)
|
||||
|
||||
|
||||
def test_operator_pin_still_wins(release, monkeypatch):
|
||||
_private, archive = release
|
||||
monkeypatch.setenv("MESH_UPDATE_SHA256", hashlib.sha256(archive.read_bytes()).hexdigest())
|
||||
note = updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9", signature="junk")
|
||||
assert "MESH_UPDATE_SHA256" in note
|
||||
|
||||
|
||||
def test_unsigned_release_without_digest_is_still_refused(release):
|
||||
_private, archive = release
|
||||
with pytest.raises(RuntimeError, match="no independent archive digest"):
|
||||
updater._validate_zip_hash(str(archive), asset_name=ASSET, release_tag="v9.9.9")
|
||||
|
||||
|
||||
def test_download_finds_the_archive_signature(tmp_path, monkeypatch):
|
||||
base = "https://github.com/BigBodyCobain/Shadowbroker/releases/download/v9.9.9/"
|
||||
release_json = {
|
||||
"tag_name": "v9.9.9",
|
||||
"html_url": "https://github.com/BigBodyCobain/Shadowbroker/releases/tag/v9.9.9",
|
||||
"assets": [
|
||||
{"name": ASSET, "browser_download_url": base + ASSET},
|
||||
{"name": ASSET + ".sig", "browser_download_url": base + ASSET + ".sig"},
|
||||
{"name": "ShadowBroker_9.9.9_x64-setup.exe.sig", "browser_download_url": base + "x.sig"},
|
||||
{"name": "SHA256SUMS.txt", "browser_download_url": base + "SHA256SUMS.txt"},
|
||||
],
|
||||
}
|
||||
zip_bytes = (Path(__file__).parent / "__init__.py").read_bytes()
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as zf:
|
||||
zf.writestr("README.md", zip_bytes)
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, url, payload=None, content=b""):
|
||||
self.url = url
|
||||
self._payload = payload
|
||||
self.content = content
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
def iter_content(self, chunk_size=0):
|
||||
yield self.content
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def _get(url, **_kwargs):
|
||||
if url == updater.GITHUB_RELEASES_URL:
|
||||
return _Resp(url, payload=release_json)
|
||||
return _Resp(url, content=buf.getvalue())
|
||||
|
||||
monkeypatch.setattr(updater.requests, "get", _get)
|
||||
result = updater._download_release(str(tmp_path))
|
||||
assert result[4] == ASSET
|
||||
assert result[6] == base + ASSET + ".sig"
|
||||
|
||||
|
||||
def test_shipped_key_is_the_desktop_updater_key():
|
||||
conf = Path(__file__).resolve().parents[2] / "desktop-shell" / "tauri-skeleton" / "src-tauri" / "tauri.conf.json"
|
||||
if not conf.is_file():
|
||||
pytest.skip("desktop shell config not in this checkout")
|
||||
pubkey = json.loads(conf.read_text(encoding="utf-8"))["plugins"]["updater"]["pubkey"]
|
||||
assert updater._RELEASE_SIGNING_PUBLIC_KEY == pubkey
|
||||
@@ -124,6 +124,20 @@ https://github.com/BigBodyCobain/Shadowbroker/releases/latest/download/latest.js
|
||||
|
||||
For GitHub releases, upload `latest.json`, the installer (`.msi` / `.exe`), and
|
||||
the matching `.sig` files generated under `src-tauri/target/release/bundle/`.
|
||||
|
||||
The source ZIP (`ShadowBroker_vX.Y.Z.zip`) is signed with the same key:
|
||||
|
||||
```bash
|
||||
cargo tauri signer sign ShadowBroker_vX.Y.Z.zip
|
||||
```
|
||||
|
||||
Upload the resulting `ShadowBroker_vX.Y.Z.zip.sig` next to the ZIP. ZIP and
|
||||
source installs verify it against the public key in
|
||||
`backend/services/updater.py` (which must equal the one in
|
||||
`tauri.conf.json`) and refuse a release whose ZIP has no valid signature
|
||||
unless the operator pins `MESH_UPDATE_SHA256`. `SHA256SUMS.txt` is only a
|
||||
consistency check.
|
||||
|
||||
Tauri updater signing verifies update packages only; it does not remove Windows
|
||||
SmartScreen warnings. Windows public trust still requires a real code-signing
|
||||
certificate later.
|
||||
|
||||
Reference in new issue
Block a user