|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import shutil |
| 5 | +import tarfile |
| 6 | +import zipfile |
| 7 | +from pathlib import Path |
| 8 | +from urllib.request import urlretrieve |
| 9 | + |
| 10 | +from osv_common import collect_history, iter_vulnerability_files, load_vulnerability, recidivism_for_vulnerability |
| 11 | +from recidivism_config import get_required_value, load_config_with_source, resolve_config_path |
| 12 | + |
| 13 | + |
| 14 | +def download_dump(url: str, destination: Path, force: bool) -> None: |
| 15 | + if destination.exists() and not force: |
| 16 | + return |
| 17 | + destination.parent.mkdir(parents=True, exist_ok=True) |
| 18 | + urlretrieve(url, destination) |
| 19 | + |
| 20 | + |
| 21 | +def extract_dump(archive: Path, extract_dir: Path, force: bool) -> None: |
| 22 | + if extract_dir.exists() and force: |
| 23 | + shutil.rmtree(extract_dir) |
| 24 | + extract_dir.mkdir(parents=True, exist_ok=True) |
| 25 | + |
| 26 | + if archive.suffix == ".zip": |
| 27 | + with zipfile.ZipFile(archive, "r") as zf: |
| 28 | + zf.extractall(extract_dir) |
| 29 | + elif archive.name.endswith(".tar.gz") or archive.suffix == ".tgz": |
| 30 | + with tarfile.open(archive, "r:gz") as tf: |
| 31 | + tf.extractall(extract_dir) |
| 32 | + else: |
| 33 | + raise ValueError(f"Unsupported archive format: {archive}") |
| 34 | + |
| 35 | + |
| 36 | +def main() -> None: |
| 37 | + config, config_source = load_config_with_source("enrich") |
| 38 | + |
| 39 | + parser = argparse.ArgumentParser(description="Download OSV dump and enrich with recidivism metrics.") |
| 40 | + parser.add_argument("--dump-url", help="Override enrich.dump_url from recidivism.ini") |
| 41 | + parser.add_argument("--archive-path", help="Override enrich.archive_path from recidivism.ini") |
| 42 | + parser.add_argument("--extract-dir", help="Override enrich.extract_dir from recidivism.ini") |
| 43 | + parser.add_argument("--output", help="Override enrich.output from recidivism.ini") |
| 44 | + parser.add_argument( |
| 45 | + "--force-download", |
| 46 | + action=argparse.BooleanOptionalAction, |
| 47 | + default=config.getboolean("force_download", fallback=False), |
| 48 | + ) |
| 49 | + parser.add_argument( |
| 50 | + "--force-extract", |
| 51 | + action=argparse.BooleanOptionalAction, |
| 52 | + default=config.getboolean("force_extract", fallback=False), |
| 53 | + ) |
| 54 | + args = parser.parse_args() |
| 55 | + |
| 56 | + try: |
| 57 | + dump_url = args.dump_url or get_required_value(config, "enrich", "dump_url") |
| 58 | + archive_path = resolve_config_path(args.archive_path or get_required_value(config, "enrich", "archive_path")) |
| 59 | + extract_dir = resolve_config_path(args.extract_dir or get_required_value(config, "enrich", "extract_dir")) |
| 60 | + output_path = resolve_config_path(args.output or get_required_value(config, "enrich", "output")) |
| 61 | + except ValueError as error: |
| 62 | + parser.error(f"{error} (config: {config_source})") |
| 63 | + |
| 64 | + download_dump(dump_url, archive_path, args.force_download) |
| 65 | + extract_dump(archive_path, extract_dir, args.force_extract) |
| 66 | + |
| 67 | + vulnerability_files = list(iter_vulnerability_files(extract_dir)) |
| 68 | + cwe_counts, repo_counts = collect_history(load_vulnerability(path) for path in vulnerability_files) |
| 69 | + |
| 70 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 71 | + enriched_count = 0 |
| 72 | + with output_path.open("w", encoding="utf-8") as handle: |
| 73 | + for path in vulnerability_files: |
| 74 | + vulnerability = load_vulnerability(path) |
| 75 | + metric = recidivism_for_vulnerability(vulnerability, cwe_counts, repo_counts) |
| 76 | + dbs = vulnerability.setdefault("database_specific", {}) |
| 77 | + if "recidivism" in dbs: |
| 78 | + print(f"Overwriting existing recidivism metric for vulnerability {vulnerability.get('id', 'UNKNOWN')}") |
| 79 | + dbs["recidivism"] = metric |
| 80 | + |
| 81 | + severity = [ |
| 82 | + item |
| 83 | + for item in vulnerability.setdefault("severity", []) |
| 84 | + if item.get("type") not in {"RECIDIVISM", "RECIDIVISM_ADJUSTED"} |
| 85 | + ] |
| 86 | + severity.append({"type": "RECIDIVISM", "score": f"{metric['score']:.2f}"}) |
| 87 | + adjusted = metric["adjusted_severity_score"] |
| 88 | + if adjusted is not None: |
| 89 | + severity.append({"type": "RECIDIVISM_ADJUSTED", "score": f"{adjusted:.2f}"}) |
| 90 | + vulnerability["severity"] = severity |
| 91 | + |
| 92 | + handle.write(json.dumps(vulnerability, sort_keys=True)) |
| 93 | + handle.write("\n") |
| 94 | + enriched_count += 1 |
| 95 | + |
| 96 | + print(f"Enriched {enriched_count} vulnerabilities -> {output_path}") |
| 97 | + |
| 98 | + |
| 99 | +if __name__ == "__main__": |
| 100 | + main() |
0 commit comments