|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# VulnerableCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 6 | +# See https://github.com/aboutcode-org/vulnerablecode for support or download. |
| 7 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 8 | +# |
| 9 | + |
| 10 | +import gzip |
| 11 | +import io |
| 12 | +import os |
| 13 | +import shutil |
| 14 | +import tarfile |
| 15 | +import tempfile |
| 16 | +from pathlib import Path |
| 17 | +from typing import List |
| 18 | + |
| 19 | +import requests |
| 20 | + |
| 21 | +from vulnerabilities.models import AdvisoryAlias |
| 22 | +from vulnerabilities.models import AdvisoryDetectionRule |
| 23 | +from vulnerabilities.pipelines import VulnerableCodeBaseImporterPipelineV2 |
| 24 | +from vulnerabilities.utils import find_all_cve |
| 25 | + |
| 26 | + |
| 27 | +def extract_cvd(cvd_path, output_dir): |
| 28 | + """ |
| 29 | + Extract a CVD file. CVD format: 512-byte header + gzipped tar archive and returns Path to output directory |
| 30 | + """ |
| 31 | + output_path = Path(output_dir) |
| 32 | + output_path.mkdir(parents=True, exist_ok=True) |
| 33 | + |
| 34 | + with open(cvd_path, "rb") as f: |
| 35 | + f.seek(512) # Skip header |
| 36 | + compressed_data = f.read() |
| 37 | + |
| 38 | + decompressed_data = gzip.decompress(compressed_data) |
| 39 | + tar_buffer = io.BytesIO(decompressed_data) |
| 40 | + |
| 41 | + with tarfile.open(fileobj=tar_buffer, mode="r:") as tar: |
| 42 | + tar.extractall(path=output_path) |
| 43 | + |
| 44 | + for file in output_path.rglob("*"): |
| 45 | + if file.is_file(): |
| 46 | + file.chmod(0o644) # rw-r--r-- |
| 47 | + return output_path |
| 48 | + |
| 49 | + |
| 50 | +def parse_ndb_file(ndb_path: Path) -> List[dict]: |
| 51 | + """Parse a .ndb file (extended signatures). Return list of dicts.""" |
| 52 | + signatures = [] |
| 53 | + with ndb_path.open("r", encoding="utf-8", errors="ignore") as f: |
| 54 | + for line_num, line in enumerate(f, 1): |
| 55 | + line = line.strip() |
| 56 | + if not line or line.startswith("#"): |
| 57 | + continue |
| 58 | + |
| 59 | + parts = line.split(":") |
| 60 | + if len(parts) >= 4: |
| 61 | + signatures.append( |
| 62 | + { |
| 63 | + "name": parts[0], |
| 64 | + "target_type": parts[1], |
| 65 | + "offset": parts[2], |
| 66 | + "hex_signature": parts[3], |
| 67 | + "line_num": line_num, |
| 68 | + } |
| 69 | + ) |
| 70 | + return signatures |
| 71 | + |
| 72 | + |
| 73 | +def parse_hdb_file(hdb_path: Path) -> List[dict]: |
| 74 | + """Parse a .hdb file (MD5 hash signatures). Return list of dicts.""" |
| 75 | + signatures = [] |
| 76 | + with hdb_path.open("r", encoding="utf-8", errors="ignore") as f: |
| 77 | + for line_num, line in enumerate(f, 1): |
| 78 | + line = line.strip() |
| 79 | + if not line or line.startswith("#"): |
| 80 | + continue |
| 81 | + |
| 82 | + parts = line.split(":") |
| 83 | + if len(parts) >= 3: |
| 84 | + signatures.append( |
| 85 | + { |
| 86 | + "hash": parts[0], |
| 87 | + "file_size": parts[1], |
| 88 | + "name": parts[2], |
| 89 | + "line_num": line_num, |
| 90 | + } |
| 91 | + ) |
| 92 | + return signatures |
| 93 | + |
| 94 | + |
| 95 | +def extract_cve_id(name: str): |
| 96 | + """Normalize underscores and extract the first CVE ID from a string, or None.""" |
| 97 | + normalized = name.replace("_", "-") |
| 98 | + cves = [cve.upper() for cve in find_all_cve(normalized)] |
| 99 | + return cves[0] if cves else None |
| 100 | + |
| 101 | + |
| 102 | +class ClamVRulesImproverPipeline(VulnerableCodeBaseImporterPipelineV2): |
| 103 | + """ |
| 104 | + Pipeline that downloads ClamAV database (main.cvd), extracts signatures, |
| 105 | + parses .ndb and .hdb files and save a detection rules. |
| 106 | + """ |
| 107 | + |
| 108 | + pipeline_id = "clamv_rules" |
| 109 | + MAIN_DATABASE_URL = "https://database.clamav.net/main.cvd" |
| 110 | + license_url = "" |
| 111 | + license_expression = "GNU GENERAL PUBLIC LICENSE" |
| 112 | + |
| 113 | + @classmethod |
| 114 | + def steps(cls): |
| 115 | + return ( |
| 116 | + cls.download_database, |
| 117 | + cls.extract_database, |
| 118 | + cls.collect_and_store_advisories, |
| 119 | + cls.clean_downloads, |
| 120 | + ) |
| 121 | + |
| 122 | + def download_database(self): |
| 123 | + """Download ClamAV database using the supported API with proper headers.""" |
| 124 | + |
| 125 | + self.log("Downloading ClamAV database…") |
| 126 | + self.db_dir = Path(tempfile.mkdtemp()) / "clamav_db" |
| 127 | + self.db_dir.mkdir(parents=True, exist_ok=True) |
| 128 | + |
| 129 | + database_url = "https://database.clamav.net/main.cvd?api-version=1" |
| 130 | + headers = { |
| 131 | + "User-Agent": "ClamAV-Client/1.0 (https://github.com/yourproject)", |
| 132 | + "Accept": "*/*", |
| 133 | + } |
| 134 | + |
| 135 | + filename = self.db_dir / "main.cvd" |
| 136 | + self.log(f"Downloading {database_url} → {filename}") |
| 137 | + |
| 138 | + resp = requests.get(database_url, headers=headers, stream=True, timeout=30) |
| 139 | + resp.raise_for_status() |
| 140 | + |
| 141 | + with filename.open("wb") as f: |
| 142 | + for chunk in resp.iter_content(chunk_size=8192): |
| 143 | + if chunk: |
| 144 | + f.write(chunk) |
| 145 | + |
| 146 | + self.log("ClamAV DB file downloaded successfully.") |
| 147 | + |
| 148 | + def extract_database(self): |
| 149 | + """Extract the downloaded CVD into a directory""" |
| 150 | + out_dir = self.db_dir / "extracted" |
| 151 | + self.extract_cvd_dir = extract_cvd(self.db_dir / "main.cvd", out_dir) |
| 152 | + self.log(f"Extracted CVD to {self.extract_cvd_dir}") |
| 153 | + |
| 154 | + def collect_and_store_advisories(self): |
| 155 | + """Parse .ndb and .hdb files and store rules in the DB.""" |
| 156 | + rules = {} |
| 157 | + for entry in parse_hdb_file(self.extract_cvd_dir / "main.hdb") + parse_ndb_file( |
| 158 | + self.extract_cvd_dir / "main.ndb" |
| 159 | + ): |
| 160 | + name = entry.get("name", "") |
| 161 | + cve = extract_cve_id(name) |
| 162 | + if cve: |
| 163 | + rules[cve] = entry |
| 164 | + |
| 165 | + rules_added = 0 |
| 166 | + for cve_id, rule_text in rules.items(): |
| 167 | + advisories = set() |
| 168 | + try: |
| 169 | + if alias := AdvisoryAlias.objects.get(alias=cve_id): |
| 170 | + for adv in alias.advisories.all(): |
| 171 | + advisories.add(adv) |
| 172 | + except AdvisoryAlias.DoesNotExist: |
| 173 | + self.log(f"Advisory {cve_id} not found.") |
| 174 | + continue |
| 175 | + |
| 176 | + for advisory in advisories: |
| 177 | + AdvisoryDetectionRule.objects.update_or_create( |
| 178 | + advisory=advisory, |
| 179 | + rule_type="clamav", |
| 180 | + defaults={ |
| 181 | + "rule_text": str(rule_text), |
| 182 | + }, |
| 183 | + ) |
| 184 | + |
| 185 | + rules_added += 1 |
| 186 | + self.log(f"Successfully added/updated {rules_added} rules for advisories.") |
| 187 | + |
| 188 | + def clean_downloads(self): |
| 189 | + """Clean up downloaded files.""" |
| 190 | + if getattr(self, "db_dir", None) and os.path.exists(self.db_dir): |
| 191 | + shutil.rmtree(self.db_dir, ignore_errors=True) |
| 192 | + self.log("Cleaned up downloaded files.") |
| 193 | + |
| 194 | + def on_failure(self): |
| 195 | + """Ensure cleanup on failure.""" |
| 196 | + self.clean_downloads() |
0 commit comments