#!/usr/bin/env python3
# Gather CVE information for front-desk triage
# Copyright (C) 2015, 2017  Raphael Hertzog <hertzog@debian.org>
# Copyright (C) 2015, 2017  Guido Günther <agx@sigxcpu.org>
# Copyright (C) 2016, 2017, 2019, 2021  Chris Lamb <lamby@debian.org>
# Copyright (C) 2016  Mike Gabriel <sunweaver@debian.org>
# Copyright (C) 2019, 2022, 2024, 2025, 2026  Sylvain Beucler <beuc@beuc.net>
# Copyright (C) 2019, 2020, 2023  Emilio Pozuelo Monfort <pochu@debian.org>
# Copyright (C) 2025  François Lesueur <flesueur@alwaysdata.com>
#
# 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/>.

# The data flow is currently complex, see:
# https://salsa.debian.org/lts-team/lts-extra-tasks/-/issues/92

import setup_paths

import sys
import argparse
import collections
import functools
import re
from apt_pkg import version_compare

from tracker_data import TrackerData
from unsupported_packages import UnsupportedPackages, LimitedSupportPackages
from debian_support import PointUpdateParser

import config

supported_releases = config.get_supported_releases()
all_releases = config.get_all_releases()
RELEASES = {}


try:
    from termcolor import colored  # noqa
except ImportError:
    print("Note: you can install python3-termcolor for colored output",
          file=sys.stderr)
    def colored(x, *args, **kwargs):
        return x


# Display links to ELTS' tracker URL which has more dists,
# to easily compare prev_lts/lts/next_lts:
#TRACKER_LINK_URL = 'https://security-tracker.debian.org/tracker/'
TRACKER_LINK_URL = 'https://deb.freexian.com/extended-lts/tracker/'

# Order: fixed in DSA > planned for DSA > LTS-specific > no-dsa > limited support > EOL
#        > consistency checks
LIST_NAMES = (
    ('triage_possible_easy_fixes',
     ('Issues not yet triaged for {lts}, but already fixed in {next_lts}')),
    ('triage_already_in_dsa_needed',
     ('Issues to triage for {lts} that are already in dsa-needed')),
    ('triage_other',
     'Unclassified issues to triage (likely LTS-specific)'),
    ('triage_likely_nodsa',
     ('Issues to triage for {lts} that are no-dsa in {next_lts}')),
    ('triage_limited_support',
     'Issues on packages with limited support (review support rules)'),
    ('triage_end_of_life',
     'Issues to mark as <end-of-life> for {lts}'),
    ('triage_other_not_triaged_in_next_lts',
     ('Other issues to triage for {lts} (not yet triaged for {next_lts})')),
    ('from_next_lts',
     ('Issues postponed for {lts}, but already fixed in {next_lts} via DSA or point releases (low priority)')),
    ('unexpected_nodsa',
     ('Issues tagged no-dsa in {lts} that are open in {next_lts}')),
    ('to_forward',
     ('Issues fixed in {lts} but not in {next_lts} (low priority) [caution: new report]'
      + '\ncf. https://salsa.debian.org/lts-team/lts-updates-tasks/-/issues/?label_name%5B%5D=%28O%29SPU ')),
    ('from_elts',
     ('Issues fixed in {prev_lts} and {next_lts} but not in {lts} [caution: new report]')),
    ('undetermined',
     ('Undetermined issues in {lts}')),
)

lists = collections.defaultdict(lambda: collections.defaultdict(lambda: []))

parser = argparse.ArgumentParser(
    description='Find CVEs to triage',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument('--skip-cache-update', action='store_true',
                    help='Skip updating the tracker data cache')
parser.add_argument('--filter', nargs='+', choices=[x[0] for x in LIST_NAMES],
                    help='Only report on specified lists')
parser.add_argument('--exclude', nargs='+', choices=[x[0] for x in LIST_NAMES],
                    help='Do not report on the specified lists')
parser.add_argument('--releases', action='store', nargs=3,
                    metavar=('prev_lts','lts','next_lts'),
                    default=[
                        all_releases[all_releases.index(supported_releases[0])-1],
                        supported_releases[0],
                        supported_releases[1]
                    ], help='Override target releases')
args = parser.parse_args()

(RELEASES['prev_lts'],RELEASES['lts'],RELEASES['next_lts'],) = args.releases
# Expand dist names in descriptions
LIST_NAMES = [(title,desc.format(**RELEASES)) for title,desc in LIST_NAMES]

tracker = TrackerData(update_cache=not args.skip_cache_update,
                      dla_dist_filter=RELEASES['lts'])
unsupported = UnsupportedPackages(codename=RELEASES['lts'],
                                  update_cache=not args.skip_cache_update)
limited = LimitedSupportPackages(codename=RELEASES['lts'],
                                 update_cache=not args.skip_cache_update)
# unsupport/limited package names can be regexps
unsupported_re = re.compile('|'.join(unsupported))
limited_re = re.compile('|'.join(limited))

secupdate_re = re.compile(r'deb\d+u\d+$')

if config.get_release_alias(RELEASES['next_lts']) == 'stable':
    pu_expected = PointUpdateParser.parseNextPointUpdateStable()
elif config.get_release_alias(RELEASES['next_lts']) == 'oldstable':
    pu_expected = PointUpdateParser.parseNextOldstablePointUpdate()
else:
    print("Error: {} is neither stable nor oldstable".format(RELEASES['next_lts']))
    raise SystemExit(1)

def add_to_list(key, pkg, cve, annotation=''):
    assert key in [l[0] for l in LIST_NAMES]
    lists[key][pkg].append((cve, annotation))

def is_next_lts_fix_explicit(issue):
    """Was the fix in stable/oldstable explicit or inherited from unstable?"""
    next_lts_fixed_version = issue.data['releases'][RELEASES['next_lts']]['fixed_version']
    if 'sid' in issue.data['releases']:
        if 'fixed_version' not in issue.data['releases']['sid']:
            # if sid is unfixed, the fix is probably explicit
            return True

        unstable_version = issue.data['releases']['sid']['fixed_version']
        is_explicit_fix = version_compare(next_lts_fixed_version, unstable_version) < 0
    else:
        # package removed from sid, use heuristic
        is_explicit_fix = re.search(secupdate_re, next_lts_fixed_version)
    return bool(is_explicit_fix)


for pkg in tracker.iterate_packages():
    if pkg in tracker.dla_needed:
        # Issues already triaged
        continue
    for issue in tracker.iterate_pkg_issues(pkg):
        status_in_lts = issue.get_status(RELEASES['lts'])
        status_in_next_lts = issue.get_status(RELEASES['next_lts'])

        if ((status_in_lts.status == 'resolved' and status_in_lts.reason != 'fixed in 0' and status_in_lts.urgency != 'unimportant')
            and (status_in_next_lts.status not in ('resolved', 'not-affected')
                 and (status_in_next_lts.status != 'ignored' or issue.data['releases'].get(RELEASES['next_lts'], {}).get('nodsa_reason', 'ignored') != 'ignored'))
            and issue.name not in pu_expected):
            note = ''
            if status_in_next_lts.status == 'open':
                note += ' [wf secteam triage]'
            add_to_list('to_forward', pkg, issue, note)

        if status_in_lts.status in ('not-affected', 'resolved'):
            continue

        elif status_in_lts.status == 'open':
            if re.fullmatch(unsupported_re, pkg):
                add_to_list('triage_end_of_life', pkg, issue)
                continue

            if re.fullmatch(limited_re, pkg):
                add_to_list('triage_limited_support', pkg, issue)
                continue

            if status_in_next_lts.status == 'open':
                if pkg in tracker.dsa_needed:
                    add_to_list('triage_already_in_dsa_needed', pkg, issue)
                else:
                    add_to_list('triage_other_not_triaged_in_next_lts',
                                pkg, issue)
            elif (status_in_next_lts.status == 'ignored' and
                    status_in_next_lts.reason == 'no-dsa'):
                add_to_list('triage_likely_nodsa', pkg, issue)
            elif status_in_next_lts.status == 'resolved':
                add_to_list('triage_possible_easy_fixes', pkg, issue)
            else:
                add_to_list('triage_other', pkg, issue)

        # status=='ignored': <no-dsa>/<postponed>/<ignored>/<unimportant>/<undetermined>
        elif status_in_lts.status == 'ignored':
            if (status_in_lts.reason == 'no-dsa' and
                    status_in_next_lts.status == 'open'):
                add_to_list('unexpected_nodsa', pkg, issue,
                            issue.data['releases'][RELEASES['lts']]['nodsa_reason'])
            elif (status_in_lts.reason == 'no-dsa' and
                    status_in_next_lts.status == 'resolved'):
                # include explicit fixes from DSA or stable/oldstable point releases
                # exclude issues explicitly ignored, and old fixes back from unstable
                nodsa_reason = issue.data['releases'][RELEASES['lts']]['nodsa_reason']
                if is_next_lts_fix_explicit(issue) and nodsa_reason != 'ignored':
                    add_to_list('from_next_lts', pkg, issue)
            elif status_in_lts.reason == 'undetermined':
                add_to_list('undetermined', pkg, issue)


tracker_elts = TrackerData(update_cache=not args.skip_cache_update,
    data_url="https://deb.freexian.com/extended-lts/tracker/data/json",
    git_url="https://salsa.debian.org/freexian-team/extended-lts/security-tracker.git",
    id="elts_tracker")

for pkg in tracker_elts.iterate_packages():
    if pkg in tracker.dla_needed:
        # Issues already triaged
        continue
    for issue in tracker_elts.iterate_pkg_issues(pkg):
        status_in_lts = issue.get_status(RELEASES['lts'])
        status_in_next_lts = issue.get_status(RELEASES['next_lts'])
        status_in_elts = issue.get_status(RELEASES['prev_lts'])

        if (    status_in_elts.status == 'resolved'
            and status_in_elts.reason != 'fixed in 0'
            and status_in_next_lts.status == 'resolved'
            and status_in_lts.status not in ('resolved', 'not-affected')
            and status_in_lts.urgency != 'unimportant'):
            annotation = issue.data['releases'][RELEASES['lts']].get('nodsa_reason','')
            if not is_next_lts_fix_explicit(issue):
                annotation += ' [{next_lts} fixed via unstable]'.format(**RELEASES)
            add_to_list('from_elts', pkg, issue, annotation)


for key, header in LIST_NAMES:
    if args.filter is not None and key not in args.filter:
        continue
    if args.exclude is not None and key in args.exclude:
        continue
    if not len(lists[key]):
        continue
    print()
    print(colored(header, attrs=('bold',)) + ':')
    for pkg in sorted(lists[key].keys()):
        print()
        alignment = 18 - len(pkg)
        print('*',
              colored(pkg, 'red', attrs=('bold', 'underline')),
              ' ' * alignment,
              colored(TRACKER_LINK_URL + 'source-package/' + pkg, 'blue'),
        )
        nb_issues = 0
        versionrsort = functools.cmp_to_key(lambda a, b: version_compare(b[0].name, a[0].name))
        for (cve, annotation) in sorted(lists[key][pkg], key=versionrsort):
            # limit very large lists such as linux'
            nb_issues += 1
            if nb_issues > 10:
                print('  - ...')
                break
            url = TRACKER_LINK_URL + cve.name
            print('  - {:16s}  {} {}'.format(
                cve.name,
                colored(url, 'blue'),
                annotation)
            )
    print()
