mirror of
https://github.com/CloakHQ/CloakBrowser.git
synced 2026-06-23 11:41:46 +02:00
feat(security): verify binaries with pinned Ed25519 signature on SHA256SUMS
Replace the same-origin checksum with a detached Ed25519 signature (SHA256SUMS.sig) verified against a pinned public key before extraction, closing #308: a compromised download mirror can no longer certify a tampered binary. The signed manifest also binds the release version, rejecting a forced downgrade to an older signed build. Verification is mandatory and non-bypassable on the official download path; custom CLOAKBROWSER_DOWNLOAD_URL mirrors keep the legacy skippable checksum. Silent auto-update is preserved for everyone because only a constant public key is pinned, not per-version hashes. Older installed wrappers are unaffected — the version= line is ignored by their checksum parser. Python uses cryptography; JS uses node:crypto. Adds tamper, downgrade, and fail-closed tests in both languages.
This commit is contained in:
+238
-1
@@ -2,12 +2,14 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
|
||||
from cloakbrowser.config import (
|
||||
CHROMIUM_VERSION,
|
||||
@@ -22,10 +24,14 @@ from cloakbrowser.download import (
|
||||
_check_wrapper_update,
|
||||
_download_and_extract,
|
||||
_fetch_checksums,
|
||||
_fetch_signed_manifest,
|
||||
_get_latest_chromium_version,
|
||||
_parse_checksums,
|
||||
_parse_manifest_version,
|
||||
_should_check_for_update,
|
||||
_verify_checksum,
|
||||
_verify_download_checksum,
|
||||
_verify_signature,
|
||||
_write_version_marker,
|
||||
check_for_update,
|
||||
clear_cache,
|
||||
@@ -486,7 +492,6 @@ class TestDownloadFallback:
|
||||
with patch.dict(os.environ, {
|
||||
"CLOAKBROWSER_CACHE_DIR": str(tmp_path),
|
||||
"CLOAKBROWSER_DOWNLOAD_URL": "",
|
||||
"CLOAKBROWSER_SKIP_CHECKSUM": "true",
|
||||
}):
|
||||
urls_called = []
|
||||
|
||||
@@ -497,7 +502,10 @@ class TestDownloadFallback:
|
||||
# GitHub fallback succeeds
|
||||
dest.write_bytes(b"fake")
|
||||
|
||||
# This test exercises URL fallback, not verification — stub the
|
||||
# (now signature-based, non-bypassable) verify step.
|
||||
with patch("cloakbrowser.download._download_file", side_effect=mock_download_file), \
|
||||
patch("cloakbrowser.download._verify_download_checksum"), \
|
||||
patch("cloakbrowser.download._extract_archive"), \
|
||||
patch("cloakbrowser.download._show_welcome"):
|
||||
_download_and_extract()
|
||||
@@ -548,3 +556,232 @@ class TestDownloadFallback:
|
||||
result = _fetch_checksums()
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Signed-manifest verification (Ed25519). Trust root is the pinned public key,
|
||||
# not the same-origin SHA256SUMS — this is what closes M1 (#308).
|
||||
# ---------------------------------------------------------------------------
|
||||
def _make_key():
|
||||
priv = Ed25519PrivateKey.generate()
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
raw = priv.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.Raw,
|
||||
format=serialization.PublicFormat.Raw,
|
||||
)
|
||||
return priv, base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _sign(priv, manifest_bytes: bytes) -> bytes:
|
||||
"""Return SHA256SUMS.sig content (base64 of the raw signature), as served."""
|
||||
return base64.b64encode(priv.sign(manifest_bytes))
|
||||
|
||||
|
||||
class TestSignatureVerification:
|
||||
"""_verify_signature: the cryptographic gate over the raw manifest bytes."""
|
||||
|
||||
def test_valid_signature_passes(self):
|
||||
priv, pub_b64 = _make_key()
|
||||
manifest = b"abc cloakbrowser-linux-x64.tar.gz\n"
|
||||
sig = _sign(priv, manifest)
|
||||
with patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]):
|
||||
_verify_signature(manifest, sig) # no raise
|
||||
|
||||
def test_tampered_manifest_fails(self):
|
||||
priv, pub_b64 = _make_key()
|
||||
manifest = b"abc cloakbrowser-linux-x64.tar.gz\n"
|
||||
sig = _sign(priv, manifest)
|
||||
tampered = manifest.replace(b"abc", b"xyz")
|
||||
with patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]):
|
||||
with pytest.raises(RuntimeError, match="signature verification failed"):
|
||||
_verify_signature(tampered, sig)
|
||||
|
||||
def test_wrong_key_fails(self):
|
||||
priv, _ = _make_key()
|
||||
_, other_pub = _make_key()
|
||||
manifest = b"data\n"
|
||||
sig = _sign(priv, manifest)
|
||||
with patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [other_pub]):
|
||||
with pytest.raises(RuntimeError, match="signature verification failed"):
|
||||
_verify_signature(manifest, sig)
|
||||
|
||||
def test_malformed_signature_fails(self):
|
||||
_, pub_b64 = _make_key()
|
||||
with patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]):
|
||||
with pytest.raises(RuntimeError, match="Malformed"):
|
||||
_verify_signature(b"data\n", b"!!!not base64!!!")
|
||||
|
||||
def test_placeholder_key_is_skipped_not_crashing(self):
|
||||
"""An unparseable pinned key (placeholder) must not abort — a real key still validates."""
|
||||
priv, pub_b64 = _make_key()
|
||||
manifest = b"data\n"
|
||||
sig = _sign(priv, manifest)
|
||||
with patch(
|
||||
"cloakbrowser.download.BINARY_SIGNING_PUBKEYS",
|
||||
["REPLACE_WITH_REAL_ED25519_PUBLIC_KEY_BASE64", pub_b64],
|
||||
):
|
||||
_verify_signature(manifest, sig) # no raise
|
||||
|
||||
def test_key_rotation_second_key_accepts(self):
|
||||
"""A manifest signed with the new key validates while the old key stays pinned."""
|
||||
old_priv, old_pub = _make_key()
|
||||
new_priv, new_pub = _make_key()
|
||||
manifest = b"rotated\n"
|
||||
sig = _sign(new_priv, manifest)
|
||||
with patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [old_pub, new_pub]):
|
||||
_verify_signature(manifest, sig) # no raise
|
||||
|
||||
|
||||
class TestVerifyDownloadChecksumSigned:
|
||||
"""_verify_download_checksum on the official path: signature + version + hash, fail-closed."""
|
||||
|
||||
def _hash(self, data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def _manifest(self, body: str, version: str | None = None) -> bytes:
|
||||
"""Build a signed-manifest body with the bound version line prepended."""
|
||||
v = version if version is not None else get_chromium_version()
|
||||
return f"version={v}\n{body}".encode()
|
||||
|
||||
def test_valid_manifest_and_hash_passes(self, tmp_path):
|
||||
priv, pub_b64 = _make_key()
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"the real binary")
|
||||
tarball = get_download_url().rsplit("/", 1)[-1]
|
||||
manifest = self._manifest(f"{self._hash(b'the real binary')} {tarball}\n")
|
||||
sig = _sign(priv, manifest)
|
||||
|
||||
with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}), \
|
||||
patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]), \
|
||||
patch("cloakbrowser.download._fetch_signed_manifest", return_value=(manifest, sig)):
|
||||
_verify_download_checksum(archive) # no raise
|
||||
|
||||
def test_tampered_binary_fails_hash(self, tmp_path):
|
||||
priv, pub_b64 = _make_key()
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"a malicious binary") # different bytes
|
||||
tarball = get_download_url().rsplit("/", 1)[-1]
|
||||
manifest = self._manifest(f"{self._hash(b'the real binary')} {tarball}\n")
|
||||
sig = _sign(priv, manifest)
|
||||
|
||||
with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}), \
|
||||
patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]), \
|
||||
patch("cloakbrowser.download._fetch_signed_manifest", return_value=(manifest, sig)):
|
||||
with pytest.raises(RuntimeError, match="Checksum verification failed"):
|
||||
_verify_download_checksum(archive)
|
||||
|
||||
def test_wrong_version_fails_downgrade(self, tmp_path):
|
||||
"""A genuinely-signed manifest for a DIFFERENT version is rejected (downgrade)."""
|
||||
priv, pub_b64 = _make_key()
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"the real binary")
|
||||
tarball = get_download_url().rsplit("/", 1)[-1]
|
||||
# Manifest declares an old version, but we ask for get_chromium_version().
|
||||
manifest = self._manifest(
|
||||
f"{self._hash(b'the real binary')} {tarball}\n", version="1.0.0.0"
|
||||
)
|
||||
sig = _sign(priv, manifest)
|
||||
with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}), \
|
||||
patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]), \
|
||||
patch("cloakbrowser.download._fetch_signed_manifest", return_value=(manifest, sig)):
|
||||
with pytest.raises(RuntimeError, match="Version mismatch"):
|
||||
_verify_download_checksum(archive)
|
||||
|
||||
def test_missing_version_line_fails(self, tmp_path):
|
||||
"""A signed manifest without a version line is rejected (binding required)."""
|
||||
priv, pub_b64 = _make_key()
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"the real binary")
|
||||
tarball = get_download_url().rsplit("/", 1)[-1]
|
||||
manifest = f"{self._hash(b'the real binary')} {tarball}\n".encode() # no version=
|
||||
sig = _sign(priv, manifest)
|
||||
with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}), \
|
||||
patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]), \
|
||||
patch("cloakbrowser.download._fetch_signed_manifest", return_value=(manifest, sig)):
|
||||
with pytest.raises(RuntimeError, match="Version mismatch"):
|
||||
_verify_download_checksum(archive)
|
||||
|
||||
def test_missing_signed_manifest_fails_closed(self, tmp_path):
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"x")
|
||||
with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}), \
|
||||
patch("cloakbrowser.download._fetch_signed_manifest", return_value=None):
|
||||
with pytest.raises(RuntimeError, match="signed SHA256SUMS"):
|
||||
_verify_download_checksum(archive)
|
||||
|
||||
def test_manifest_without_entry_fails(self, tmp_path):
|
||||
priv, pub_b64 = _make_key()
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"x")
|
||||
manifest = self._manifest("deadbeef some-other-file.tar.gz\n") # no entry for our tarball
|
||||
sig = _sign(priv, manifest)
|
||||
with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}), \
|
||||
patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]), \
|
||||
patch("cloakbrowser.download._fetch_signed_manifest", return_value=(manifest, sig)):
|
||||
with pytest.raises(RuntimeError, match="no entry for"):
|
||||
_verify_download_checksum(archive)
|
||||
|
||||
def test_custom_url_uses_plain_checksum_and_skip(self, tmp_path):
|
||||
"""Self-hosted CLOAKBROWSER_DOWNLOAD_URL keeps the legacy skippable path."""
|
||||
archive = tmp_path / "binary"
|
||||
archive.write_bytes(b"x")
|
||||
with patch.dict(os.environ, {
|
||||
"CLOAKBROWSER_DOWNLOAD_URL": "https://my-mirror.test",
|
||||
"CLOAKBROWSER_SKIP_CHECKSUM": "true",
|
||||
}):
|
||||
# Signature path must NOT be consulted for a custom mirror.
|
||||
with patch("cloakbrowser.download._fetch_signed_manifest") as mocked:
|
||||
_verify_download_checksum(archive) # skip honored, no raise
|
||||
mocked.assert_not_called()
|
||||
|
||||
|
||||
class TestVersionBinding:
|
||||
"""The 'version=<v>' line: read by new wrappers, ignored by old parsers."""
|
||||
|
||||
def test_parse_manifest_version(self):
|
||||
manifest = "version=146.0.7680.177.5\nabc cloakbrowser-linux-x64.tar.gz\n"
|
||||
assert _parse_manifest_version(manifest) == "146.0.7680.177.5"
|
||||
|
||||
def test_parse_manifest_version_absent(self):
|
||||
assert _parse_manifest_version("abc cloakbrowser-linux-x64.tar.gz\n") is None
|
||||
|
||||
def test_old_checksum_parser_ignores_version_line(self):
|
||||
"""Regression: the version line must not pollute the old hash map."""
|
||||
h = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
manifest = f"version=146.0.7680.177.5\n{h} cloakbrowser-linux-x64.tar.gz\n"
|
||||
result = _parse_checksums(manifest)
|
||||
assert result == {"cloakbrowser-linux-x64.tar.gz": h}
|
||||
|
||||
|
||||
class TestFetchSignedManifest:
|
||||
"""_fetch_signed_manifest pairs SHA256SUMS + .sig from the same origin."""
|
||||
|
||||
def test_fetches_both_from_primary(self):
|
||||
def mock_get(url, **kwargs):
|
||||
resp = MagicMock()
|
||||
resp.raise_for_status = MagicMock()
|
||||
resp.content = b"SIG" if url.endswith(".sig") else b"MANIFEST"
|
||||
return resp
|
||||
|
||||
with patch("cloakbrowser.download.httpx.get", side_effect=mock_get):
|
||||
result = _fetch_signed_manifest("1.2.3.4")
|
||||
assert result == (b"MANIFEST", b"SIG")
|
||||
|
||||
def test_falls_back_to_github_when_primary_missing_sig(self):
|
||||
def mock_get(url, **kwargs):
|
||||
resp = MagicMock()
|
||||
resp.content = b"SIG" if url.endswith(".sig") else b"MANIFEST"
|
||||
if "cloakbrowser.dev" in url and url.endswith(".sig"):
|
||||
resp.raise_for_status.side_effect = Exception("404")
|
||||
else:
|
||||
resp.raise_for_status = MagicMock()
|
||||
return resp
|
||||
|
||||
with patch("cloakbrowser.download.httpx.get", side_effect=mock_get):
|
||||
result = _fetch_signed_manifest("1.2.3.4")
|
||||
assert result == (b"MANIFEST", b"SIG")
|
||||
|
||||
def test_returns_none_when_all_fail(self):
|
||||
with patch("cloakbrowser.download.httpx.get", side_effect=Exception("network")):
|
||||
assert _fetch_signed_manifest("1.2.3.4") is None
|
||||
|
||||
Reference in New Issue
Block a user