"""Install release binaries locally after checking upstream SHA256 manifests.""" import argparse import hashlib import io import json import os import platform import re import tarfile import urllib.request from pathlib import Path def download(url: str) -> bytes: request = urllib.request.Request(url, headers={"User-Agent": "lincodex-security"}) with urllib.request.urlopen(request, timeout=120) as response: return response.read() def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("tool", choices=["trivy", "gitleaks"]) args = parser.parse_args() system = platform.system() machine = platform.machine() if system != "Linux" or machine not in {"x86_64", "aarch64", "arm64"}: parser.error("The binary installer supports Linux amd64/arm64.") owner = "aquasecurity" if args.tool == "trivy" else "gitleaks" repository = f"{owner}/{args.tool}" release = json.loads( download(f"https://api.github.com/repos/{repository}/releases/latest") ) tag = release["tag_name"] if not re.fullmatch(r"v\d+\.\d+\.\d+", tag): raise ValueError(f"Unexpected stable release tag: {tag}") version = tag.removeprefix("v") if args.tool == "trivy": arch = "64bit" if machine == "x86_64" else "ARM64" archive_name = f"trivy_{version}_Linux-{arch}.tar.gz" else: arch = "x64" if machine == "x86_64" else "arm64" archive_name = f"gitleaks_{version}_linux_{arch}.tar.gz" base = f"https://github.com/{repository}/releases/download/{tag}" manifest = download(f"{base}/{args.tool}_{version}_checksums.txt").decode() checksums = {} for line in manifest.splitlines(): fields = line.split() if len(fields) == 2: checksums[fields[1].lstrip("*")] = fields[0] archive = download(f"{base}/{archive_name}") expected = checksums.get(archive_name) if expected is None or hashlib.sha256(archive).hexdigest() != expected: raise ValueError(f"SHA256 verification failed for {archive_name}") destination = Path(__file__).resolve().parent / ".bin" destination.mkdir(exist_ok=True) with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as bundle: member = bundle.getmember(args.tool) if not member.isfile(): raise ValueError("Expected a regular executable in the release archive") binary = bundle.extractfile(member) if binary is None: raise ValueError("Release executable is missing") temporary = destination / f".{args.tool}.download" try: temporary.write_bytes(binary.read()) temporary.chmod(0o755) os.replace(temporary, destination / args.tool) finally: temporary.unlink(missing_ok=True) print(f"Installed {args.tool} {version}; SHA256 verified.") if __name__ == "__main__": main()