~ubuntu-security/ubuntu-cve-tracker/master

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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#!/usr/bin/python3

# Module containing classes, variables, etc. for creating OVAL content
#
# Author: David Ries <ries@jovalcm.com>
# Copyright (C) 2015 Farnam Hall Ventures LLC
#
# This script is distributed under the terms and conditions of the GNU General
# Public License, Version 2 or later. See http://www.gnu.org/copyleft/gpl.html
# for details.
#
# NOTES / TODOs
# This script creates OVAL ids based on the related CVE ID but does not
# currently increment the version number of generated elements when they
# change.

import datetime
import os
import random
import re
import shutil
import sys
import tempfile
from xml.sax.saxutils import escape


def recursive_rm(dirPath):
    '''recursively remove directory'''
    names = os.listdir(dirPath)
    for name in names:
        path = os.path.join(dirPath, name)
        if not os.path.isdir(path):
            os.unlink(path)
        else:
            recursive_rm(path)
    os.rmdir(dirPath)


class OvalGenerator:
    supported_oval_elements = ('definition', 'test', 'object', 'state',
                               'variable')
    generator_version = 1
    oval_schema_version = '5.11.1'

    def __init__(self, release_codename, warn_method=False, outdir='./'):
        """ constructor, set defaults for instances """

        self.release_codename = release_codename
        self.warn = warn_method or self.warn
        self.tmpdir = tempfile.mkdtemp(prefix='oval_lib-')
        self.output_dir = outdir
        self.output_filepath = \
            'com.ubuntu.{0}.cve.oval.xml'.format(self.release_codename)
        self.ns = 'oval:com.ubuntu.{0}'.format(self.release_codename)

    def __del__(self):
        """ deconstructor, clean up """
        if os.path.exists(self.tmpdir):
            recursive_rm(self.tmpdir)

    def generate_cve_definition(self, cve):
        """ generate an OVAL definition based on parsed CVE data """

        header = cve['header']
        id_base = int(re.sub('[^0-9]', '', header['Candidate'])) * 100
        if not self.unique_id_base(id_base, header['Source-note']):
            self.warn('Calculated id_base "{0}" based on candidate value "{1}" is not unique. Skipping CVE.'.format(id_base, header['Candidate']))

        # make test(s) for each package
        test_refs = []
        packages = cve['packages']
        for package in sorted(packages.keys()):
            releases = packages[package]['Releases']
            for release in sorted(releases.keys()):
                if release == self.release_codename:
                    release_status = releases[release]
                    test_ref = self.get_oval_test_for_package({
                        'name': package,
                        'status': release_status['status'],
                        'note': release_status['note'],
                        'fix-version': release_status['fix-version'] if 'fix-version' in release_status else '',
                        'id_base': id_base + len(test_refs),
                        'source-note': header['Source-note']
                    })
                    if test_ref:
                        test_refs.append(test_ref)

        # if no packages for this release, then we're done
        if not len(test_refs):
            return False

        # convert CVE data to OVAL definition metadata
        mapping = {
            'ns': escape(self.ns),
            'id_base': id_base,
            'codename': escape(self.release_codename),
            'release_version': escape(self.release_version),
            'applicability_def_id': escape(
                self.release_applicability_definition_id),
            'cve_title': escape(header['Candidate']),
            'description': escape('{0} {1}'.format(header['Description'],
                                  header['Ubuntu-Description']).strip()),
            'priority': escape(header['Priority']),
            'criteria': '',
            'references': '',
            'notes': ''
        }

        # convert test_refs to criteria
        if len(test_refs) == 1:
            negation_attribute = 'negate = "true" ' \
                if 'negate' in test_refs[0] and test_refs[0]['negate'] else ''
            mapping['criteria'] = \
                '<criterion test_ref="{0}" comment="{1}" {2}/>'.format(
                    test_refs[0]['id'], escape(test_refs[0]['comment']), negation_attribute)
        else:
            criteria = []
            criteria.append('<criteria operator="OR">')
            for test_ref in test_refs:
                negation_attribute = 'negate = "true" ' \
                    if 'negate' in test_ref and test_ref['negate'] else ''
                criteria.append(
                    '    ' +
                    '<criterion test_ref="{0}" comment="{1}" {2}/>'.format(
                        test_ref['id'],
                        escape(test_ref['comment']), negation_attribute))
            criteria.append('</criteria>')
            mapping['criteria'] = '\n                    '.join(criteria)

        # convert notes
        if header['Notes']:
            mapping['notes'] = '\n                <oval:notes>' + \
                               '\n                    <oval:note>{0}</oval:note>'.format(escape(header['Notes'])) + \
                               '\n                </oval:notes>'

        # convert additional data <advisory> metadata elements
        advisory = []
        advisory.append('<severity>{0}</severity>'.format(
            escape(header['Priority'].title())))
        advisory.append(
            '<rights>Copyright (C) {0}Canonical Ltd.</rights>'.format(escape(
                header['PublicDate'].split('-', 1)[0] + ' '
                if header['PublicDate'] else '')))
        if header['PublicDate']:
            advisory.append('<public_date>{0}</public_date>'.format(
                escape(header['PublicDate'])))
        if header['PublicDateAtUSN']:
            advisory.append(
                '<public_date_at_usn>{0}</public_date_at_usn>'.format(escape(
                    header['PublicDateAtUSN'])))
        if header['Assigned-to']:
            advisory.append('<assigned_to>{0}</assigned_to>'.format(escape(
                header['Assigned-to'])))
        if header['Discovered-by']:
            advisory.append('<discovered_by>{0}</discovered_by>'.format(escape(
                header['Discovered-by'])))
        if header['CRD']:
            advisory.append('<crd>{0}</crd>'.format(escape(header['CRD'])))
        for bug in header['Bugs']:
            advisory.append('<bug>{0}</bug>'.format(escape(bug)))
        for ref in header['References']:
            if ref.startswith('https://cve.mitre'):
                cve_title = ref.split('=')[-1].strip()
                if not cve_title:
                    continue
                mapping['cve_title'] = escape(cve_title)
                mapping['references'] = '\n                    <reference source="CVE" ref_id="{0}" ref_url="{1}" />'.format(mapping['cve_title'], escape(ref))
            else:
                advisory.append('<ref>{0}</ref>'.format(escape(ref)))
        mapping['advisory_elements'] = '\n                        '.join(advisory)

        self.queue_element('definition', """
            <definition class="vulnerability" id="{ns}:def:{id_base}0" version="1">
                <metadata>
                    <title>{cve_title} on Ubuntu {release_version} ({codename}) - {priority}.</title>
                    <description>{description}</description>
                    <affected family="unix">
                        <platform>Ubuntu {release_version}</platform>
                    </affected>{references}
                    <advisory>
                        {advisory_elements}
                    </advisory>
                </metadata>{notes}
                <criteria>
                    <extend_definition definition_ref="{applicability_def_id}" comment="Ubuntu {release_version} ({codename}) is installed." applicability_check="true" />
                    {criteria}
                </criteria>
            </definition>
""".format(**mapping))

    def get_oval_test_for_package(self, package):
        """ create OVAL test and dependent objects for this package status
                @package = {
                    'name'          : '<package name>',
                    'status'        : '<not-applicable | unknown | vulnerable | fixed>',
                    'note'          : '<a description of the status>',
                    'fix-version'   : '<the version in which the issue was fixed, if applicable>',
                    'id_base'       : a base for the integer section of the OVAL id,
                    'source-note'   : a note about the datasource for debugging
                }
        """

        if package['status'] == 'fixed' and not package['fix-version']:
            self.warn('"{0}" package in {1} is marked fixed, but missing a fix-version. Changing status to unknown.'.format(package['name'], package['source-note']))
            package['status'] = 'unknown'

        if package['status'] == 'not-applicable':
            # if the package status is not-applicable, skip it!
            return False
        elif package['status'] == 'not-vulnerable':
            object_id = self.get_package_object_id(package['name'],
                                                   package['id_base'], 1)
            test_id = '{0}:tst:{1}0'.format(self.ns, package['id_base'])

            self.queue_element('test', """
                <linux-def:dpkginfo_test id="{0}" version="{1}" check_existence="any_exist" check="all" comment="Returns true whether or not the '{2}' package exists.">
                    <linux-def:object object_ref="{3}"/>
                </linux-def:dpkginfo_test>
""".format(test_id, 1, package['name'], object_id))

            return {'id': test_id, 'comment': package['note'], 'negate': True}
        elif package['status'] == 'vulnerable':
            object_id = self.get_package_object_id(package['name'],
                                                   package['id_base'], 1)
            test_id = '{0}:tst:{1}0'.format(self.ns, package['id_base'])

            self.queue_element('test', """
                <linux-def:dpkginfo_test id="{0}" version="{1}" check_existence="at_least_one_exists" check="all" comment="Does the '{2}' package exist?">
                    <linux-def:object object_ref="{3}"/>
                </linux-def:dpkginfo_test>
""".format(test_id, 1, package['name'], object_id))

            return {'id': test_id, 'comment': package['note']}
        elif package['status'] == 'fixed':
            object_id = self.get_package_object_id(package['name'],
                                                   package['id_base'], 1)

            state_id = '{0}:ste:{1}0'.format(self.ns, package['id_base'])
            self.queue_element('state', """
                <linux-def:dpkginfo_state id="{0}" version="{1}" comment="The package name is '{2}' and the version is less than '{3}'.">
                    <linux-def:name>{2}</linux-def:name>
                    <linux-def:evr datatype="debian_evr_string" operation="less than">{3}</linux-def:evr>
                </linux-def:dpkginfo_state>
""".format(state_id, 1, package['name'], package['fix-version']))

            test_id = '{0}:tst:{1}0'.format(self.ns, package['id_base'])
            self.queue_element('test', """
                <linux-def:dpkginfo_test id="{0}" version="{1}" check_existence="at_least_one_exists" check="all" comment="Does the '{2}' package exist and is the version less than '{3}'?">
                    <linux-def:object object_ref="{4}" />
                    <linux-def:state state_ref="{5}" />
                </linux-def:dpkginfo_test>
""".format(test_id, 1, package['name'], package['fix-version'], object_id, state_id))

            return {'id': test_id, 'comment': package['note']}
        else:
            if package['status'] != 'unknown':
                self.warn('"{0}" is not a supported package status. Outputting for "unknown" status.'.format(package['status']))

            if not hasattr(self, 'id_unknown_test'):
                self.id_unknown_test = '{0}:tst:10'.format(self.ns)
                self.queue_element('test', """
                    <ind-def:unknown_test id="{0}" check="all" comment="The result of this test is always UNKNOWN." version="1" />
""".format(self.id_unknown_test))

            return {'id': self.id_unknown_test, 'comment': package['note']}

    def add_release_applicability_definition(self, version,
                                             kernel_version_pattern, id):
        """ add platform/release applicability OVAL definition for codename """

        mapping = {
            'ns': self.ns,
            'id_base': id,
            'codename': self.release_codename,
            'release_version': version,
            'kernel_version_pattern': kernel_version_pattern
        }
        self.release_version = version
        self.release_applicability_definition_id = \
            '{ns}:def:{id_base}0'.format(**mapping)

        self.queue_element('definition', """
            <definition class="inventory" id="{ns}:def:{id_base}0" version="1">
                <metadata>
                    <title>Check that Ubuntu {release_version} ({codename}) is installed.</title>
                    <description></description>
                </metadata>
                <criteria>
                    <criterion test_ref="{ns}:tst:{id_base}0" comment="The host is part of the unix family." />
                    <criterion test_ref="{ns}:tst:{id_base}1" comment="The host is running Ubuntu {codename}." />
                </criteria>
            </definition>
""".format(**mapping))

        self.queue_element('test', """
            <ind-def:family_test id="{ns}:tst:{id_base}0" check="at least one" check_existence="at_least_one_exists" version="1" comment="Is the host part of the unix family?">
                <ind-def:object object_ref="{ns}:obj:{id_base}0"/>
                <ind-def:state state_ref="{ns}:ste:{id_base}0"/>
            </ind-def:family_test>

            <unix-def:uname_test id="{ns}:tst:{id_base}1" check="at least one" check_existence="at_least_one_exists" version="1" comment="Is the host running Ubuntu {codename}?">
                <unix-def:object object_ref="{ns}:obj:{id_base}1"/>
                <unix-def:state state_ref="{ns}:ste:{id_base}1"/>
            </unix-def:uname_test>
""".format(**mapping))

        self.queue_element('object', """
            <ind-def:family_object id="{ns}:obj:{id_base}0" version="1" comment="The singleton family object."/>

            <unix-def:uname_object id="{ns}:obj:{id_base}1" version="1" comment="The singleton uname object."/>
""".format(**mapping))

        self.queue_element('state', """
            <ind-def:family_state id="{ns}:ste:{id_base}0" version="1" comment="The singleton family object.">
                <ind-def:family>unix</ind-def:family>
            </ind-def:family_state>

            <unix-def:uname_state id="{ns}:ste:{id_base}1" version="1" comment="Ubuntu {release_version}">
                <unix-def:os_name>Linux</unix-def:os_name>
                <unix-def:os_release operation="pattern match">{kernel_version_pattern}</unix-def:os_release>
                <unix-def:os_version operation="pattern match">Ubuntu</unix-def:os_version>
            </unix-def:uname_state>
""".format(**mapping))

    def get_package_object_id(self, name, id_base, version=1):
        """ create unique objects for each package and return their OVAL id """
        if not hasattr(self, 'package_objects'):
            self.package_objects = {}

        if name not in self.package_objects:
            object_id = '{0}:obj:{1}0'.format(self.ns, id_base)
            self.queue_element('object', """
                <linux-def:dpkginfo_object id="{0}" version="{1}" comment="The '{2}' package.">
                    <linux-def:name>{2}</linux-def:name>
                </linux-def:dpkginfo_object>
""".format(object_id, version, name))
            self.package_objects[name] = object_id

        return self.package_objects[name]

    def _open(self, fn, mode, encoding='utf-8'):
        """ open file """
        fd = None
        if sys.version_info[0] < 3:
            fd = open(fn, mode=mode)
        else:
            fd = open(fn, mode=mode, encoding=encoding)
        return fd

    def queue_element(self, element, xml):
        """ add an OVAL element to an output queue file """
        if element not in OvalGenerator.supported_oval_elements:
            self.warn('"{0}" is not a supported OVAL element.'.format(element))
            return

        if not hasattr(self, 'tmp'):
            self.tmp = {}
            self.tmp_n = random.randrange(1000000, 9999999)

        if element not in self.tmp:
            self.tmp[element] = self._open(os.path.join(self.tmpdir,
                                           './queue.{0}.{1}.xml'.format(
                                               self.tmp_n, element)), 'wt')

        # trim and fix indenting (assumes fragment is nicely indented internally)
        xml = xml.strip('\n')
        base_indent = re.match('\s*', xml).group(0)
        xml = re.sub('^{0}'.format(base_indent), '        ', xml, 0,
                     re.MULTILINE)

        self.tmp[element].write(xml + '\n')

    def write_to_file(self):
        """ dequeue all elements into one OVAL definitions file and clean up """
        # close queue files for writing and then open for reading
        for key in self.tmp:
            self.tmp[key].close()
            self.tmp[key] = self._open(self.tmp[key].name, 'rt')

        tmp = os.path.join(self.tmpdir, self.output_filepath)
        with self._open(tmp, 'wt') as f:
            # add header
            oval_timestamp = datetime.datetime.utcnow().strftime(
                '%Y-%m-%dT%H:%M:%S')
            f.write("""<oval_definitions
    xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5"
    xmlns:ind-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent"
    xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5"
    xmlns:unix-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix"
    xmlns:linux-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5 oval-definitions-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5#independent independent-definitions-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5#unix unix-definitions-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5#macos linux-definitions-schema.xsd">

    <generator>
        <oval:product_name>Canonical CVE OVAL Generator</oval:product_name>
        <oval:product_version>{0}</oval:product_version>
        <oval:schema_version>{1}</oval:schema_version>
        <oval:timestamp>{2}</oval:timestamp>
    </generator>
""".format(OvalGenerator.generator_version, OvalGenerator.oval_schema_version, oval_timestamp))

            # add queued file content
            for element in OvalGenerator.supported_oval_elements:
                if element in self.tmp:
                    f.write("\n    <{0}s>\n".format(element))
                    f.write(self.tmp[element].read().rstrip())
                    f.write("\n    </{0}s>".format(element))

            # add footer
            f.write("\n</oval_definitions>")

        # close and delete queue files
        for key in self.tmp:
            self.tmp[key].close()
            os.remove(self.tmp[key].name)

        # close self.output_filepath and move into place
        f.close()
        shutil.move(tmp, os.path.join(self.output_dir, self.output_filepath))

    def unique_id_base(self, id_base, note):
        """ queue a warning message """
        if not hasattr(self, 'id_bases'):
            self.id_bases = {}
        is_unique = id_base not in self.id_bases.keys()
        if not is_unique:
            self.warn('ID Base collision {0} in {1} and {2}.'.format(
                id_base, note, self.id_bases[id_base]))
        self.id_bases[id_base] = note
        return is_unique

    def warn(self, message):
        """ print a warning message """
        print('WARNING: {0}'.format(message))