summaryrefslogtreecommitdiff
blob: 45914d6c81dadfa65cbac09b5526a65755af242a (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
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
#!/usr/bin/env python
# kernel-check -- Gentoo Kernel Security
# Copyright 2009-2009 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

from portage.output import blue, bold, colorize, EOutput, darkgreen #FIXME

try:
    from _emerge.userquery import userquery
    from _emerge.stdout_spinner import stdout_spinner
except ImportError:
    from _emerge import userquery #FIXME proper checking without except
    from _emerge import stdout_spinner

import getopt
import portage
import sys
import textwrap
import os

import lib.kernellib as lib

info = EOutput().einfo #FIXME
warn = EOutput().ewarn
error = EOutput().eerror
spin = stdout_spinner()

def main(argv):
    'Main function'

    try:
        opts, args = getopt.gnu_getopt(argv, 'dhnr:sv',
        ['debug', 'help', 'nocolor', 'report=', 'sync', 'verbose'])
    except getopt.GetoptError:
        usage()
        return

    for opt, arg in opts:
        if opt in ('-d', '--debug'):
            lib.DEBUG = True
        elif opt in ('-h', '--help'):
            usage()
            return
        elif opt in ('-n', '--nocolor'):
            portage.output.nocolor()
        elif opt in ('-r', '--report'):
            error('--report not yet implemented')
            return
        elif opt in ('-s', '--sync'):
            os.system('%s%s' % ('rsync -avz rsync://rbu.sh/gentoo-kernel ',
                                '/usr/portage/metadata/kernel'))
            return
        elif opt in ('-v', '--verbose'):
            lib.VERBOSE = True

    for arg in argv:
        if lib.REGEX['argument'].match(arg):
            if 'cve' in arg.lower():
                vul = lib.find_cve(arg, lib.DIR['out'])
                if not vul:
                    print_bug(arg) #FIXME
                else:
                    print_bug(vul.bugid)
            else:
                print_bug(arg)
            return

    information = dict()

    print('')
    print(darkgreen('These are the specifications of your kernel:'))
    print('')

    uname = os.uname()
    if uname[0] != 'Linux':
        error('This tool currently only works for Linux kernels.')
        error('Apparantly you are using "%s".' % uname[0]) #TODO
        return

    kernel = lib.extract_version(uname[2])
    if kernel is None:
        error('No kernel information found!')
        return

    arch = portage.settings['ARCH']
    if not arch:
        arch = '?' #FIXME

    kernel.genpatch = lib.get_genpatch(lib.PORTDIR, kernel)
    if not kernel.genpatch:
        genpatch = ''
    else:
        genpatch = '%s %s (%s)' % ('genpatch', kernel.genpatch.version,
                                   repr(kernel.genpatch))

    information = {
        'Kernel source'  : kernel.source,
        'Kernel version' : '%s-%s' % (kernel.version, kernel.revision),
        'Kernel patches' : genpatch,
        'Architecture'   : arch
    }
    print_items(information, 'Information')

    print('')
    print_items(lib.gather_configuration(), 'Configuration')

    print('\nDetermining vulnerabilities... done!') #TODO #spin
    print('')

    evaluation = lib.eval_cve_files(lib.DIR['out'], kernel, arch, None)
    if not evaluation:
        error('No kernel vulnerability files found!')
        return

    if len(evaluation.affected) is not 0:
        print_summary(evaluation.affected)

        print('Total: %s vulnerabilities (%s), Average CVSS score: %.1f\n' % (
              len(evaluation.affected), repr(evaluation), evaluation.avg_cvss))

        prompt = "Would you like to upgrade your kernel?"
        if userquery(prompt, None) == 'No':
            print('')
            print('Quitting.')
            print('')

        else:
            print('Not implemented yet...')

    else:
        print('Total: 0 vulnerabilities, Average CVSS score: 0.0\n')
        print(bold('Your kernel is not affected by any known vulnerability!'))


def print_items(category, header):
    'Indents and prints items'

    screenwidth = 120
    if portage.output.get_term_size()[1] < screenwidth:
        screenwidth = portage.output.get_term_size()[1]

    info(bold('%s:' % header))
    for item in category.keys():
        for i, string in enumerate(textwrap.wrap('%s' % category[item],
                                                 (screenwidth - 23))):
            if i is 0:
                print('%s%s%s : %s' % (' ' * 6, darkgreen(item),
                                       ' ' * (14 - len(item)), string))
            else:
                print('%s%s' % (' ' * 23, string))


def print_summary(vullist):
    'Prints the vulnerability summary'

    for item in vullist:
        if item.cves:
            for cve in item.cves:
                cvetype = str()
                if 'AV:L' in cve.vector:
                    cvetype += colorize('BAD', 'local')

                if 'AV:A' in cve.vector or 'AV:N' in cve.vector:
                    cvetype += colorize('BAD', 'network')

                if ('C:P' in cve.vector or 'C:C' in cve.vector)               \
                and ('I:P' in cve.vector or 'I:C' in cve.vector)              \
                and ('A:P' in cve.vector or 'A:C' in cve.vector):
                    cvetype += '%s%s' % (' ', blue('-complete'))
                else:
                    if 'C:P' in cve.vector or 'C:C' in cve.vector:
                        cvetype += '%s%s' % (' ', blue('-confidentiality'))

                    if 'I:P' in cve.vector or 'I:C' in cve.vector:
                        cvetype += '%s%s' % (' ', blue('-integrity'))

                    if 'A:P' in cve.vector or 'A:C' in cve.vector:
                        cvetype += '%s%s' % (' ', blue('-availability'))

                print ('[%s %26s] %s %s TYPE="%s"') % (darkgreen('bugid'),
                      colorize('GOOD', item.bugid), darkgreen(cve.cve),
                      blue('[%s]' % cve.score), cvetype)

    print('')


def print_bug(bugid):
    'Prints information about a particular bugid'

    if 'cve' in bugid.lower():
        print_cve(bugid.upper())
        return

    vul = lib.read_cve_file(lib.DIR['out'], bugid)

    if vul is None:
        error('Could not find bugid: %s' % bugid)
        return

    buginformation = {
        'Status'       : vul.status.capitalize(),
        'Reporter'     : vul.reporter,
        'Reported'     : vul.reported[:-11],
        'Affected'     : vul.affected,
        'Architecture' : vul.arch.capitalize()
    }

    print('')
    print_items(buginformation, 'Bugid %s' % bugid)

    for cve in vul.cves:
        print_cve(cve.cve)


def print_cve(cveid):
    'Prints information about a cve'

    cve = lib.Cve(cveid)
    vul = lib.find_cve(cveid, lib.DIR['out']) #FIXME
    if vul is None:
        error('Could not find cve: %s' % cveid)
        return
    else:
        for item in vul.cves:
            if item.cve == cveid:
                cve = item

    cveinformation = {
        'Published'   : cve.published,
        'Severity'    : cve.severity,
        'Score'       : cve.score,
        'Vector'      : cve.vector,
        'Description' : cve.desc,
    }
    #TODO print cve.refs

    print('')
    print_items(cveinformation, cve.cve)


def print_information():
    'Prints an information message'

    info('To print more information about a vulnerability try:')
    info('   $ %s [BUGID|CVE]' % sys.argv[0])


def usage():
    'Prints the usage screen'

    print('Usage: kernel-check [BUGID|CVE] [OPTION]...')
    print('Gentoo Kernel Security %s\n' % lib.VERSION)
    print('  -d, --debug          display debugging information')
    print('  -h, --help           display help information')
    print('  -n, --nocolor        disable colors')
    print('  -r, --report [file]  create a security report')
    print('  -s, --sync           receive the latest vulnerabilities')
    print('  -v, --verbose        display additional information')


if __name__ == '__main__':
    main(sys.argv[1:])