#!/usr/bin/python3
#
# Look for all CVEs issued by a CNA and report their NFU status in
# the security tracker.
#
# Copyright © 2025 Emilio Pozuelo Monfort <pochu@debian.org>
#
# This file is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file.  If not, see <https://www.gnu.org/licenses/>.

import argparse
import collections
import json
import logging
import os
import sys
import zipfile

import requests

import setup_paths  # noqa
from sectracker import parsers

logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s')
#logging.getLogger().setLevel("DEBUG")

def debug(s):
    if args.verbose:
        print(s)

def get_cve5(cve_id):
    global cve5_zip

    if cve_id not in cve5s:
        return None

    fname = cve5s[cve_id]

    logging.info('loading file')
    f = cve5_zip.open(fname)
    logging.info('loading json')
    return json.load(f)

def read_cve5_file(f):
    cve5s = {}

    z = zipfile.ZipFile(cve5_file)
    for fname in z.namelist():
        if os.path.basename(fname).startswith('CVE-'):
            debug("found record " + fname)
            cve_id = os.path.basename(fname)[:-5]
            cve5s[cve_id] = fname

    return cve5s

def parse_cves():
    cvelist = parsers.cvelist(datafile)

    # we want to use a dict to easily lookup and replace a cve, but we need
    # to keep order from the list above for when we write the keys back.
    cves = collections.OrderedDict()
    for cve in cvelist:
        name = cve.header.name
        # skip temporary entries, we can't get CVE5 for them
        if 'XXXX' in name:
            continue

        cves[name] = cve

    return cves


parser = argparse.ArgumentParser(description="check issues from a specific CNA")
parser.add_argument('-c', '--cna', help='CNA short name')
parser.add_argument('-D', '--no-download', action='store_true',
                    help='Skip downloading files')
parser.add_argument('-v', '--verbose', action='store_true',
                    help='Verbose mode')

args = parser.parse_args()

cve5_file_url = 'https://github.com/CVEProject/cvelistV5/archive/refs/heads/main.zip'
cve5_file = 'mitre.zip'
datafile = "data/CVE/list"

if not args.no_download:
    debug("downloading files...")

    r = requests.get(cve5_file_url)
    with open(cve5_file, "wb") as f:
        f.write(r.content)

# used by read_cve5, used as a global so that we don't have to open the
# file repeatedly, since we only read cve5s one by one on demand
cve5_zip = zipfile.ZipFile(cve5_file)

# We have CVE 5.0 JSON information coming from MITRE, we use cve5 for those
# We also have CVE information coming from our data/CVE/list, we use cve there
cves = parse_cves()
cve5s = read_cve5_file(cve5_file)

cves_from_cna = 0
cves_from_cna_with_packages = 0

for name, cve in cves.items():
    if cve5 := get_cve5(name):
        try:
            if cve5['containers']['cna']['providerMetadata']['shortName'] == args.cna:
                cves_from_cna += 1

                # we don't check for NFU, as a CVE could be REJECTED or RESERVED.
                # And it could be both RESERVED and still have a package assigned.
                # So let's just check if it has a package, and flag those.
                package_ann = [ann for ann in cve.annotations if isinstance(ann, parsers.PackageAnnotation)]
                if package_ann:
                    cves_from_cna_with_packages += 1
                    products = [affected['product'] for affected in cve5['containers']['cna']['affected']]
                    products = ", ".join(products)
                    sources = [ann.package for ann in cve.annotations if isinstance(ann, parsers.PackageAnnotation) and not ann.release]
                    sources = ", ".join(sources)
                    print(f"{name}: upstream: {products}; debian: {sources}")
        except KeyError:
            # Some CVE5s don't have enough information, ignore them
            pass

print(f"Total CVEs from {args.cna}: {cves_from_cna}")
print(f"Total CVEs from {args.cna} with packages assigned: {cves_from_cna_with_packages}")
