Skip to content

Commit 354560f

Browse files
PrajwalM2212pdxjohnny
authored andcommitted
Remove verbose and quiet args
1 parent 1cf5636 commit 354560f

File tree

7 files changed

+89
-104
lines changed

7 files changed

+89
-104
lines changed

cve_bin_tool/NVDAutoUpdate.py

+30-42
Original file line numberDiff line numberDiff line change
@@ -48,18 +48,12 @@
4848

4949

5050
def get_cvelist(
51-
output,
52-
dbname,
53-
quiet,
54-
supplement=True,
55-
json_feed=JSON_FEED,
56-
json_zip=JSON_ZIP,
57-
**kargs
51+
output, dbname, supplement=True, json_feed=JSON_FEED, json_zip=JSON_ZIP, **kargs
5852
):
5953
""" Get list of CVEs and add to the database """
6054
if not os.path.exists(output):
6155
os.makedirs(output, 0o750)
62-
conn = init_database(dbname, quiet)
56+
conn = init_database(dbname)
6357

6458
today = str(datetime.date.today())
6559
year = str(int(today[:4]))
@@ -72,7 +66,7 @@ def get_cvelist(
7266
r"nvdcve-1.1-[0-9]*\.json\.zip", r_feed.read().decode("utf-8")
7367
):
7468
t = threading.Thread(
75-
target=download_cves, args=(filename, output, json_zip, kargs, year, quiet)
69+
target=download_cves, args=(filename, output, json_zip, kargs, year)
7670
)
7771
t.start()
7872
threads.append(t)
@@ -118,30 +112,27 @@ def get_cvelist(
118112
conn.close()
119113

120114

121-
def download_cves(filename, output, json_zip, kargs, year, quiet):
115+
def download_cves(filename, output, json_zip, kargs, year):
122116
r_file = urlopen(json_zip + filename, **kargs)
123117
filepath = os.path.join(output, filename)
124118
if year in filename or not os.path.exists(filepath):
125119
with open(filepath, "wb") as file_handle:
126120
for chunk in r_file:
127121
file_handle.write(chunk)
128122
file_handle.close()
129-
if not quiet:
130-
if year in filename:
131-
LOGGER.debug("Updated current year file " + filename)
132-
# check only 2019 for now (old files not updated)
133-
if check_cve_zip(2019):
134-
if not quiet:
135-
LOGGER.debug("Verified 2019 zipfile against published sha256 sum")
136-
else:
137-
LOGGER.error(
138-
"Error: failed to verify zipfile against published sha256 sum",
139-
)
123+
if year in filename:
124+
LOGGER.debug("Updated current year file " + filename)
125+
# check only 2019 for now (old files not updated)
126+
if check_cve_zip(2019):
127+
LOGGER.debug("Verified 2019 zipfile against published sha256 sum")
140128
else:
141-
LOGGER.debug("Creating new file " + filename)
129+
LOGGER.error(
130+
"Error: failed to verify zipfile against published sha256 sum",
131+
)
132+
else:
133+
LOGGER.debug("Creating new file " + filename)
142134
else:
143-
if not quiet:
144-
LOGGER.debug("Previous year file: " + filename + " already exists")
135+
LOGGER.debug("Previous year file: " + filename + " already exists")
145136

146137

147138
def check_cve_zip(year):
@@ -173,9 +164,9 @@ def check_cve_zip(year):
173164
return False
174165

175166

176-
def init_database(dbname, quiet):
167+
def init_database(dbname):
177168
""" Create new database if needed """
178-
if not quiet and (not os.path.isfile(dbname)):
169+
if not os.path.isfile(dbname):
179170
LOGGER.debug("Database file does not exist. Initializing it")
180171
conn = sqlite3.connect(dbname)
181172
db_cursor = conn.cursor()
@@ -315,7 +306,7 @@ def extract_data(nvddir):
315306

316307
jsonfile.close()
317308
except Exception as exception:
318-
LO("Exception in extract_data: " + str(exception))
309+
LOGGER.error("Exception in extract_data: " + str(exception))
319310

320311
return (
321312
cve_number,
@@ -395,7 +386,7 @@ def display_data(conn):
395386
LOGGER.info(row)
396387

397388

398-
def get_cvelist_if_stale(nvddir, dbname, quiet):
389+
def get_cvelist_if_stale(nvddir, dbname):
399390
""" If the local copy of the cvelist is more than a day old, download a new one.
400391
This allows some caching so you don't have to wait for the full download with every
401392
single execution. """
@@ -406,12 +397,11 @@ def get_cvelist_if_stale(nvddir, dbname, quiet):
406397
datetime.datetime.today()
407398
- datetime.datetime.fromtimestamp(os.path.getmtime(latest_zipfile))
408399
) > datetime.timedelta(hours=24):
409-
if not quiet:
410-
LOGGER.debug("Updating CVE data. This will take a few minutes.")
411-
get_cvelist(nvddir, dbname, quiet)
400+
LOGGER.debug("Updating CVE data. This will take a few minutes.")
401+
get_cvelist(nvddir, dbname)
412402

413403
if not os.path.isfile(dbname):
414-
conn = init_database(dbname, quiet)
404+
conn = init_database(dbname)
415405
(
416406
cve_number,
417407
vendor_name,
@@ -433,24 +423,22 @@ def get_cvelist_if_stale(nvddir, dbname, quiet):
433423
)
434424
conn.close()
435425

436-
elif not quiet:
437-
LOGGER.debug(
438-
"Last Update: "
439-
+ datetime.date.fromtimestamp(os.path.getmtime(dbname)).isoformat()
440-
)
441-
LOGGER.debug("Local database has been updated in the past 24h.")
442-
LOGGER.debug('New data not downloaded. Use "-u now" to force an update')
426+
LOGGER.debug(
427+
"Last Update: "
428+
+ datetime.date.fromtimestamp(os.path.getmtime(dbname)).isoformat()
429+
)
430+
LOGGER.debug("Local database has been updated in the past 24h.")
431+
LOGGER.debug('New data not downloaded. Use "-u now" to force an update')
443432

444433

445434
class NVDSQLite(object):
446435
""" Methods for NVD stored in sqlite """
447436

448-
def __init__(self, disk_location=DISK_LOCATION_DEFAULT, quiet=False):
437+
def __init__(self, disk_location=DISK_LOCATION_DEFAULT):
449438
""" Set location on disk where NVD data cache will reside.
450439
Connect to SQLite database"""
451440
self.disk_location = disk_location
452441
self.conn = None
453-
self.quiet = quiet
454442

455443
@property
456444
def dbname(self):
@@ -506,7 +494,7 @@ def get_cves(self, *vendor_product_pairs):
506494

507495
def get_cvelist_if_stale(self):
508496
""" Update CVEs data from NVD if stale."""
509-
get_cvelist_if_stale(self.nvddir, self.dbname, self.quiet)
497+
get_cvelist_if_stale(self.nvddir, self.dbname)
510498

511499
@classmethod
512500
def clear_cached_data(cls):

cve_bin_tool/cli.py

+45-49
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ class Scanner(object):
4848

4949
CHECKER_ENTRYPOINT = "cve_bin_tool.checker"
5050

51-
def __init__(self, nvd, checkers=None, verbose=True, logger=None):
51+
def __init__(self, nvd, checkers=None, logger=None):
5252
if logger is None:
5353
logger = LOGGER.getChild(self.__class__.__name__)
5454
# Load checkers if not given
@@ -57,10 +57,9 @@ def __init__(self, nvd, checkers=None, verbose=True, logger=None):
5757
self.nvd = nvd
5858
self.checkers = checkers
5959
self.logger = logger
60-
self.verbose = verbose
6160
self.all_cves = defaultdict(dict)
6261
self.files_with_cve = 0
63-
self.logger.info("Checkers loaded: %s", ", ".join(self.checkers.keys()))
62+
self.logger.info("Checkers loaded: %s" % (", ".join(self.checkers.keys())))
6463

6564
@staticmethod
6665
def vendor_package_pairs(docstring):
@@ -98,18 +97,18 @@ def available_checkers(cls):
9897
checker_list = [item.name for item in checkers]
9998
return checker_list
10099

101-
def remove_skiplist(self, skips=None, quiet=False):
100+
def remove_skiplist(self, skips=None):
102101
# Take out any checkers that are on the skip list
103102
# (string of comma-delimited checker names)
104103
skiplist = skips.split(",") if skips else []
105104
for skipme in skiplist:
106105
if skipme in self.checkers:
107106
del self.checkers[skipme]
108-
if not quiet:
109-
self.logger.debug("Skipping checker: {}".format(skipme))
107+
self.logger.debug("Skipping checker: {}".format(skipme))
110108
else:
111-
if not quiet:
112-
self.logger.error("Checker {} is not a valid checker name".format(skipme))
109+
self.logger.error(
110+
"Checker {} is not a valid checker name".format(skipme)
111+
)
113112

114113
def print_checkers(self):
115114
self.logger.info("Checkers: {}".format(", ".join(self.checkers.keys())))
@@ -133,7 +132,7 @@ def scan_file(self, filename):
133132
"""Scans a file to see if it contains any of the target libraries,
134133
and whether any of those contain CVEs"""
135134

136-
self.logger.debug("Scanning file: %r", filename)
135+
self.logger.debug("Scanning file: %r" % filename)
137136

138137
# Do not try to scan symlinks
139138
if os.path.islink(filename):
@@ -199,13 +198,15 @@ def scan_file(self, filename):
199198
if found_cves.keys():
200199
self.files_with_cve = self.files_with_cve + 1
201200
self.all_cves[modulename][version] = found_cves
202-
if self.verbose:
203-
self.logger.info(filename, result["is_or_contains"], modulename, version)
204-
if found_cves.keys():
205-
self.logger.info("Known CVEs in version " + str(version))
206-
self.logger.info(", ".join(found_cves.keys()))
201+
self.logger.info(
202+
"%s %s %s %s"
203+
% (filename, result["is_or_contains"], modulename, version)
204+
)
205+
if found_cves.keys():
206+
self.logger.info("Known CVEs in version " + str(version))
207+
self.logger.info(", ".join(found_cves.keys()))
207208

208-
self.logger.debug("Done scanning file: %r", filename)
209+
self.logger.debug("Done scanning file: %r" % filename)
209210
return self.all_cves
210211

211212
def extract_and_scan(self, filename, walker=None):
@@ -250,7 +251,9 @@ def scan_and_or_extract_file(scanner, ectx, walker, should_extract, filepath):
250251
# Attempt to extract the file and scan the contents
251252
if ectx.can_extract(filepath):
252253
if not should_extract:
253-
LOGGER.debug("%s is an archive. Pass " % (filepath,) + "-x option to auto-extract")
254+
LOGGER.warning(
255+
"%s is an archive. Pass " % (filepath,) + "-x option to auto-extract"
256+
)
254257
return
255258
for filename in walker([ectx.extract(filepath)]):
256259
scan_and_or_extract_file(scanner, ectx, walker, should_extract, filename)
@@ -261,20 +264,22 @@ def extract_file(ectx, walker, should_extract, filepath, file_list):
261264
if ectx.can_extract(filepath):
262265
if not should_extract:
263266
file_list.append(filepath)
264-
LOGGER.debug("%s is an archive. Pass " % (filepath,) + "-x option to auto-extract")
267+
LOGGER.warning(
268+
"%s is an archive. Pass " % (filepath,) + "-x option to auto-extract"
269+
)
265270
return
266271
for filename in walker([ectx.extract(filepath)]):
267272
extract_file(ectx, walker, should_extract, filename, file_list)
268273
file_list.append(filepath)
269274

270275

271276
def scan_files(scanning_file, args):
272-
nvd = NVDSQLite(quiet=args["quiet"])
277+
nvd = NVDSQLite()
273278
if args["update"] != "never":
274279
nvd.get_cvelist_if_stale()
275280
with nvd:
276-
scanner = Scanner(nvd, verbose=args["verbose"])
277-
scanner.remove_skiplist(args["skips"], args["quiet"])
281+
scanner = Scanner(nvd)
282+
scanner.remove_skiplist(args["skips"])
278283
scanner.scan_file(scanning_file)
279284
return scanner.files_with_cve
280285

@@ -313,13 +318,6 @@ def main(argv=None, outfile=sys.stdout):
313318
parser.add_argument(
314319
"-x", "--extract", action="store_true", help="autoextract compressed files"
315320
)
316-
parser.add_argument(
317-
"-v",
318-
"--verbose",
319-
action="store_true",
320-
help="details on found issues as script runs",
321-
)
322-
parser.add_argument("-q", "--quiet", action="store_true", help="suppress output")
323321
parser.add_argument(
324322
"-l",
325323
"--log",
@@ -357,10 +355,10 @@ def main(argv=None, outfile=sys.stdout):
357355
args = parser.parse_args(argv[1:])
358356
except SystemExit:
359357
# override default argparse exit(2) behaviour so positive numbers can indicate
360-
# number of cves (useful in quiet mode)
361358
sys.exit(-2)
362359

363-
logging.basicConfig(level=args.log_level)
360+
if args.log_level:
361+
LOGGER.setLevel(args.log_level)
364362

365363
if platform.system() != "Linux":
366364
warning_nolinux = """
@@ -386,25 +384,22 @@ def main(argv=None, outfile=sys.stdout):
386384
).walk
387385

388386
if args.update == "now":
389-
if not args.quiet:
390-
LOGGER.debug("Removing all cached CVE data.")
387+
LOGGER.debug("Removing all cached CVE data.")
391388
NVDSQLite.clear_cached_data()
392389

393390
# Single-thread mode
394391
if not args.multithread:
395392
# Close database when done
396-
nvd = NVDSQLite(quiet=args.quiet)
393+
nvd = NVDSQLite()
397394
# Update CVE database
398395
if args.update != "never":
399-
if not args.quiet:
400-
LOGGER.debug("Checking if CVE data needs an update.")
396+
LOGGER.debug("Checking if CVE data needs an update.")
401397
nvd.get_cvelist_if_stale()
402398
with nvd:
403399
extractor = Extractor()
404-
scanner = Scanner(nvd, verbose=args.verbose)
405-
scanner.remove_skiplist(args.skips, args.quiet)
406-
if args.verbose:
407-
scanner.print_checkers()
400+
scanner = Scanner(nvd)
401+
scanner.remove_skiplist(args.skips)
402+
scanner.print_checkers()
408403

409404
with extractor() as ectx:
410405
if os.path.isdir(args.directory):
@@ -417,21 +412,22 @@ def main(argv=None, outfile=sys.stdout):
417412
scanner, ectx, walker, args.extract, args.directory
418413
)
419414

420-
if not args.quiet:
421-
LOGGER.info("")
422-
LOGGER.info("Overall CVE summary: ")
423-
LOGGER.info(
424-
"There are" + str(scanner.files_with_cve) + "files with known CVEs detected"
425-
)
426-
if (not args.quiet) and scanner.files_with_cve > 0:
415+
LOGGER.info("")
416+
LOGGER.info("Overall CVE summary: ")
417+
LOGGER.info(
418+
"There are "
419+
+ str(scanner.files_with_cve)
420+
+ " files with known CVEs detected"
421+
)
422+
if scanner.files_with_cve > 0:
427423
affected_string = ", ".join(
428424
map(
429425
lambda module_version: " ".join(str(module_version)),
430426
scanner.affected(),
431427
)
432428
)
433429
LOGGER.info("Known CVEs in %s:" % (affected_string,))
434-
output_cves(outfile, scanner.all_cves, include_details=args.verbose)
430+
output_cves(outfile, scanner.all_cves)
435431

436432
# Use the number of files with known cves as error code
437433
# as requested by folk planning to automate use of this script.
@@ -442,12 +438,12 @@ def main(argv=None, outfile=sys.stdout):
442438
else:
443439

444440
def worker():
445-
nvd = NVDSQLite(quiet=args.quiet)
441+
nvd = NVDSQLite()
446442
if args.update != "never":
447443
nvd.get_cvelist_if_stale()
448444
with nvd:
449-
scanner = Scanner(nvd, verbose=args.verbose)
450-
scanner.remove_skiplist(args.skips, args.quiet)
445+
scanner = Scanner(nvd)
446+
scanner.remove_skiplist(args.skips)
451447
while True:
452448
scan_target = q.get()
453449
if not scan_target:

cve_bin_tool/csv2cve.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,13 @@ def csv2cve(filename):
5151
csvdata = csv.DictReader(csvfile, delimiter=",") # "," is default anyhow
5252

5353
if csvdata is None or csvdata.fieldnames is None:
54-
LOGGER.error("Error: invalid CSV", file=sys.stderr)
54+
LOGGER.error("Error: invalid CSV")
5555
return ERR_BADCSV
5656

5757
required_columns = ["vendor", "package", "version"]
5858
for column in required_columns:
5959
if column not in csvdata.fieldnames:
60-
LOGGER.error("Error: no {} column found".format(column), file=sys.stderr)
60+
LOGGER.error("Error: no {} column found".format(column))
6161
return ERR_MISSINGCOLUMN
6262

6363
# Initialize the NVD database

0 commit comments

Comments
 (0)