Merge ~eslerm/ubuntu-cve-tracker:check-cves-variables into ubuntu-cve-tracker:master

Proposed by Mark Esler
Status: Merged
Merged at revision: fb96f59c1267dc5da2facee5ee39b2e23cd87e65
Proposed branch: ~eslerm/ubuntu-cve-tracker:check-cves-variables
Merge into: ubuntu-cve-tracker:master
Diff against target: 523 lines (+110/-112)
1 file modified
scripts/check-cves (+110/-112)
Reviewer Review Type Date Requested Status
Alex Murray Approve
Review via email: mp+462731@code.launchpad.net

Commit message

check-cves: variable clarity updates

Description of the change

This is mostly an update to make variables clearer.

I should have said "constants" not "globals".

I'm not certain all of them should be added. Particularly `BUILT_USING_MAP` which pylint suggested. `UNTRIAGED_JSON` as well, but I don't believe code using this variable is proper (several parameters can override it).

There is more work to clarify human_process_cve(), but this seems like a good point to stop and ask for a review.

To post a comment you must log in.
Revision history for this message
Mark Esler (eslerm) wrote :
Revision history for this message
Marc Deslauriers (mdeslaur) wrote :

This script doesn't have a main function, it's just a script. If you really want to run something like pylint over it and want to switch everything it thinks are "global" variables to uppercase, you should probably convert the script to use a main function first.

Revision history for this message
Mark Esler (eslerm) wrote (last edit ):

The plan is to use a main function. My refactor isn't complete, but had begun to implement this https://git.launchpad.net/~eslerm/ubuntu-cve-tracker/tree/scripts/check_cves.py?h=cve-translate

It's easier to work with the code after it is clearer, which is why I'm suggesting style changes first.

Potentially I _could_ drop all of these variables to lower case if needed.

Revision history for this message
Alex Murray (alexmurray) wrote :

LGTM

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
diff --git a/scripts/check-cves b/scripts/check-cves
index be0b713..c1239fd 100755
--- a/scripts/check-cves
+++ b/scripts/check-cves
@@ -79,20 +79,20 @@ for release in list(source.keys()):
79# remove common words which also happen to be names79# remove common words which also happen to be names
80# of source packages since our ignore suggestion is80# of source packages since our ignore suggestion is
81# likely to sometimes contain these81# likely to sometimes contain these
82common_words = ['an', 'and', 'context', 'file', 'modules', 'the', 'when']82COMMON_WORDS = ['an', 'and', 'context', 'file', 'modules', 'the', 'when']
83allsrcs.difference_update(set(common_words))83allsrcs.difference_update(set(COMMON_WORDS))
84allsrcs.update(set(cve_lib.package_db.keys()))84allsrcs.update(set(cve_lib.package_db.keys()))
8585
86built_using_map = None86BUILT_USING_MAP = None
8787
88destdir = "."88DEST_DIR = "."
8989
90# Skip stuff older than 200590# Skip stuff older than 2005
91cve_limit = 200491CVE_LIMIT = 2004
9292
93mistriaged_hint = 'Previously triaged as ignored in Ubuntu\n\n'93MISTRIAGED_HINT = 'Previously triaged as ignored in Ubuntu\n\n'
9494
95ignore_strings = [95IGNORE_STRINGS = [
96 "** REJECT **", "Internet Explorer", "Microsoft Edge", "Windows 98",96 "** REJECT **", "Internet Explorer", "Microsoft Edge", "Windows 98",
97 "Windows 2000", "Windows XP", "Windows Server 2003", "Windows NT",97 "Windows 2000", "Windows XP", "Windows Server 2003", "Windows NT",
98 "Mercury Board", "ZeroBoard", "AntiVirus", "Microsoft", "SGI IRIX",98 "Mercury Board", "ZeroBoard", "AntiVirus", "Microsoft", "SGI IRIX",
@@ -136,7 +136,6 @@ def _spawn_editor(path):
136 subprocess.call([editor, path])136 subprocess.call([editor, path])
137137
138def debug(msg):138def debug(msg):
139 global opt
140 if args.debug:139 if args.debug:
141 print(msg, file=sys.stderr)140 print(msg, file=sys.stderr)
142141
@@ -227,7 +226,7 @@ def import_debian(handler):
227 cves = dict()226 cves = dict()
228227
229 today = datetime_date.today()228 today = datetime_date.today()
230 known = set(CVEKnownList + CVEIgnoreList)229 known = set(cve_known_list + cve_ignore_list)
231230
232 def ever_existed(pkg):231 def ever_existed(pkg):
233 for rel in source:232 for rel in source:
@@ -236,8 +235,8 @@ def import_debian(handler):
236 return False235 return False
237236
238 def mistriaged(cve):237 def mistriaged(cve):
239 if cve in CVEIgnoreNotForUsSet and \238 if cve in CVE_IGNORE_NFU_SET and \
240 cve not in CVEIgnoreMistriagedSet and \239 cve not in CVE_IGNORE_MISTRIAGED_LIST and \
241 handler.debian[cve]['state'] == 'FOUND':240 handler.debian[cve]['state'] == 'FOUND':
242 # check that at least one of the assigned packages exist241 # check that at least one of the assigned packages exist
243 # in Ubuntu242 # in Ubuntu
@@ -259,7 +258,7 @@ def import_debian(handler):
259 continue258 continue
260259
261 year = int(re.split('-', cve)[1])260 year = int(re.split('-', cve)[1])
262 if year < cve_limit:261 if year < CVE_LIMIT:
263 continue262 continue
264263
265 # If we already know about the CVE, skip it unless is264 # If we already know about the CVE, skip it unless is
@@ -267,7 +266,7 @@ def import_debian(handler):
267 if cve in known:266 if cve in known:
268 if mistriaged(cve):267 if mistriaged(cve):
269 # add a note about how this was originally classified268 # add a note about how this was originally classified
270 dsas[dsa]['desc'] = mistriaged_hint + dsas[dsa]['desc']269 dsas[dsa]['desc'] = MISTRIAGED_HINT + dsas[dsa]['desc']
271 else:270 else:
272 continue271 continue
273272
@@ -294,16 +293,16 @@ def import_debian(handler):
294 continue293 continue
295294
296 year = int(re.split('-', cve)[1])295 year = int(re.split('-', cve)[1])
297 if year < cve_limit:296 if year < CVE_LIMIT:
298 if args.verbose:297 if args.verbose:
299 print(f"Skipping {cve}, year {year} predates {cve_limit}", file=sys.stderr)298 print(f"Skipping {cve}, year {year} predates {CVE_LIMIT}", file=sys.stderr)
300 continue299 continue
301300
302 # If we already know about the CVE, skip it unless is mistriaged301 # If we already know about the CVE, skip it unless is mistriaged
303 if cve in known:302 if cve in known:
304 if mistriaged(cve):303 if mistriaged(cve):
305 # add a note about how this was originally classified304 # add a note about how this was originally classified
306 handler.debian[cve]['desc'] = mistriaged_hint + handler.debian[cve]['desc']305 handler.debian[cve]['desc'] = MISTRIAGED_HINT + handler.debian[cve]['desc']
307 else:306 else:
308 if args.verbose:307 if args.verbose:
309 print(f"Skipping {cve}, already known", file=sys.stderr)308 print(f"Skipping {cve}, already known", file=sys.stderr)
@@ -539,14 +538,14 @@ def dpkg_compare_versions(v1, op, v2):
539538
540539
541def get_built_using(pkgs=[]):540def get_built_using(pkgs=[]):
542 global built_using_map541 global BUILT_USING_MAP
543 if built_using_map is None:542 if BUILT_USING_MAP is None:
544 built_using_map = source_map.load_built_using_collection(543 BUILT_USING_MAP = source_map.load_built_using_collection(
545 source_map.load(data_type='packages'))544 source_map.load(data_type='packages'))
546545
547 out = ""546 out = ""
548 for pkg in pkgs:547 for pkg in pkgs:
549 out += source_map.get_built_using(built_using_map, pkg)548 out += source_map.get_built_using(BUILT_USING_MAP, pkg)
550549
551 return out550 return out
552551
@@ -602,7 +601,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
602 timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())601 timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
603602
604 # Append to timestamp file list603 # Append to timestamp file list
605 with open(f'{destdir}/check-cves.log', 'a') as f:604 with open(f'{DEST_DIR}/check-cves.log', 'a') as f:
606 f.write(605 f.write(
607 f"{timestamp} UTC - "606 f"{timestamp} UTC - "
608 f"{self.num_added} added, "607 f"{self.num_added} added, "
@@ -780,10 +779,10 @@ class CVEHandler(xml.sax.handler.ContentHandler):
780 if not self.curr_cve or not self.curr_desc:779 if not self.curr_cve or not self.curr_desc:
781 return780 return
782 # Skip CVEs we know about already unless this is a mistriaged CVE781 # Skip CVEs we know about already unless this is a mistriaged CVE
783 if self.curr_cve in self.cve_ignore and mistriaged_hint not in self.curr_desc:782 if self.curr_cve in self.cve_ignore and MISTRIAGED_HINT not in self.curr_desc:
784 return783 return
785784
786 limit = cve_limit785 limit = CVE_LIMIT
787 if not args.refresh and not args.score_refresh:786 if not args.refresh and not args.score_refresh:
788 limit = 2005787 limit = 2005
789 if int(self.curr_cve.split("-")[1]) < limit:788 if int(self.curr_cve.split("-")[1]) < limit:
@@ -832,7 +831,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
832 if subproject in source:831 if subproject in source:
833 aliases = source_map.get_all_aliases(source, subproject)832 aliases = source_map.get_all_aliases(source, subproject)
834 for hint in software_hints_from_cve_description:833 for hint in software_hints_from_cve_description:
835 if hint in common_words:834 if hint in COMMON_WORDS:
836 continue835 continue
837836
838 if hint in source[subproject]:837 if hint in source[subproject]:
@@ -863,7 +862,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
863 sys.stdout = CVEOutput(file, line_prefix)862 sys.stdout = CVEOutput(file, line_prefix)
864863
865 # Check if this was once an embargoed issue864 # Check if this was once an embargoed issue
866 if cve in EmbargoList:865 if cve in CVE_EMBARGO_LIST:
867 print('**!!** no longer embargoed **!!**')866 print('**!!** no longer embargoed **!!**')
868 print('==========================details from embargo entry==========================')867 print('==========================details from embargo entry==========================')
869 with open(os.path.join('embargoed', cve)) as f:868 with open(os.path.join('embargoed', cve)) as f:
@@ -927,7 +926,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
927 print(" - " + affected_subproject + ": " + " - ".join(926 print(" - " + affected_subproject + ": " + " - ".join(
928 software_hints_per_external_releases[affected_subproject]))927 software_hints_per_external_releases[affected_subproject]))
929 # once again, announce formerly embargoed status928 # once again, announce formerly embargoed status
930 if cve in EmbargoList:929 if cve in CVE_EMBARGO_LIST:
931 print('**!!** no longer embargoed **!!**')930 print('**!!** no longer embargoed **!!**')
932 print('**!!** ensure this is correct before unembargoing **!!**')931 print('**!!** ensure this is correct before unembargoing **!!**')
933932
@@ -940,12 +939,12 @@ class CVEHandler(xml.sax.handler.ContentHandler):
940 reason = ""939 reason = ""
941 packages = []940 packages = []
942 # Skip CVEs that are obviously not about Ubuntu941 # Skip CVEs that are obviously not about Ubuntu
943 for s in ignore_strings:942 for s in IGNORE_STRINGS:
944 if re.search('(^| )%s' % re.escape(s), self.cve_data[cve]['desc'], flags=re.MULTILINE) and self.cve_data[cve]['desc'].find("Linux") < 0:943 if re.search('(^| )%s' % re.escape(s), self.cve_data[cve]['desc'], flags=re.MULTILINE) and self.cve_data[cve]['desc'].find("Linux") < 0:
945 action = 'ignore'944 action = 'ignore'
946 reason = s945 reason = s
947 # if cve is in embargo list (but now public), default to unembargo action946 # if cve is in embargo list (but now public), default to unembargo action
948 if cve in EmbargoList:947 if cve in CVE_EMBARGO_LIST:
949 action = 'unembargo'948 action = 'unembargo'
950 reason = ""949 reason = ""
951 else:950 else:
@@ -1011,36 +1010,36 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1011 return words1010 return words
10121011
1013 def human_process_cve(self, cve, action='skip', reason='', package=''):1012 def human_process_cve(self, cve, action='skip', reason='', package=''):
1014 info = ''1013 user_input = ''
1015 while info == "" or info[0] not in ['i', 'a', 's', 'q', 'r']:1014 while user_input == "" or user_input[0] not in ['i', 'a', 's', 'q', 'r']:
1016 prompt_user(f'\nA]dd (or R]epeat), I]gnore forever, S]kip for now, or Q]uit? [{action}] ')1015 prompt_user(f'\nA]dd (or R]epeat), I]gnore forever, S]kip for now, or Q]uit? [{action}] ')
1017 info = sys.stdin.readline().strip().lower()1016 user_input = sys.stdin.readline().strip().lower()
1018 if info == "":1017 if user_input == "":
1019 info = action1018 user_input = action
10201019
1021 if info.startswith('q'):1020 if user_input.startswith('q'):
1022 self.printReport()1021 self.printReport()
1023 self.updateTimestamp()1022 self.updateTimestamp()
1024 sys.exit(0)1023 sys.exit(0)
1025 elif info.startswith('a') or info.startswith('r'):1024 elif user_input.startswith('a') or user_input.startswith('r'):
1026 do_repeat = False1025 do_repeat = False
1027 if info.startswith('r'):1026 if user_input.startswith('r'):
1028 info = self.saved_package1027 user_input = self.saved_package
1029 do_repeat = True1028 do_repeat = True
1030 else:1029 else:
1031 info = ""1030 user_input = ""
1032 while info == "":1031 while user_input == "":
1033 prompt_user('Package(s) affected? ')1032 prompt_user('Package(s) affected? ')
1034 if package == "":1033 if package == "":
1035 package = self.saved_package1034 package = self.saved_package
1036 if package != "":1035 if package != "":
1037 prompt_user(f'[{package}] ')1036 prompt_user(f'[{package}] ')
1038 info = sys.stdin.readline().strip()1037 user_input = sys.stdin.readline().strip()
1039 if info == '':1038 if user_input == '':
1040 info = package1039 user_input = package
1041 self.saved_package = info1040 self.saved_package = user_input
10421041
1043 dst = self.add_cve(cve, info.split(), None)1042 dst = self.add_cve(cve, user_input.split(), None)
10441043
1045 if do_repeat:1044 if do_repeat:
1046 subprocess.call(['./scripts/active_dup', self.saved_cve, cve])1045 subprocess.call(['./scripts/active_dup', self.saved_cve, cve])
@@ -1048,11 +1047,11 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1048 self.saved_cve = cve1047 self.saved_cve = cve
10491048
1050 print('\n===================== Dependant packages ======================')1049 print('\n===================== Dependant packages ======================')
1051 print(f' Detecting packages built using: {info}...', end='')1050 print(f' Detecting packages built using: {user_input}...', end='')
1052 sys.stdout.flush()1051 sys.stdout.flush()
1053 built_using = ""1052 built_using = ""
1054 try:1053 try:
1055 built_using = get_built_using(info)1054 built_using = get_built_using(user_input)
1056 except Exception as e:1055 except Exception as e:
1057 print(f"ERROR: {e}", file=sys.stderr)1056 print(f"ERROR: {e}", file=sys.stderr)
1058 pass # for now just show the error but don't break triage1057 pass # for now just show the error but don't break triage
@@ -1062,13 +1061,13 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1062 print(source_map.get_built_using_header())1061 print(source_map.get_built_using_header())
1063 print(built_using)1062 print(built_using)
1064 print("IMPORTANT: the above packages are candidates for rebuilds when fixes are applied to:")1063 print("IMPORTANT: the above packages are candidates for rebuilds when fixes are applied to:")
1065 print(" %s" % "\n ".join(info))1064 print(" %s" % "\n ".join(user_input))
1066 else:1065 else:
1067 print("none detected")1066 print("none detected")
10681067
1069 elif info.startswith('i'):1068 elif user_input.startswith('i'):
1070 info = ""1069 ignored_reason = ""
1071 while info == "":1070 while ignored_reason == "":
1072 print('Reason to be ignored?')1071 print('Reason to be ignored?')
1073 prompts = []1072 prompts = []
10741073
@@ -1085,24 +1084,23 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1085 print(f" {chr(97 + i)}) {prompts[i]}")1084 print(f" {chr(97 + i)}) {prompts[i]}")
1086 prompt_user(' > ')1085 prompt_user(' > ')
10871086
1088 info = sys.stdin.readline().strip()1087 ignored_reason_input = sys.stdin.readline().strip()
1089 if len(info) == 1 and info.isalpha():1088 # NOTE: user is selecting a choice from prompts
1089 if len(ignored_reason_input) == 1 and ignored_reason_input.isalpha():
1090 try:1090 try:
1091 # ord('a') == 971091 # ord('a') == 97
1092 info = prompts[ord(info) - 97]1092 ignored_reason = prompts[ord(ignored_reason_input) - 97]
1093 except IndexError:1093 except IndexError:
1094 print('\nError: invalid reason.\n')1094 print('\nError: invalid reason.\n')
1095 info = ""1095 # TODO: reassess if < 2 is a better value
1096 # Enter defaults to only suggestion if only one exists1096 # or add a mechanism to catch certain 3 letter words
1097 elif len(info) == 0 and len(prompts) == 1:1097 # e.g., IBM is currently invalid
1098 info = prompts[0]1098 elif len(ignored_reason_input) < 3: # Fat fingers protection
1099 elif len(info) < 3: # Fat fingers protection
1100 print('\nError: Reason must be at least 3 characters long!\n')1099 print('\nError: Reason must be at least 3 characters long!\n')
1101 info = ""1100 self.saved_ignore_cache.insert(ignored_reason)
1102 self.saved_ignore_cache.insert(info)1101 self.ignore_cve(cve, ignored_reason)
1103 self.ignore_cve(cve, info)
11041102
1105 elif info.startswith('s'):1103 elif user_input.startswith('s'):
1106 self.skip_cve()1104 self.skip_cve()
1107 print('')1105 print('')
11081106
@@ -1146,7 +1144,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1146 if priority not in cve_lib.priorities and not priority == 'untriaged':1144 if priority not in cve_lib.priorities and not priority == 'untriaged':
1147 raise ValueError(f'Invalid priority on line {line_num}:\n{orig_line}')1145 raise ValueError(f'Invalid priority on line {line_num}:\n{orig_line}')
11481146
1149 if os.path.exists(f'{destdir}/active/{cve}'):1147 if os.path.exists(f'{DEST_DIR}/active/{cve}'):
1150 raise ValueError(f'Updating an existing CVE is not supported (line {line_num}):\n{orig_line}')1148 raise ValueError(f'Updating an existing CVE is not supported (line {line_num}):\n{orig_line}')
11511149
1152 if preprocess:1150 if preprocess:
@@ -1160,7 +1158,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1160 if action == 'edit':1158 if action == 'edit':
1161 _spawn_editor(cve_path)1159 _spawn_editor(cve_path)
1162 elif action == 'unembargo':1160 elif action == 'unembargo':
1163 if cve not in EmbargoList:1161 if cve not in CVE_EMBARGO_LIST:
1164 raise ValueError(f'CVE {cve} is not in the embargo database (line {line_num}):\n{orig_line}')1162 raise ValueError(f'CVE {cve} is not in the embargo database (line {line_num}):\n{orig_line}')
11651163
1166 if os.path.exists(os.path.join('active', cve)):1164 if os.path.exists(os.path.join('active', cve)):
@@ -1198,7 +1196,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1198 desc = ''1196 desc = ''
11991197
1200 # Check if this was once an embargoed issue1198 # Check if this was once an embargoed issue
1201 if cve in EmbargoList:1199 if cve in CVE_EMBARGO_LIST:
1202 desc += '# **!!** no longer embargoed **!!**\n'1200 desc += '# **!!** no longer embargoed **!!**\n'
1203 desc += '# ==========================details from embargo entry==========================\n'1201 desc += '# ==========================details from embargo entry==========================\n'
1204 with open(os.path.join('embargoed', cve)) as f:1202 with open(os.path.join('embargoed', cve)) as f:
@@ -1238,7 +1236,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1238 action = 'skip'1236 action = 'skip'
1239 data = ""1237 data = ""
1240 # Skip CVEs that are obviously not about Ubuntu1238 # Skip CVEs that are obviously not about Ubuntu
1241 for s in ignore_strings:1239 for s in IGNORE_STRINGS:
1242 if self.cve_data[cve]['desc'].find(s) >= 0 and self.cve_data[cve]['desc'].find("Linux") < 0:1240 if self.cve_data[cve]['desc'].find(s) >= 0 and self.cve_data[cve]['desc'].find("Linux") < 0:
1243 action = 'ignore'1241 action = 'ignore'
1244 data = s1242 data = s
@@ -1255,11 +1253,11 @@ class CVEHandler(xml.sax.handler.ContentHandler):
12551253
1256 def add_cve(self, cve, packages, priority=None):1254 def add_cve(self, cve, packages, priority=None):
1257 # remove from not-for-us.txt if adding and ensure we remove any1255 # remove from not-for-us.txt if adding and ensure we remove any
1258 # mistriaged_hint from the description1256 # MISTRIAGED_HINT from the description
1259 if cve in CVEIgnoreNotForUsSet:1257 if cve in CVE_IGNORE_NFU_SET:
1260 cmd = ['sed', '-i', f'/^{cve} #.*$/d', './ignored/not-for-us.txt']1258 cmd = ['sed', '-i', f'/^{cve} #.*$/d', './ignored/not-for-us.txt']
1261 subprocess.call(cmd)1259 subprocess.call(cmd)
1262 self.cve_data[cve]['desc'] = self.cve_data[cve]['desc'].replace(mistriaged_hint, '')1260 self.cve_data[cve]['desc'] = self.cve_data[cve]['desc'].replace(MISTRIAGED_HINT, '')
12631261
1264 # Build up list of reference urls1262 # Build up list of reference urls
1265 ref_urls = []1263 ref_urls = []
@@ -1376,10 +1374,10 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1376 self.num_added += 11374 self.num_added += 1
13771375
1378 def ignore_cve(self, cve, reason):1376 def ignore_cve(self, cve, reason):
1379 # Append to ignore list unless is already in CVEIgnoreList and then1377 # Append to ignore list unless is already in cve_ignore_list and then
1380 # append to the ignored/ignore-mistriaged.txt1378 # append to the ignored/ignore-mistriaged.txt
1381 txtfile = 'ignore-mistriaged.txt' if cve in CVEIgnoreNotForUsSet else 'not-for-us.txt'1379 txtfile = 'ignore-mistriaged.txt' if cve in CVE_IGNORE_NFU_SET else 'not-for-us.txt'
1382 with open(f'{destdir}/ignored/{txtfile}', 'a') as f:1380 with open(f'{DEST_DIR}/ignored/{txtfile}', 'a') as f:
1383 f.write(f'{cve} # {reason}\n')1381 f.write(f'{cve} # {reason}\n')
13841382
1385 self.num_ignored += 11383 self.num_ignored += 1
@@ -1388,74 +1386,74 @@ class CVEHandler(xml.sax.handler.ContentHandler):
1388 self.num_skipped += 11386 self.num_skipped += 1
13891387
13901388
1391ignored_notforus_path = 'ignored/not-for-us.txt'1389IGNORED_NFU_PATH = 'ignored/not-for-us.txt'
1392if destdir != './' and destdir != '.':1390if DEST_DIR != './' and DEST_DIR != '.':
1393 ignored_notforus_path = os.path.join(destdir, ignored_notforus_path)1391 IGNORED_NFU_PATH = os.path.join(DEST_DIR, IGNORED_NFU_PATH)
1394# CVEIgnoreNotForUsSet is a set of all CVEs that we have previously1392# CVE_IGNORE_NFU_SET is a set of all CVEs that we have previously
1395# chosen to ignore since they don't apply to software in Ubuntu1393# chosen to ignore since they don't apply to software in Ubuntu
1396CVEIgnoreNotForUsSet = set(cve_lib.parse_CVEs_from_uri(ignored_notforus_path))1394CVE_IGNORE_NFU_SET = set(cve_lib.parse_CVEs_from_uri(IGNORED_NFU_PATH))
13971395
1398ignored_mistriaged_path = 'ignored/ignore-mistriaged.txt'1396IGNORED_MISTRIAGED_PATH = 'ignored/ignore-mistriaged.txt'
1399if destdir != './' and destdir != '.':1397if DEST_DIR != './' and DEST_DIR != '.':
1400 ignored_mistriaged_path = os.path.join(destdir, ignored_mistriaged_path)1398 IGNORED_MISTRIAGED_PATH = os.path.join(DEST_DIR, IGNORED_MISTRIAGED_PATH)
1401# CVEIgnoreMistriagedSet is a set of all CVEs that we want to definitely1399# CVE_IGNORE_MISTRIAGED_LIST is a set of all CVEs that we want to definitely
1402# ignore when doing mistriaged CVE detection - they should exist in both1400# ignore when doing mistriaged CVE detection - they should exist in both
1403# CVEIgnoreNotForUsList and CVEIgnoreMistriagedList1401# CVEIgnoreNotForUsList and CVEIgnoreMistriagedList
1404CVEIgnoreMistriagedSet = set(cve_lib.parse_CVEs_from_uri(ignored_mistriaged_path))1402CVE_IGNORE_MISTRIAGED_LIST = set(cve_lib.parse_CVEs_from_uri(IGNORED_MISTRIAGED_PATH))
14051403
1406# CVEIgnoreList is a list of all CVEs we know about already. These will be1404# cve_ignore_list is a list of all CVEs we know about already. These will be
1407# ignored when checking MITRE for new CVEs1405# ignored when checking MITRE for new CVEs
1408CVEIgnoreList = list(CVEIgnoreNotForUsSet)1406cve_ignore_list = list(CVE_IGNORE_NFU_SET)
14091407
1410CVEKnownList = []1408cve_known_list = []
1411CVEKnownList += [cve for cve in os.listdir(destdir + "/ignored/") if cve.startswith('CVE-')]1409cve_known_list += [cve for cve in os.listdir(DEST_DIR + "/ignored/") if cve.startswith('CVE-')]
1412CVEKnownList += [cve for cve in os.listdir(destdir + "/retired/") if cve.startswith('CVE-')]1410cve_known_list += [cve for cve in os.listdir(DEST_DIR + "/retired/") if cve.startswith('CVE-')]
1413(ActiveList, EmbargoList) = cve_lib.get_cve_list()1411(CVE_ACTIVE_LIST, CVE_EMBARGO_LIST) = cve_lib.get_cve_list()
1414CVEKnownList += [cve for cve in ActiveList if cve not in EmbargoList]1412cve_known_list += [cve for cve in CVE_ACTIVE_LIST if cve not in CVE_EMBARGO_LIST]
14151413
1416if not args.refresh and not args.mistriaged and not args.score_refresh:1414if not args.refresh and not args.mistriaged and not args.score_refresh:
1417 CVEIgnoreList += CVEKnownList1415 cve_ignore_list += cve_known_list
14181416
1419if args.known:1417if args.known:
1420 cvelist = CVEIgnoreList1418 cvelist = cve_ignore_list
1421 if args.skip_nfu:1419 if args.skip_nfu:
1422 cvelist = CVEKnownList1420 cvelist = cve_known_list
1423 for cve in sorted(cvelist):1421 for cve in sorted(cvelist):
1424 print(cve)1422 print(cve)
1425 sys.exit(0)1423 sys.exit(0)
14261424
1427parser = xml.sax.make_parser()1425parser = xml.sax.make_parser()
1428handler = CVEHandler(CVEIgnoreList)1426handler = CVEHandler(cve_ignore_list)
1429parser.setContentHandler(handler)1427parser.setContentHandler(handler)
14301428
1431# if has specified to triage only specific CVEs, check these are not1429# if has specified to triage only specific CVEs, check these are not
1432# ignored1430# ignored
1433specific_cves = None1431SPECIFIC_CVES = None
1434if args.cve:1432if args.cve:
1435 specific_cves = set()1433 SPECIFIC_CVES = set()
1436 for cve in args.cve.split(","):1434 for cve in args.cve.split(","):
1437 # ignore empty CVE1435 # ignore empty CVE
1438 if cve.strip() == "":1436 if cve.strip() == "":
1439 continue1437 continue
1440 # error out if is ignored1438 # error out if is ignored
1441 if cve in CVEIgnoreList:1439 if cve in cve_ignore_list:
1442 print(f"{cve} already exists in UCT - please remove it then retriage.")1440 print(f"{cve} already exists in UCT - please remove it then retriage.")
1443 sys.exit(1)1441 sys.exit(1)
1444 specific_cves.add(cve)1442 SPECIFIC_CVES.add(cve)
14451443
1446untriaged_json = ""1444UNTRIAGED_JSON = ""
1447if args.untriaged:1445if args.untriaged:
1448 untriaged_json = read_locate_cves_output(args.untriaged)1446 UNTRIAGED_JSON = read_locate_cves_output(args.untriaged)
1449 args.uris.append(untriaged_json)1447 args.uris.append(UNTRIAGED_JSON)
14501448
1451if args.mbox:1449if args.mbox:
1452 untriaged_json = read_mbox_file(args.mbox)1450 UNTRIAGED_JSON = read_mbox_file(args.mbox)
1453 args.uris.append(untriaged_json)1451 args.uris.append(UNTRIAGED_JSON)
14541452
1455rhel8oval_import_json = ""1453rhel8oval_import_json = ""
1456if args.rhel8oval:1454if args.rhel8oval:
1457 untriaged_json = read_rhel8oval_file(args.rhel8oval)1455 UNTRIAGED_JSON = read_rhel8oval_file(args.rhel8oval)
1458 args.uris.append(untriaged_json)1456 args.uris.append(UNTRIAGED_JSON)
14591457
1460debian_import_json = ""1458debian_import_json = ""
1461if (args.import_missing_debian or args.mistriaged) and handler.debian is not None:1459if (args.import_missing_debian or args.mistriaged) and handler.debian is not None:
@@ -1483,8 +1481,8 @@ for uri in args.uris:
1483 print('')1481 print('')
14841482
1485# Leaving our fake json around is icky1483# Leaving our fake json around is icky
1486if os.path.exists(untriaged_json):1484if os.path.exists(UNTRIAGED_JSON):
1487 os.unlink(untriaged_json)1485 os.unlink(UNTRIAGED_JSON)
1488if os.path.exists(debian_import_json):1486if os.path.exists(debian_import_json):
1489 os.unlink(debian_import_json)1487 os.unlink(debian_import_json)
14901488
@@ -1508,7 +1506,7 @@ def refresh_cves(cve_refresh_list, full_refresh=True):
1508 # Find the on-disk CVE file1506 # Find the on-disk CVE file
1509 cvefile = ""1507 cvefile = ""
1510 for status in ['active', 'retired', 'ignored']:1508 for status in ['active', 'retired', 'ignored']:
1511 check = f'{destdir}/{status}/{cve}'1509 check = f'{DEST_DIR}/{status}/{cve}'
1512 if os.path.exists(check):1510 if os.path.exists(check):
1513 cvefile = check1511 cvefile = check
1514 break1512 break
@@ -1568,10 +1566,10 @@ def refresh_cves(cve_refresh_list, full_refresh=True):
15681566
15691567
1570if args.refresh or args.score_refresh:1568if args.refresh or args.score_refresh:
1571 if args.cve and specific_cves is not set():1569 if args.cve and SPECIFIC_CVES is not set():
1572 cve_refresh_list = specific_cves1570 cve_refresh_list = SPECIFIC_CVES
1573 else:1571 else:
1574 cve_refresh_list = CVEKnownList1572 cve_refresh_list = cve_known_list
15751573
1576 # with OptParse args.refresh and args.score_refresh will each1574 # with OptParse args.refresh and args.score_refresh will each
1577 # either be True or None. We want full_refresh to be False when1575 # either be True or None. We want full_refresh to be False when
@@ -1590,12 +1588,12 @@ if experimental:
1590 handler.display_command_file_usage(fout, '# ')1588 handler.display_command_file_usage(fout, '# ')
15911589
1592for cve in new_cves:1590for cve in new_cves:
1593 if args.cve and cve not in specific_cves:1591 if args.cve and cve not in SPECIFIC_CVES:
1594 # ignore this cve1592 # ignore this cve
1595 continue1593 continue
1596 # if this got marked as mistriaged, probablistically choose it for1594 # if this got marked as mistriaged, probablistically choose it for
1597 # processing1595 # processing
1598 if mistriaged_hint in handler.cve_data[cve]['desc']:1596 if MISTRIAGED_HINT in handler.cve_data[cve]['desc']:
1599 if args.mistriaged == 0:1597 if args.mistriaged == 0:
1600 # ignore this one1598 # ignore this one
1601 continue1599 continue

Subscribers

People subscribed via source and target branches