summaryrefslogtreecommitdiffstats
path: root/bin/tracker_data.py
blob: b5f15c3976ea2a38f56c73c4b24d4d5db772615e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# Copyright 2015 Raphael Hertzog <hertzog@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 json
import os.path
import re
import subprocess

import requests
import six


class TrackerData(object):
    DATA_URL = "https://security-tracker.debian.org/tracker/data/json"
    GIT_URL = "https://salsa.debian.org/security-tracker-team/security-tracker.git"
    CACHED_DATA_PATH = "~/.cache/debian_security_tracker.json"
    CACHED_REVISION_PATH = "~/.cache/debian_security_tracker.rev"
    GET_REVISION_COMMAND = \
        "LC_ALL=C git ls-remote %s | awk '/HEAD$/ { print $1 }'" % GIT_URL
    DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')

    def __init__(self, update_cache=True):
        self._latest_revision = None
        self.cached_data_path = os.path.expanduser(self.CACHED_DATA_PATH)
        self.cached_revision_path = os.path.expanduser(
            self.CACHED_REVISION_PATH)
        if update_cache:
            self.update_cache()
        self.load()

    @property
    def latest_revision(self):
        """Return the current revision of the Git repository"""
        # Return cached value if available
        if self._latest_revision is not None:
            return self._latest_revision
        # Otherwise call out to git to get the latest revision
        output = subprocess.check_output(self.GET_REVISION_COMMAND,
                                         shell=True)
        self._latest_revision = output.strip()
        return self._latest_revision

    def _cache_must_be_updated(self):
        """Verify if the cache is out of date"""
        if os.path.exists(self.cached_data_path) and os.path.exists(
                self.cached_revision_path):
            with open(self.cached_revision_path, 'r') as f:
                try:
                    revision = f.read()
                except ValueError:
                    revision = None
            if revision == self.latest_revision:
                return False
        return True

    def update_cache(self):
        """Update the cached data if it's out of date"""
        if not self._cache_must_be_updated():
            return

        print("Updating {} from {} ...".format(self.CACHED_DATA_PATH,
                                               self.DATA_URL))
        response = requests.get(self.DATA_URL, allow_redirects=True)
        response.raise_for_status()
        with open(self.cached_data_path, 'w') as cache_file:
            cache_file.write(response.text)
        with open(self.cached_revision_path, 'w') as rev_file:
            rev_file.write('{}'.format(self.latest_revision))

    def load(self):
        with open(self.cached_data_path, 'r') as f:
            self.data = json.load(f)
        self.load_dsa_dla_needed()
        self.load_point_updates()

    @classmethod
    def parse_needed_file(self, inputfile):
        PKG_RE = '^(\S+)(?:\s+\((.*)\))?$'
        SEP_RE = '^--$'
        state = 'LOOK_FOR_SEP'
        result = {}
        package = ''
        for line in inputfile:
            # Always strip whitespace from end of line
            line = line.rstrip()
            if state == 'LOOK_FOR_SEP':
                res = re.match(SEP_RE, line)
                if not res:
                    if package:
                        result[package]['more'] += '\n' + line
                    continue
                package = ''
                state = 'LOOK_FOR_PKG'
            elif state == 'LOOK_FOR_PKG':
                res = re.match(PKG_RE, line)
                if res:
                    package = res.group(1)
                    result[package] = {
                        'taken_by': res.group(2),
                        'more': '',
                    }
                state = 'LOOK_FOR_SEP'
        return result

    def load_dsa_dla_needed(self):
        with open(os.path.join(self.DATA_DIR, 'dsa-needed.txt'), 'r') as f:
            self.dsa_needed = self.parse_needed_file(f)
        with open(os.path.join(self.DATA_DIR, 'dla-needed.txt'), 'r') as f:
            self.dla_needed = self.parse_needed_file(f)

    @classmethod
    def parse_point_update_file(self, inputfile):
        CVE_RE = 'CVE-[0-9]{4}-[0-9X]{4}'
        result = {}
        for line in inputfile:
            res = re.match(CVE_RE, line)
            if res:
                cve = res.group(0)
                result[cve] = {}
                continue
            elif line.startswith('\t['):
                dist, _, pkg, ver = line.split()
                result[cve][pkg] = ver
        return result

    def load_point_updates(self):
        with open(os.path.join(self.DATA_DIR, 'next-oldstable-point-update.txt'), 'r') as f:
            self.oldstable_point_update = self.parse_point_update_file(f)
        with open(os.path.join(self.DATA_DIR, 'next-point-update.txt'), 'r') as f:
            self.stable_point_update = self.parse_point_update_file(f)

    def iterate_packages(self):
        """Iterate over known packages"""
        for pkg in self.data:
            yield pkg

    def iterate_pkg_issues(self, pkg):
        for id, data in six.iteritems(self.data[pkg]):
            data['package'] = pkg
            yield Issue(id, data)

class IssueStatus(object):

    def __init__(self, status, reason=None):
        self.status = status
        self.reason = reason

    def __str__(self):
        return str((self.status, self.reason))

class Issue(object):
    '''Status of a security issue'''

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def get_status(self, release):
        data = self.data['releases'].get(release)
        if data is None:
            status = 'not-affected'
            # XXX: ask for data to differentiate between "package not in
            # release" and "package not-affected"
            reason = 'unknown'
        elif data['status'] == 'resolved':
            status = 'resolved'
            reason = 'fixed in {}'.format(
                self.data['releases'][release]['fixed_version'])
        elif data.get('nodsa_reason', None) == 'ignored':
            status = 'ignored'
            reason = 'no-dsa'
        elif data['status'] == 'undetermined':
            status = 'ignored'
            reason = 'undetermined'
        elif 'nodsa' in data:
            status = 'ignored'
            reason = 'no-dsa'
        elif data['urgency'] == 'unimportant':
            status = 'ignored'
            reason = 'unimportant'
        elif data['urgency'] == 'end-of-life':
            status = 'ignored'
            reason = 'unsupported'
        else:
            status = 'open'
            reason = 'nobody fixed it yet'
        return IssueStatus(status, reason)

© 2014-2024 Faster IT GmbH | imprint | privacy policy