#!/bin/sh
# Look for the CVEs affecting a RouterOS version, using a local CVE database
# (routeros_cves.json in the current directory) so that the NVD API is not
# queried. The test database contains CVEs with explicit version ranges and
# CVEs whose ranges are extracted from their description.

set -eu

cd "$AUTOPKGTEST_TMP"

cat > routeros_cves.json <<'EOF'
[
  {
    "cve_id": "CVE-0000-0001",
    "description": "Test CVE affecting RouterOS 6.0 up to 6.49.7 (excluded).",
    "severity": "CRITICAL",
    "cvss_score": 9.8,
    "published": "2000-01-01T00:00:00.000",
    "affected_versions": [
      {
        "criteria": "cpe:2.3:o:mikrotik:routeros:*:*:*:*:*:*:*:*",
        "versionStartIncluding": "6.0",
        "versionStartExcluding": null,
        "versionEndIncluding": null,
        "versionEndExcluding": "6.49.7"
      }
    ]
  },
  {
    "cve_id": "CVE-0000-0002",
    "description": "Test CVE affecting RouterOS 7.0 up to 7.10 (excluded).",
    "severity": "HIGH",
    "cvss_score": 7.5,
    "published": "2000-01-02T00:00:00.000",
    "affected_versions": [
      {
        "criteria": "cpe:2.3:o:mikrotik:routeros:*:*:*:*:*:*:*:*",
        "versionStartIncluding": "7.0",
        "versionStartExcluding": null,
        "versionEndIncluding": null,
        "versionEndExcluding": "7.10"
      }
    ]
  },
  {
    "cve_id": "CVE-0000-0003",
    "description": "MikroTik RouterOS before 6.48 allows a test attack.",
    "severity": "MEDIUM",
    "cvss_score": 5.3,
    "published": "2000-01-03T00:00:00.000",
    "affected_versions": []
  },
  {
    "cve_id": "CVE-0000-0004",
    "description": "MikroTik RouterOS before 6.49.8 allows another test attack.",
    "severity": "LOW",
    "cvss_score": 3.1,
    "published": "2000-01-04T00:00:00.000",
    "affected_versions": []
  }
]
EOF

# sara asks whether to refresh the existing CVE database from NVD
echo no | sara cve version 6.49.6 > output.txt
cat output.txt

for cve in CVE-0000-0001 CVE-0000-0004; do
    if ! grep -qF "$cve" output.txt; then
        echo "FAIL: $cve affects RouterOS 6.49.6 but was not reported"
        exit 1
    fi
done
for cve in CVE-0000-0002 CVE-0000-0003; do
    if grep -qF "$cve" output.txt; then
        echo "FAIL: $cve does not affect RouterOS 6.49.6 but was reported"
        exit 1
    fi
done
