|
| 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 json |
| 11 | +import logging |
| 12 | +from typing import Iterable |
| 13 | + |
| 14 | +import requests |
| 15 | +from packageurl import PackageURL |
| 16 | +from univers.version_range import AlpineLinuxVersionRange |
| 17 | +from univers.versions import InvalidVersion |
| 18 | + |
| 19 | +from vulnerabilities.importer import AdvisoryDataV2 |
| 20 | +from vulnerabilities.importer import AffectedPackageV2 |
| 21 | +from vulnerabilities.importer import ReferenceV2 |
| 22 | +from vulnerabilities.importer import VulnerabilitySeverity |
| 23 | +from vulnerabilities.pipelines import VulnerableCodeBaseImporterPipelineV2 |
| 24 | +from vulnerabilities.severity_systems import SCORING_SYSTEMS |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | +ALPINE_SECURITY_ROOT = "https://security.alpinelinux.org/" |
| 29 | +BRANCH_URL = "https://security.alpinelinux.org/branch/{branch}" |
| 30 | +ADVISORY_HEADERS = {"Accept": "application/ld+json"} |
| 31 | + |
| 32 | +# EOL branches with data that no longer appear in the root API index. |
| 33 | +# 3.13 through 3.16 are omitted because the API returns 0 items for them. |
| 34 | +HISTORICAL_BRANCHES = [ |
| 35 | + "3.22-community", |
| 36 | + "3.18-main", |
| 37 | + "3.17-main", |
| 38 | + "3.12-main", |
| 39 | + "3.11-main", |
| 40 | + "3.10-main", |
| 41 | +] |
| 42 | + |
| 43 | + |
| 44 | +def get_branches() -> list: |
| 45 | + """Discover active branches from the root API and append HISTORICAL_BRANCHES.""" |
| 46 | + try: |
| 47 | + resp = requests.get(ALPINE_SECURITY_ROOT, headers=ADVISORY_HEADERS, timeout=30) |
| 48 | + resp.raise_for_status() |
| 49 | + data = resp.json() |
| 50 | + # Branch entries have dict values; scalar values indicate non-branch keys. |
| 51 | + active = [k for k, v in data.items() if isinstance(v, dict)] |
| 52 | + except Exception as e: |
| 53 | + logger.error("Failed to discover branches from root API: %s", e) |
| 54 | + active = [] |
| 55 | + |
| 56 | + seen = set(active) |
| 57 | + return active + [b for b in HISTORICAL_BRANCHES if b not in seen] |
| 58 | + |
| 59 | + |
| 60 | +class AlpineSecurityImporterPipeline(VulnerableCodeBaseImporterPipelineV2): |
| 61 | + """Collect Alpine Linux advisories from https://security.alpinelinux.org/.""" |
| 62 | + |
| 63 | + pipeline_id = "alpine_security_importer" |
| 64 | + spdx_license_expression = "CC-BY-SA-4.0" |
| 65 | + license_url = "https://security.alpinelinux.org/" |
| 66 | + precedence = 200 |
| 67 | + |
| 68 | + @classmethod |
| 69 | + def steps(cls): |
| 70 | + return (cls.collect_and_store_advisories,) |
| 71 | + |
| 72 | + def advisories_count(self) -> int: |
| 73 | + count = 0 |
| 74 | + for branch in get_branches(): |
| 75 | + url = BRANCH_URL.format(branch=branch) |
| 76 | + try: |
| 77 | + resp = requests.get(url, headers=ADVISORY_HEADERS, timeout=30) |
| 78 | + resp.raise_for_status() |
| 79 | + data = resp.json() |
| 80 | + except Exception as e: |
| 81 | + logger.error("Failed to fetch branch %s: %s", branch, e) |
| 82 | + continue |
| 83 | + count += len(data.get("items") or []) |
| 84 | + return count |
| 85 | + |
| 86 | + def collect_advisories(self) -> Iterable[AdvisoryDataV2]: |
| 87 | + for branch in get_branches(): |
| 88 | + url = BRANCH_URL.format(branch=branch) |
| 89 | + try: |
| 90 | + resp = requests.get(url, headers=ADVISORY_HEADERS, timeout=30) |
| 91 | + resp.raise_for_status() |
| 92 | + data = resp.json() |
| 93 | + except Exception as e: |
| 94 | + logger.error("Failed to fetch branch %s: %s", branch, e) |
| 95 | + continue |
| 96 | + for item in data.get("items") or []: |
| 97 | + advisory = parse_advisory(item) |
| 98 | + if advisory: |
| 99 | + yield advisory |
| 100 | + |
| 101 | + |
| 102 | +def parse_advisory(data: dict): |
| 103 | + """Parse a JSON-LD advisory; return None if the advisory ID is missing.""" |
| 104 | + cve_url = data.get("id") or "" |
| 105 | + cve_id = cve_url.rstrip("/").split("/")[-1] |
| 106 | + if not cve_id: |
| 107 | + return None |
| 108 | + |
| 109 | + summary = data.get("description") or "" |
| 110 | + |
| 111 | + references = [] |
| 112 | + for ref in data.get("ref") or []: |
| 113 | + ref_url = ref.get("rel") or "" |
| 114 | + if ref_url: |
| 115 | + references.append(ReferenceV2(url=ref_url)) |
| 116 | + |
| 117 | + severities = [] |
| 118 | + cvss3 = data.get("cvss3") or {} |
| 119 | + cvss_score = cvss3.get("score") |
| 120 | + cvss_vector = cvss3.get("vector") or "" |
| 121 | + if cvss_vector and cvss_score: |
| 122 | + if cvss_vector.startswith("CVSS:3.1/"): |
| 123 | + system = SCORING_SYSTEMS["cvssv3.1"] |
| 124 | + else: |
| 125 | + system = SCORING_SYSTEMS["cvssv3"] |
| 126 | + severities.append( |
| 127 | + VulnerabilitySeverity( |
| 128 | + system=system, |
| 129 | + value=str(cvss_score), |
| 130 | + scoring_elements=cvss_vector, |
| 131 | + ) |
| 132 | + ) |
| 133 | + |
| 134 | + affected_packages = [] |
| 135 | + for state in data.get("state") or []: |
| 136 | + if not state.get("fixed"): |
| 137 | + continue |
| 138 | + pkg_version_url = state.get("packageVersion") or "" |
| 139 | + repo = state.get("repo") or "" |
| 140 | + parts = pkg_version_url.rstrip("/").split("/") |
| 141 | + if len(parts) < 2: |
| 142 | + continue |
| 143 | + pkg_name = parts[-2] |
| 144 | + version = parts[-1] |
| 145 | + if not pkg_name or not version: |
| 146 | + continue |
| 147 | + repo_parts = repo.split("-", 1) |
| 148 | + if len(repo_parts) != 2: |
| 149 | + continue |
| 150 | + version_tag, reponame = repo_parts |
| 151 | + distroversion = version_tag if version_tag == "edge" else f"v{version_tag}" |
| 152 | + purl = PackageURL( |
| 153 | + type="apk", |
| 154 | + namespace="alpine", |
| 155 | + name=pkg_name, |
| 156 | + qualifiers={"distroversion": distroversion, "reponame": reponame}, |
| 157 | + ) |
| 158 | + try: |
| 159 | + fixed_version_range = AlpineLinuxVersionRange.from_versions([version]) |
| 160 | + except InvalidVersion: |
| 161 | + logger.warning("Cannot parse Alpine version %r in %s", version, cve_id) |
| 162 | + continue |
| 163 | + affected_packages.append( |
| 164 | + AffectedPackageV2( |
| 165 | + package=purl, |
| 166 | + fixed_version_range=fixed_version_range, |
| 167 | + ) |
| 168 | + ) |
| 169 | + |
| 170 | + return AdvisoryDataV2( |
| 171 | + advisory_id=cve_id, |
| 172 | + aliases=[], |
| 173 | + summary=summary, |
| 174 | + affected_packages=affected_packages, |
| 175 | + references=references, |
| 176 | + severities=severities, |
| 177 | + url=cve_url, |
| 178 | + original_advisory_text=json.dumps(data, indent=2, ensure_ascii=False), |
| 179 | + ) |
0 commit comments