#
# 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.update_time = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
updated_source.lastModifiedDate = updated_source.update_time
updated_source.save()
def nist_cwe(self, content):
#
CWE-123 |
# Write-what-where Condition |
# 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. |
state = 0
for line in content.split('\n'):
if (0 == state) and (0 < line.find('cweIdEntry')):
# CWE-613 |
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')):
# Insufficient Session Expiration |
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('')):
# | Insufficient Information |
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('')):
# | Weaknesses in this category are related to improper calculation or conversion of numbers. |
m = re.search('(.*?) | ', 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):
#
# 1024cms.org 1024 CMS 0.7
#
#
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***")
try:
from urllib.request import urlopen, URLError
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlopen, URLError
from urlparse 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:
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()