aboutsummaryrefslogtreecommitdiffstats
path: root/lib/orm/management/commands/lsupdates.py
blob: 7bbcb0661cf314a39b9d6ed16261e50cc391b56b (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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
#
# 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 orm.models import SrtSetting, DataSource, Vulnerability, Investigation
from orm.models import Cve, CveSet, CveToCveSet, VulnerabilityProduct
from orm.models import CveReference, CweTable, Product, CveToCwe
from orm.models import CpeToCve, CpeTable
from orm.models import CpeFilter, Product, Jira, InvestigationToJira, CveToVulnerablility
from orm.models import Keywords

import os
import sys
import re

import json
import xml.etree.ElementTree as ET
import csv
import logging
import threading
import time
logger = logging.getLogger("srt")
import urllib


def _log(msg):
    f1=open('/tmp/srt.log', 'a')
    f1.write("|" + msg + "|\n" )
    f1.close()


# === 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_jira_limit = 0 # 0 for all
#debug_jira_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_jira_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()


    def nist_scan_configuration_or(self, cve, cpe_or_node, name, and_enum):
        cpe_list = '<or>|'
        for cpe in cpe_or_node['cpe']:
            cpe23Uri = cpe['cpe23Uri']
            if 'cpeMatchString' in cpe:
                cpeMatchString = cpe['cpeMatchString']
            else:
                cpeMatchString = ''
            if 'versionEndIncluding' in cpe:
                versionEndIncluding = cpe['versionEndIncluding']
            else:
                versionEndIncluding = ''
            cpe_list += '%s,%s,%s,%s|' % (cpe['vulnerable'],cpe23Uri,cpeMatchString,versionEndIncluding)
        cpe_list += '</or>|'
        return cpe_list

    def nist_jason(self, dct):
        CVE_Items = dct['CVE_Items']
        total = len(CVE_Items)
        for i, CVE_Item  in enumerate(CVE_Items):
            cve = CVE_Item['cve']
            references = cve['references']['reference_data']
            CVE_data_meta  = cve['CVE_data_meta']['ID']

            # DEBUGGING SUPPORT !!! TODO
            scan = True
            status = Cve.NOT_VULNERABLE
            if (Command.debug_cve_count or len(debug_cve_list)) and not CVE_data_meta.startswith(Command.debug_include_id_prefix):
                scan = False
                if Command.debug_cve_count:
                    if i < Command.debug_cve_count:
                        scan = True
                if len(debug_cve_list):
                    for debug_cve in debug_cve_list:
                        if cve['CVE_data_meta']['ID'].startswith(debug_cve):
                            scan = True
                            status = Cve.INVESTIGATE
            if not scan:
                continue

            if False:
                print("  publishedDate: %s" % CVE_Item['publishedDate'])
                print("  lastModifiedDate: %s" % CVE_Item['lastModifiedDate'])

                print("    publishedDate: %s" % re.sub('T.*','',CVE_Item['publishedDate']))
                print("    lastModifiedDate: %s" % re.sub('T.*','',CVE_Item['lastModifiedDate']))

                print("  data_type: %s" % cve['data_type'])
                print("  data_format: %s" % cve['data_format'])
                print("  CVE_data_meta: %s" % cve['CVE_data_meta']['ID'])
                print("  problemtype: %s" % cve['problemtype']['problemtype_data'][0]['description'][0]['value'])
                print("  description: '%s'" % cve['description']['description_data'][0]['value'])
                references = cve['references']['reference_data']
                print("  References = %d" % len(references))
                for ref in references:
                    print("    reference: %s" % ref['url'])
                if CVE_Item['impact'] and CVE_Item['impact']['baseMetricV3']:
                    baseMetricV3 = CVE_Item['impact']['baseMetricV3']
                    print("  cvssV3 : %s,%s" % (baseMetricV3['exploitabilityScore'],baseMetricV3['impactScore']))
                    print("    vectorString = %s" % baseMetricV3['cvssV3']['vectorString'])
                    print("    attackVector = %s" % baseMetricV3['cvssV3']['attackVector'])
                    print("    attackComplexity = %s" % baseMetricV3['cvssV3']['attackComplexity'])
                    print("    privilegesRequired = %s" % baseMetricV3['cvssV3']['privilegesRequired'])
                    print("    userInteraction = %s" % baseMetricV3['cvssV3']['userInteraction'])
                    print("    scope = %s" % baseMetricV3['cvssV3']['scope'])
                    print("    confidentialityImpact = %s" % baseMetricV3['cvssV3']['confidentialityImpact'])
                    print("    integrityImpact = %s" % baseMetricV3['cvssV3']['integrityImpact'])
                    print("    availabilityImpact = %s" % baseMetricV3['cvssV3']['availabilityImpact'])
                    print("    baseScore = %s" % baseMetricV3['cvssV3']['baseScore'])
                    print("    baseSeverity = %s" % baseMetricV3['cvssV3']['baseSeverity'])
                if CVE_Item['impact'] and CVE_Item['impact']['baseMetricV2']:
                    baseMetricV2 = CVE_Item['impact']['baseMetricV2']
                    print("  cvssV2 : %s,%s" % (baseMetricV2['exploitabilityScore'],baseMetricV2['exploitabilityScore']))
                    print("    vectorString = %s" % baseMetricV2['cvssV2']['vectorString'])
                    print("    accessVector = %s" % baseMetricV2['cvssV2']['accessVector'])
                    print("    accessComplexity = %s" % baseMetricV2['cvssV2']['accessComplexity'])
                    print("    authentication = %s" % baseMetricV2['cvssV2']['authentication'])
                    print("    confidentialityImpact = %s" % baseMetricV2['cvssV2']['confidentialityImpact'])
                    print("    integrityImpact = %s" % baseMetricV2['cvssV2']['integrityImpact'])
                    print("    availabilityImpact = %s" % baseMetricV2['cvssV2']['availabilityImpact'])
                    print("    baseScore = %s" % baseMetricV2['cvssV2']['baseScore'])
                    print("    severity = %s" % baseMetricV2['severity'])

            try:
                CVE_data_meta  = cve['CVE_data_meta']['ID']
                v, created = Cve.objects.get_or_create(name=CVE_data_meta)

                v.name = CVE_data_meta
                v.source = 'NIST'
                status = Cve.NOT_VULNERABLE

                # Debugging support
#                if v.name.startswith("CVE-2018"):
#                    status = Cve.NEW
#                v.status = status
                v.tags = ''
                v.tags_private = ''

                v.cve_data_type = cve['data_type']
                v.cve_data_format = cve['data_format']
                v.cve_data_version = cve['data_version']

                v.description = cve['description']['description_data'][0]['value']
                v.publishedDate = re.sub('T.*','',CVE_Item['publishedDate'])
                v.lastModifiedDate = re.sub('T.*','',CVE_Item['lastModifiedDate'])

                v.public = True
                v.publish = Cve.PUBLISH_PUBLISHED
                v.publish_date = v.publishedDate

                #v.problemtype = cve['problemtype']['problemtype_data'][0]['description'][0]['value']
                problem_list = cve['problemtype']['problemtype_data']
                CveToCwe.objects.filter(cve=v).delete()
                for problem_Item in problem_list:
                    description_list = problem_Item['description']
                    for description_Item in description_list:
                        value = description_Item['value']
                        cwe, created = CweTable.objects.get_or_create(name=value)
                        if created:
                            print("WARNING Missing CWE = '%s'"% value)
                            cwe.save()
                        cve2cwe, created = CveToCwe.objects.get_or_create(cve=v,cwe=cwe)
                        if created:
                            cve2cwe.save()

#                if CVE_Item['impact'] and CVE_Item['impact']['baseMetricV3']:
                if ('impact' in CVE_Item) and ('baseMetricV3' in CVE_Item['impact']):
                    baseMetricV3 = CVE_Item['impact']['baseMetricV3']
                    v.cvssV3_baseScore = baseMetricV3['cvssV3']['baseScore']
                    v.cvssV3_baseSeverity = baseMetricV3['cvssV3']['baseSeverity']
                    v.cvssV3_vectorString = baseMetricV3['cvssV3']['vectorString']
                    v.cvssV3_exploitabilityScore = baseMetricV3['exploitabilityScore']
                    v.cvssV3_impactScore = baseMetricV3['impactScore']
                    v.cvssV3_attackVector = baseMetricV3['cvssV3']['attackVector']
                    v.cvssV3_attackComplexity = baseMetricV3['cvssV3']['attackComplexity']
                    v.cvssV3_privilegesRequired = baseMetricV3['cvssV3']['privilegesRequired']
                    v.cvssV3_userInteraction = baseMetricV3['cvssV3']['userInteraction']
                    v.cvssV3_scope = baseMetricV3['cvssV3']['scope']
                    v.cvssV3_confidentialityImpact = baseMetricV3['cvssV3']['confidentialityImpact']
                    v.cvssV3_integrityImpact = baseMetricV3['cvssV3']['integrityImpact']
                    v.cvssV3_availabilityImpact = baseMetricV3['cvssV3']['availabilityImpact']
                if ('impact' in CVE_Item) and ('baseMetricV2' in CVE_Item['impact']):
                    baseMetricV2 = CVE_Item['impact']['baseMetricV2']
                    v.cvssV2_baseScore = baseMetricV2['cvssV2']['baseScore']
                    v.cvssV2_severity = baseMetricV2['severity']
                    v.cvssV2_vectorString = baseMetricV2['cvssV2']['vectorString']
                    v.cvssV2_exploitabilityScore = baseMetricV2['exploitabilityScore']
                    v.cvssV2_impactScore = baseMetricV2['exploitabilityScore']
                    v.cvssV2_accessVector = baseMetricV2['cvssV2']['accessVector']
                    v.cvssV2_accessComplexity = baseMetricV2['cvssV2']['accessComplexity']
                    v.cvssV2_authentication = baseMetricV2['cvssV2']['authentication']
                    v.cvssV2_confidentialityImpact = baseMetricV2['cvssV2']['confidentialityImpact']
                    v.cvssV2_integrityImpact = baseMetricV2['cvssV2']['integrityImpact']

##                v.save()

                CveReference.objects.filter(cve=v).delete()
                for ref in references:
                    r, created = CveReference.objects.get_or_create(cve=v,
                                                         hyperlink=ref['url'])
                    r.resource = ''
                    r.type = ''
                    r.source = ''
                    r.name = ''
                    r.save()
#                        print("    reference: %s,%s" % (ref['url'],created))


                configurations = CVE_Item['configurations']
                v.cpe_list = ''
                is_first_and = True
                for i, config in enumerate(configurations['nodes']):
                    v.cpe_list += '<config>|'
                    v.cpe_list += '<and>|'
                    if "AND" == config['operator']:
                        # create AND record
                        if not is_first_and:
                            v.cpe_list += '</and>|'
                            v.cpe_list += '<and>|'
                        for j, cpe_or_node in enumerate(config['children']):
                            if "OR" == cpe_or_node['operator']:
                                v.cpe_list += self.nist_scan_configuration_or(v,cpe_or_node, CVE_data_meta, j)
                            else:
                                print("ERROR CONFIGURE:OR_OP?:%s" % cpe_or_node['operator'])
                    elif "OR" == config['operator']:
                        v.cpe_list += self.nist_scan_configuration_or(v,config, CVE_data_meta, 0)
                    else:
                        print("ERROR CONFIGURE:OP?:%s" % config_rec['operator'])
                    v.cpe_list += '</and>|'
                    v.cpe_list += '</config>|'

#				# create a parent CveSet if needed
#                cve_set, created = CveSet.objects.get_or_create(name=v.name)
#                if created:
#                    cve_set.name = v.name
#                    cve_set.description = v.description
#                    cve_set.cvssV3_baseScore = v.cvssV3_baseScore
#                    cve_set.cvssV3_baseSeverity = v.cvssV3_baseSeverity
#                    cve_set.publishedDate = v.publishedDate
#                    cve_set.lastModifiedDate = v.lastModifiedDate
#                    cve_set.save()
#
#                # connect the Cve with the CveSet				
#                cve2cveset, created = CveToCveSet.objects.get_or_create(cve=v, cveset=cve_set)
#                cve2cveset.save()

                # save the final CVE content
                v.recommend = v.recommendation()
                v.save()
				
            except Exception as e:
                logger.warning("Failed saving CVE %s (%s)", (cve['CVE_data_meta']['ID'],e))
                return

            self.mini_progress("CVE's", i, total)


    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))


    def cve_keywords_old(self, csvfile_name):
        # mode,type,keyword,weight
        # y,key,abiword,

        KEY_MODE=0
        KEY_TYPE=1
        KEY_KEY=2
        KEY_WEIGHT=3

        i_index=0
        is_header = True
        with open(csvfile_name, newline='') as csvfile:
            CPE_reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in CPE_reader:
                if is_header or not len(row):
                    is_header = False
                    continue

                if (KEY_WEIGHT+1) != len(row):
                    print("KEY_ROWLEN_ERROR:'%s'" % row)
                    continue

                i_index += 1
                if 0 == i_index % 100:
                    print('%04d: %20s\r' % (i_index,row[KEY_KEY]), end='')

#                # DEBUG ### TODO
#                if 0 < Command.debug_jira_limit:
#                    if i_index > Command.debug_jira_limit:
#                        return

                k, created = Keywords.objects.get_or_create(keyword=row[KEY_KEY])
                if 'y' == row[KEY_MODE]:
                    k.key_mode = Keywords.FOR
                else:
                    k.key_mode = Keywords.AGAINST
                if 'keyword' == row[KEY_KEY]:
                    k.key_type = Keywords.KEYWORD
                else:
                    k.key_type = Keywords.CPE
                if row[KEY_WEIGHT]:
                    k.weight = int(row[KEY_WEIGHT])
                else:
                    if Keywords.FOR == k.key_mode:
                        k.weight = 1
                    else:
                        k.weight = -1
                k.save()

    def cve_keywords(self, csvfile_name):
        # mode,type,keyword,weight
        # y,key,abiword,

        KEY_MODE=0
        KEY_TYPE=1
        KEY_KEY=2
        KEY_WEIGHT=3

        keywords_for = ''
        keywords_against = ''

        i_index=0
        is_header = True
        with open(csvfile_name, newline='') as csvfile:
            CPE_reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in CPE_reader:
                if is_header or not len(row):
                    is_header = False
                    continue

                if (KEY_WEIGHT+1) != len(row):
                    print("KEY_ROWLEN_ERROR:'%s'" % row)
                    continue

                i_index += 1
                if 0 == i_index % 100:
                    print('%04d: %20s\r' % (i_index,row[KEY_KEY]), end='')

                key = row[KEY_MODE]
                if '#' == key[0]:
                    key = key[1:]

                if 'y' == key:
                    keywords_for += "|%s,%s" % (row[KEY_KEY],row[KEY_WEIGHT])
                elif 'n' == key:
                    keywords_against += "|%s,%s" % (row[KEY_KEY],row[KEY_WEIGHT])

        setting = SrtSetting.objects.get_or_create(name='keywords_for')[0]
        setting.value = keywords_for[1:]
        setting.save()
        setting = SrtSetting.objects.get_or_create(name='keywords_against')[0]
        setting.value = keywords_against[1:]
        setting.save()
        
        S = SrtSetting.objects.get(name='keywords_for')
        #print("FOO_FOR:[%s]='%s'" % (S.name,S.value[0:30]))
        S = SrtSetting.objects.get(name='keywords_against')
        #print("FOO_NOT:[%s]='%s'" % (S.name,S.value[0:30]))


    def debug_set_cve(self,key,public,vulnerability,wr_comments,wr_comments_private):
        try:
            c = Cve.objects.get(name=key)
            c.public = public
            c.wr_comments = wr_comments
            c.wr_comments_private = wr_comments_private
            c.save()
            if vulnerability:
                v = Vulnerability.objects.get(name=vulnerability)
                cv, created = CveToVulnerablility.objects.get_or_create(vulnerability=v,cve=c)
                cv.save()
        except ObjectDoesNotExist:
            print("Cve %s not found" % key)

    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

        data_sources=DataSource.objects.all()
        for source in data_sources:

            if source.loaded:
                logger.info("Skipping source data from %s",source.file_path)
                print("Skipping CVE data for %s (already loaded)" % (source.description))
                continue
            else:
                logger.info("Fetching source data from %s",source.file_path)
                print("Fetching source data for '%s'" % (source.description))

            file_path = source.file_path
            url_path = source.url
            dct = None
            root = None
            content = None
            source_doc = None
            # prefer the file path before the url
            if file_path:
                # load the file
                source_doc = source.file_path
                if not source.file_path.startswith('/'):
                    file_path = os.path.join(os.getenv('SRT_BASE_DIR'), source.file_path)
                    source.loaded = True
                    source.save()
                if not os.path.isfile(file_path):
                    logger.error("Data file not found '%s'" % (file_path))
                    continue
                if 'json' == source.type:
                    with open(file_path) as json_data:
                        dct = json.load(json_data)
                elif 'xml' == source.type:
                    tree = ET.parse(file_path)
                    root = tree.getroot()
                elif 'csv' == source.type:
                    csvfile_name = file_path
                else:
                    with open(file_path) as text_data:
                        content = text_data.read()
            elif url_path:
                # load the HTML page
                source_doc = source.url
                try:
                   f = urlopen(href)
                   content = f.read().decode('UTF-8')
                   f.close()
                except URLError as e:
                    raise Exception("Failed to open %s: %s" % (href, e.reason))
                    continue
            else:
                # no data source path to load
                logger.error("Unknown data source path for '%s' (%s,%s) " % (source.source.description,source.file_path,source.url))
                continue


            # testing shortcut
            if ('nist' == source.source) and ('yes' == SrtSetting.objects.get(name='TEST_SKIP_NIST_IMPORT').value):
                continue
            
            # Common data sources
            if 'common' == source.source:
                if 'triage_keywords' == source.data:
                    self.cve_keywords(csvfile_name)
                    source.loaded = True
                    source.save()
                    continue

            # Common Vulnerabilities and Exposures
            if 'cve' == source.data:
                if 'nist' == source.source and 'json' == source.type:
                    self.nist_jason(dct)
                    source.loaded = True
                    source.save()
                    continue
            # Common Weakness Enumeration
            if 'cwe' == source.data:
                if 'nist' == source.source and 'html' == source.type:
                    self.nist_cwe(content)
                    source.loaded = True
                    source.save()
                    continue
            # Common Product Enumeration
            if 'cpe' == source.data:
                if 'nist' == source.source and 'xml' == source.type:
                    self.nist_cpe(root)
                    source.loaded = True
                    source.save()
                    continue
                if 'nist' == source.source and 'csv' == source.type:
                    self.nist_cpe_csv(csvfile_name)
                    source.loaded = True
                    source.save()
                    continue
 

            # data source not handled
            logger.error("Unknown data source type for '%s' (%s,%s,%s) " % (source.file_path,source.data,source.source,source.type))

        # TEST DEBUG
#        self.debug_set_cve('CVE-2017-0002',False,'','','')
#        self.debug_set_cve('CVE-2017-0010',False,'','','')
        self.debug_set_cve('CVE-2017-5753',True,'V0000','Spectre Variant 1: Bounds check bypass','community calling this "spectre"')
        self.debug_set_cve('CVE-2017-5715',True,'V0000','Spectre Variant 2: Branch target injection','see if this will required compiler changes')
        self.debug_set_cve('CVE-2017-5754',True,'V0000','Meltdown: Rogue data cache load, memory access permission check performed after kernel memory read','mostly for Intel parts')

        os.system('setterm -cursor on')

    def handle(self, **options):

        # testing shortcuts
        if 'yes' == SrtSetting.objects.get(name='TEST_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_jira_limit = 10
            Command.cpe_limit = 10

        self.update()