-
Notifications
You must be signed in to change notification settings - Fork 8
/
vulndigester.py
309 lines (280 loc) · 7.94 KB
/
vulndigester.py
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
import json
from collections import defaultdict
import re
import pandas
from jinja2 import Template
import argparse
nws = re.compile("[^\w]+") # 'No white space'
templateText="""
<!DOCTYPE html>
<html lang="en">
<head>
<title>Vulnerabilities report</title>
</head>
<body>
<h2>NVD file: {{ filename }} <p>
Environment root: {{ environment }}
</h2>
{% for item in reportitems %}
<p><p>*********<br>
Item type: <br>
<blockquote>
{% for t in item.itype %}
{{ t }}<br>
{% endfor %}
</blockquote><br>
Name: {{ item.iname }}<br>
CVE: {{ item.vuln.cve }}<br>
Description: {{ item.vuln.description }}<br>
URLS: <br>
<blockquote>
{% for url in item.vuln.urls %}
<a href={{ url }}>{{ url }}</a><br>
{% endfor %}
</blockquote>
{% endfor %}
</body>
</html>
"""
reportItem="""
*********
Item type:
{}
Name: {}
CVE: {}
Description: {}
URLS:
{}
"""
def updateReports(
dest,
src
):
"""
Merge 'item type' descriptions into a single report
:param dest: a dict {cve code : ItemReport obj}
:param src: same as dest, or a single ItemReport obj
:return: Updated dest parameter
"""
if isinstance(src, dict):
for cve, report in src.items():
if cve in dest:
dest[cve].itype += report.itype
else:
dest[cve] = report
else: # a single ItemReport object -- this for convenience
scve = src.vuln.cve
if scve in dest:
dest[scve].itype += src.itype
else:
dest[scve] = src
return dest
def extractFromCPE(nodes):
elements = set()
for node in nodes:
if 'cpe' in node:
elements = set([cpe['cpe23Uri'].split(':')[4].lower() for cpe in node['cpe']])
elif 'children' in node:
elements |= extractFromCPE(node['children'])
return elements
class Vulnerability(object):
def __init__(self, v):
self.cpeElements = extractFromCPE(v['configurations']['nodes'])
self.cve = v['cve']['CVE_data_meta']['ID']
self.urls = [
rd['url'] for rd in v['cve']['references']['reference_data']
]
self.description = ''
for desc in v['cve']['description']['description_data']:
if desc['lang'] == 'en':
self.description = desc['value']
break
class ItemReport(object):
def __init__(self, vuln, iname, itype):
self.vuln = vuln
self.iname = iname
self.itype= [itype]
def updateReport(self, newtype):
self.itype.append(newtype)
def printReport(self):
print reportItem.format(
'\n '.join(self.itype),
self.iname,
self.vuln.cve,
self.vuln.description,
'\n '.join(self.vuln.urls)
)
class Digest(object):
"""
Representation of NVD vulnerabilities JSON file
"""
def __init__(
self,
vfile,
ignores={}
):
"""
:param vfile: An NVD json file
:param ignores: A set of CVE codes to ignore
"""
self.prodmap = defaultdict(set)
self.cvemap = {}
self.ignores = ignores
self.j = json.load(vfile)
for vuln in self.j['CVE_Items']:
v = Vulnerability(vuln)
for prodname in v.cpeElements:
self.prodmap[prodname].add(v.cve)
self.cvemap[v.cve] = v
def itemReports(self, item, itype):
reports = {}
for vcode in filter(
lambda x: x not in self.ignores,
self.prodmap[item]
):
reports[vcode] = ItemReport(
self.cvemap[vcode],
item,
itype
)
return reports
def main():
parser = argparse.ArgumentParser(
description='Check for vulnerabilities in lists of modules, packages, libraries'
)
parser.add_argument(
'vfile',
type=argparse.FileType('r'),
help='JSON file from NVD'
)
parser.add_argument(
'pkgfile',
type=argparse.FileType('r'),
help='a list of packages in a Conda environment, one per line'
)
parser.add_argument(
'libfile',
type=argparse.FileType('r'),
help='a list of libraries in a Conda environment, one per line'
)
parser.add_argument(
'modfile',
type=argparse.FileType('r'),
help='a list of modules in a Conda environment, one per line'
)
parser.add_argument(
'--html',
action='store_true',
default=False,
help='HTML output rather than text'
)
parser.add_argument(
'--description',
'-d',
action='store_true',
default=False,
help='Search language of descriptions as well as CPE codes'
)
parser.add_argument(
'--ignore-words',
'-i',
type=argparse.FileType('r'),
default=None,
metavar='/path/to/word/list',
help='File containing a list of words to ignore in descriptions, one per line.'
)
parser.add_argument(
'--env',
action='store',
metavar='/path/to/environment/root',
type=str,
default='Not provided',
help='Conda environment root'
)
args = parser.parse_args()
pset = set([line.strip().lower() for line in args.pkgfile])
lset = set([line.strip().lower() for line in args.libfile])
mset = set([line.strip().lower() for line in args.modfile])
ignores = pandas.read_csv('ignore.csv')
ignores = set(ignores['cvecode'])
d = Digest(args.vfile, ignores=ignores)
itemset = set(d.prodmap.keys())
reports = {}
for item in (pset & itemset):
updateReports(
reports,
d.itemReports(
item,
'Package in CPE'
)
)
for item in (lset & itemset):
updateReports(
reports,
d.itemReports(
item,
'Library in CPE'
)
)
for item in (mset & itemset):
updateReports(
reports,
d.itemReports(
item,
'Module in CPE'
)
)
# Search descriptions too?
if args.description:
if args.ignore_words:
iwset = set([line.strip().lower() for line in args.ignore_words])
else:
iwset = set()
for vuln in d.cvemap.values():
if vuln.cve in ignores:
continue
wset = set(nws.sub(' ', vuln.description).lower().split())
for item in ((wset & pset) - iwset):
updateReports(
reports,
ItemReport(
vuln,
item,
'Package name occurs in description'
)
)
for item in ((wset & lset) - iwset):
updateReports(
reports,
ItemReport(
vuln,
item,
'Library name occurs in description'
)
)
for item in ((wset & mset) - iwset):
updateReports(
reports,
ItemReport(
vuln,
item,
'Module name occurs in description'
)
)
reportlist= sorted(reports.values(), key=lambda x : x.iname)
if args.html:
t = Template(templateText)
print t.render(
filename = args.vfile.name,
environment = args.env,
reportitems = reportlist
)
else:
print 'Environment: {}\nVulnerabilities file: {}\n\n'.format(
args.env,
args.vfile.name
)
for item in reportlist:
item.printReport()
if __name__ == '__main__':
main()