aboutsummaryrefslogtreecommitdiff
blob: 28b8901629bca7d463f8fd18c01382203c5c0116 (plain)
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
#!/usr/bin/env python3
# Copyright 2016 Alex Legler
# Distributed under the terms of the GNU General Public License v3

import json
import re
import string
import sys
import os
import httplib2
from urllib.parse import urlencode
from base64 import b64encode

URI_BASE = 'https://glsamaker.gentoo.org'

class CVETool:
    """ Interface to GLSAMaker's CVETool """

    CVEPlaceholderText = (
        "** RESERVED ** This candidate has been reserved by an "
        "organization or individual that will use it when announcing a "
        "new security problem. When the candidate has been publicized, "
        "the details for this candidate will be provided."
    )

    class NotFoundError(RuntimeError):
        pass

    def __init__(self, auth, command, args):
        self.auth = auth

        if command == 'info':
            if len(args) != 1:
                print('Usage: info <CVE>')
                print('Retrieves information about a CVE from database')
                sys.exit(1)

            try:
                self.info(self.cleanup_cve(sys.argv[2]))
            except ValueError:
                print('"{}" is not a valid CVE identifier!'.format(sys.argv[2]))
                sys.exit(1)
        elif command == 'assign':
            if len(args) < 2:
                print('Usage: assign <bug> <CVE> [<CVE>...]')
                print('Assigns a set of CVEs to a bug')
                sys.exit(1)

            self.assign(args[0], [self.cleanup_cve(cve) for cve in args[1:]])
        elif command == 'new':
            if len(args) != 1:
                print('Usage: new <CVE>')
                print('Adds a new CVE to database with placeholder text')
                sys.exit(1)

            try:
                self.new(self.cleanup_cve(sys.argv[2]))
            except ValueError:
                print('"{}" is not a valid CVE identifier!'.format(sys.argv[2]))
                sys.exit(1)
        elif command == 'nfu':
            if len(args) != 1:
                print('Usage: nfu <CVE>')
                print('Marks a CVE as not-for-us')
                sys.exit(1)

            self.nfu(self.cleanup_cve(args[0]))
        elif command == 'pw':
            if len(sys.argv) != 4:
                print('Usage: pw <user> <password>')
                print('Generates a base64-encoded credential for storing')
                sys.exit(1)

            self.pw(sys.argv[2], sys.argv[3])
        else:
            self.usage(sys.argv[0])
            sys.exit(1)

    def info(self, cve):
        try:
            data = self.json_request('/cve/info/' + cve + '.json')
        except self.NotFoundError as e:
            print('{} not found in Gentoo\'s CVE database!'.format(cve))
            sys.exit(0)

        print('    CVE ID: ' + data['cve_id'] + ' (#' + str(data['id']) + ')')
        print('   Summary: ' + data['summary'])
        print(' Published: ' + (data['published_at'] if data['published_at'] is not None else "Not yet published"))
        print('-' * 80)
        print('     State: ' + data['state'])
        print('      Bugs: ' + ' , '.join(['https://bugs.gentoo.org/' + str(bug) for bug in data['bugs']]))

    def assign(self, bug, cves):
        cve_ids = [self.get_internal_cve_id(cve) for cve in cves]
        response = self.request('/cve/assign/?bug=' + str(bug) + '&cves=' + ','.join([str(c) for c in cve_ids]))

        if (response == 'ok'):
            print('Assigned bug {} to {}'.format(str(bug), ', '.join(cves)))
        else:
            print('Assigning likely failed: ' + response)
            sys.exit(1)

    def new(self, cve):
        queryString = urlencode({ 'cve_id' : cve, 'summary' : self.CVEPlaceholderText })

        try:
             response = self.request('/cve/new/?' + str(queryString), 'POST')
        except RuntimeError as e:
            try:
                data = self.json_request('/cve/info/' + cve + '.json')
                print('Adding CVE "{}" to database failed: CVE already exists!'.format(cve))
                sys.exit(0)
            except self.NotFoundError:
                print('Adding CVE "{}" to database failed for unknown reason:'.format(cve))
                raise

        if (response == 'ok'):
            print('New CVE "{}" added to database'.format(cve))
        else:
            # Should never get here because HTTP API currently returns HTTP code 500
            # which triggers a RuntimeError in request function
            print('Adding CVE "{}" to database failed: '.format(cve) + response)
            sys.exit(1)

    def nfu(self, cve):
        cve_id = self.get_internal_cve_id(cve)
        response = self.request('/cve/nfu/?cves=' + str(cve_id) + '&reason=')

        if (response == 'ok'):
            print('Marked {} as NFU'.format(cve))
        else:
            print('Assigning likely failed: ' + response)
            sys.exit(1)

    def usage(self, programname):
        """ Print usage information """
        print('Usage: {} <command> <cve> [args]'.format(programname))
        print('CLI for CVETool.')

    def pw(self, user, password):
        print(b64encode(bytes(user + ':' + password, 'utf-8')).decode('ascii'))

    def get_internal_cve_id(self, cve):
        """ Resolves a CVE id to the internal databse ID """
        return self.json_request('/cve/info/' + cve + '.json')['id']

    def json_request(self, uri, method='GET'):
        return json.loads(self.request(uri, method))

    def cleanup_cve(self, str):
        regex = re.compile('^(CVE-)?\d{4}-\d{4,}$')
        if not regex.match(str):
            raise ValueError('Cannot parse CVE: ' + str)

        if not str.startswith('CVE-'):
            return 'CVE-' + str
        else:
            return str

    def request(self, uri, method='GET'):
        client = httplib2.Http('.cache')
        full_uri = URI_BASE + uri
        response, content = client.request(full_uri, method, headers = { 'Authorization': 'Basic ' + self.auth })

        status = response['status']
        if (status == '404'):
            raise self.NotFoundError(full_uri + ': ' + status)
        elif (status[0] != '2' and status != '304'):
            raise RuntimeError(full_uri + ': ' + status)

        return content.decode('utf-8')

def main():
    if len(sys.argv) == 1:
        CVETool(None, 'usage', sys.argv[2:])

    if not 'CVETOOL_AUTH' in os.environ and not sys.argv[1] == 'pw':
        print('CVETOOL_AUTH environment variable missing. Generate its contents with the pw subcommand.')
        sys.exit(1)

    auth = None
    if 'CVETOOL_AUTH' in os.environ:
        auth = os.environ['CVETOOL_AUTH']

    CVETool(auth, sys.argv[1], sys.argv[2:])

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print('\n ! Exiting.')