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
|
#
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Security Response Tool Implementation
#
# Copyright (C) 2013-2015 Intel Corp.
# Copyright (C) 2017-2018 Wind River Systems
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import Group
from orm.models import SrtSetting, DataSource
from orm.models import Cve, CveToVulnerablility, CveReference
from orm.models import Vulnerability
from orm.models import CweTable, CveToCwe
from orm.models import CpeToCve, CpeTable, CpeFilter
from orm.models import Product, Defect
from users.models import SrtUser
import os
import sys
import re
import time
import pytz
from datetime import datetime, date
import json
import xml.etree.ElementTree as ET
import csv
import logging
import threading
import urllib
logger = logging.getLogger("srt")
# quick development/debugging support
from srtgui.api import _log
# === Debugging limited database loading support ===
debug_cve_list = [] # empty list for any
#debug_cve_list = [
# 'CVE-2017-0001','CVE-2017-1000135','CVE-2017-10604','CVE-2017-0290',
# 'CVE-2017-8361','CVE-2017-8362','CVE-2017-8363','CVE-2017-8365','CVE-2017-8392','CVE-2017-8779',
# ]
#debug_cve_count = 0 # 0 for all
#debug_cve_count = 10 # 0 for any
#debug_include_id_prefix = 'CVE-2018' # always include CVEs with this prefix
#debug_include_id_prefix = 'XXX' # always include CVEs with this prefix
#status_sustaining_limit = 0 # 0 for all
#status_sustaining_limit = 10
#debug_defect_limit = 0 # 0 for all
#debug_defect_limit = 10
#cpe_limit = 0
#cpe_limit = 10
class Spinner(threading.Thread):
""" A simple progress spinner to indicate download/parsing is happening"""
def __init__(self, *args, **kwargs):
super(Spinner, self).__init__(*args, **kwargs)
self.setDaemon(True)
self.signal = True
def run(self):
os.system('setterm -cursor off')
while self.signal:
for char in ["/", "-", "\\", "|"]:
sys.stdout.write("\r" + char)
sys.stdout.flush()
time.sleep(0.25)
os.system('setterm -cursor on')
def stop(self):
self.signal = False
class Command(BaseCommand):
args = ""
help = "Updates locally cached information from the registered data sources"
# === Debugging limited database loading support ===
debug_cve_list = [] # empty list for any
debug_cve_count = 0 # 0 for all
debug_include_id_prefix = 'XXX' # always include CVEs with this prefix
status_sustaining_limit = 0 # 0 for all
debug_defect_limit = 0 # 0 for all
cpe_limit = 0
def mini_progress(self, what, i, total):
i = i + 1
pec = (float(i)/float(total))*100
sys.stdout.write("\rUpdating %s %d%%" %
(what,
pec))
sys.stdout.flush()
if int(pec) is 100:
sys.stdout.write("\n")
sys.stdout.flush()
# Execute a shell script to import data, relative the SRT base
def execute_script(self,command):
SRT_BASE_DIR = os.environ.get('SRT_BASE_DIR')
CWD = os.getcwd()
os.chdir(SRT_BASE_DIR)
script = os.path.join(SRT_BASE_DIR,command)
print("====vvv Executing script '%s' vvv====" % script)
ret = os.system(script)
os.chdir(CWD)
if 0 != ret:
# NOTE: the error is already displayed in the normal STDERR, so
# so need to repeat it here
print("\n##########\nHALT: SCRIPT ERROR: %s=%s\n##########" % (ret,script))
exit(1)
print("====^^^ Script Done = %s ^^^====" % ret)
# Mark database as loaded
def source_loaded(self,id,update_modified=True):
# Re-fetch record in case external script updates
updated_source=DataSource.objects.get(id=id)
updated_source.loaded = True
if update_modified:
updated_source.lastModifiedDate = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
updated_source.save()
def nist_cwe(self, content):
# <td nowrap><span id="cweIdEntry-CWE-123">CWE-123</span></td>
# <td nowrap><a href="http://cwe.mitre.org/data/definitions/123.html" target="_blank"> Write-what-where Condition</a></td>
# <td>Any condition where the attacker has the ability to write an arbitrary value to an arbitrary location, often as the result of a buffer overflow.</td>
state = 0
for line in content.split('\n'):
if (0 == state) and (0 < line.find('cweIdEntry')):
# <td nowrap><span id="cweIdEntry-CWE-613">CWE-613</span></td>
m = re.search('cweIdEntry.*>(.+?)<', line)
if m:
name = m.group(1)
else:
print("ERROR ID:%s" % line)
continue
state = 1
elif (1 == state) and (0 < line.find('href')):
# <td nowrap><a href="http://cwe.mitre.org/data/definitions/613.html" target="_blank"> Insufficient Session Expiration</a></td>
m = re.search('href="(.+?)"', line)
if m:
href = m.group(1)
else:
print("ERROR HREF:%s" % line)
continue
m = re.search('href.*>(.+?)<', line)
if m:
summary = m.group(1)
else:
print("ERROR Summary:%s" % line)
continue
state = 2
elif (1 == state) and (0 < line.find('<td nowrap>')):
# <td nowrap>Insufficient Information</td>
href = ''
m = re.search('nowrap>(.+?)<', line)
if m:
summary = m.group(1)
else:
print("ERROR Summary:%s" % line)
continue
state = 2
elif (2 == state) and (0 < line.find('<td>')):
# <td>Weaknesses in this category are related to improper calculation or conversion of numbers.</td>
m = re.search('<td>(.*?)</td>', line)
if m:
description = m.group(1)
else:
print("ERROR Desc:%s" % line)
continue
cwe, created = CweTable.objects.get_or_create(name=name)
index = name.find('-')
if name[index+1].isdigit():
cwe.name_sort = '%s-%04d' % (name[0:index],int(name[index+1:]))
else:
cwe.name_sort = name
cwe.href = href
cwe.summary = summary
cwe.description = description
cwe.save()
state = 0
def nist_cpe(self, root):
#<cpe-list
# <cpe-item name="cpe:/a:1024cms:1024_cms:0.7">
# <title xml:lang="en-US">1024cms.org 1024 CMS 0.7</title>
# <cpe-23:cpe23-item name="cpe:2.3:a:1024cms:1024_cms:0.7:*:*:*:*:*:*:*"/>
# </cpe-item>
i = 1
last_key_prime = ''
last_key_sub = ''
for child_1 in root:
if 'cpe-item' in child_1.tag:
for child_2 in child_1:
if 'cpe23-item' in child_2.tag:
cpe23Uri = child_2.attrib['name']
# Add to general CPE Table
if not cpe23Uri:
cpe23Uri = 'cpe:2.3:o:missing:missing:*:*:*:*:*:*:*:*'
cpe_fields = cpe23Uri.split(':')
key_prime = cpe_fields[3]
key_sub = cpe_fields[4]
if (key_prime == last_key_prime) and (key_sub == last_key_sub):
continue
last_key_prime = key_prime
last_key_sub = key_sub
# add top-level key_prime
cpe_filter, created = CpeFilter.objects.get_or_create(key_prime=key_prime,key_sub='')
if created:
cpe_filter.save()
# add full key_prime:key_sub
cpe_filter, created = CpeFilter.objects.get_or_create(key_prime=key_prime,key_sub=key_sub)
if created:
cpe_filter.save()
print("[%d]cpe23Uri='%s',%s,%s" % (i,cpe23Uri,key_prime,key_sub))
i += 1
def nist_cpe_csv(self, csvfile_name):
# Status,Company,Product,Auto
i=0
with open(csvfile_name, newline='') as csvfile:
CPE_reader = csv.reader(csvfile, delimiter=',', quotechar='"')
last_company = ''
last_product = ''
for row in CPE_reader:
i += 1
if (i>1) and len(row):
if 'i' == row[0]:
status = CpeFilter.INCLUDE
elif 'x' == row[0]:
status = CpeFilter.EXCLUDE
elif 'r' == row[0]:
status = CpeFilter.UNDECIDED
else:
status = CpeFilter.UNDECIDED
company = row[1]
product = row[2]
if 'a' == row[3]:
auto = True
else:
auto = False
if (last_company == company) and (last_product == product):
continue
last_company = company
last_product = product
# add top-level last_company
cpe_filter, created = CpeFilter.objects.get_or_create(key_prime=company,key_sub='')
cpe_filter.status = status
cpe_filter.automatic = auto
cpe_filter.save()
# add full last_company:product
cpe_filter, created = CpeFilter.objects.get_or_create(key_prime=company,key_sub=product)
cpe_filter.status = status
cpe_filter.automatic = auto
cpe_filter.save()
if 0 == i % 10:
print('%04d: %20s\r' % (i,company), end='')
# print("[%d]cpe23Uri=%s,%s" % (i,company,product))
# We explicit use Django to add users to avoid attempting to hash passwords in a shell script
# NOTE: extra items or fields (like "_comment_") are explicitly ignored
def users_load(self, dct):
User_Items = dct['User_Items']
for i, User_Item in enumerate(User_Items):
# Required fields
name = User_Item['name']
email = User_Item['email']
group_name = User_Item['group']
# Optional fields (but schema requires definition)
first_name = User_Item['first_name'] if 'first_name' in User_Item else ''
last_name = User_Item['last_name'] if 'last_name' in User_Item else ''
role = User_Item['role'] if 'role' in User_Item else 'srtool'
is_staff = User_Item['is_staff'] if 'is_staff' in User_Item else False
is_active = User_Item['is_active'] if 'is_active' in User_Item else True
date_joined = User_Item['date_joined'] if 'date_joined' in User_Item else datetime.now(pytz.utc)
# Provide default password so that they can change after first login (form prevents blank passwords)
password = User_Item['password'] if 'password' in User_Item else 'srtool'
srtuser, created = SrtUser.objects.get_or_create(username = name)
if created:
srtuser.email = email
srtuser.role = role
srtuser.password = ''
srtuser.first_name = first_name
srtuser.last_name = last_name
srtuser.is_staff = is_staff
srtuser.is_active = is_active
srtuser.date_joined = date_joined
srtuser.set_password(password) # hash the password
srtuser.save()
group = Group.objects.get(name = group_name)
group.user_set.add(srtuser)
def update(self):
"""
Fetches CVE data from the registered data sources
"""
os.system('setterm -cursor off')
logger.info("***LS UPDATES***")
from urllib.request import urlopen, URLError
from urllib.parse import urlparse
# Process the data sources in strict pk order to insure dependencies
data_sources=DataSource.objects.all().order_by('key')
for source in data_sources:
if source.loaded and not (source.update_frequency == DataSource.ONSTARTUP):
logger.info("Skipping source data from %s",source.description)
print("Skipping datasource %s (already loaded)" % (source.description))
_log("Skipping datasource %s (already loaded)" % (source.description))
continue
elif not source.init:
# No Init action?
print("Skipping datasource %s (no init action)" % (source.description))
continue
else:
logger.info("Fetching datasource %s:%s" % (source.source,source.description))
print("Fetching datasource '%s:%s'" % (source.source,source.description))
_log("Fetching datasource '%s:%s'" % (source.source,source.description))
# Development/testing shortcut
if ('cve' == source.data) and ('yes' == SrtSetting.objects.get(name='SRTDBG_SKIP_CVE_IMPORT').value):
continue
if ('cpe' == source.data) and ('yes' == SrtSetting.objects.get(name='SRTDBG_SKIP_CPE_IMPORT').value):
continue
if ('defect' == source.data) and ('yes' == SrtSetting.objects.get(name='SRTDBG_SKIP_DEFECT_IMPORT').value):
continue
# Script-based init?
if not source.init.startswith('file:'):
self.execute_script(source.init)
self.source_loaded(source.id)
continue
# Get the init content with local methods
dct = None
root = None
content = None
source_doc = None
# load the file
source_doc = source.init.replace('file:','')
if not source_doc.startswith('/'):
source_doc = os.path.join(os.getenv('SRT_BASE_DIR'), source_doc)
if not os.path.isfile(source_doc):
logger.error("Data file not found '%s'" % (source_doc))
continue
if source_doc.endswith('.json'):
with open(source_doc) as json_data:
dct = json.load(json_data)
elif source_doc.endswith('xml'):
tree = ET.parse(source_doc)
root = tree.getroot()
elif source_doc.endswith('csv'):
csvfile_name = source_doc
else:
with open(source_doc) as text_data:
content = text_data.read()
# Common data sources
pass
# Common Weakness Enumeration
if 'cwe' == source.data:
if 'nist' == source.source:
self.nist_cwe(content)
self.source_loaded(source.id)
continue
# Common User load
if 'users' == source.data:
self.users_load(dct)
self.source_loaded(source.id)
continue
# data source not handled
logger.error("Unknown data source type for (%s,%s,%s) " % (source.data,source.source,source.name))
_log("Unknown data source type for %s,%s,%s) " % (source.data,source.source,source.name))
os.system('setterm -cursor on')
def handle(self, **options):
# testing shortcuts
if 'yes' == SrtSetting.objects.get(name='SRTDBG_MINIMAL_DB').value:
print("TEST: MINIMAL DATABASE LOADING")
Command.debug_cve_count = 10 # 0 for any
Command.debug_include_id_prefix = 'XXX' # always include CVEs with this prefix
Command.status_sustaining_limit = 10
Command.debug_defect_limit = 10
Command.cpe_limit = 10
self.update()
|