Skip to content

Commit a83d7f3

Browse files
committed
Fixed log formatting, linting issues, and unnessesary conditions. This commit checks verification status, controls how often output is sent to the returner, makes logging conditionals more succinct. Also gets rid of unused imports
1 parent 71df440 commit a83d7f3

File tree

1 file changed

+64
-57
lines changed

1 file changed

+64
-57
lines changed

hubblestack/utils/signing.py

+64-57
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,7 @@ def check_verif_timestamp(target, dampener_limit=None):
107107
new_ts = time()
108108
verif_log_timestamps[target] = new_ts
109109
return True
110-
else:
111-
return False
110+
return False
112111

113112

114113
class STATUS:
@@ -143,7 +142,7 @@ def __getattribute__(self, name):
143142
pass
144143
try:
145144
default = getattr(self.Defaults, name)
146-
return __salt__['config.get']('repo_signing:{}'.format(name), default)
145+
return __salt__['config.get']('repo_signing:%s'.format(name), default)
147146
except AttributeError:
148147
raise
149148

@@ -169,12 +168,12 @@ def split_certs(fh):
169168
try:
170169
log_level = log.debug
171170
yield ossl.load_certificate(ossl.FILETYPE_PEM, ret)
172-
except Exception as E:
171+
except Exception as exception_object:
173172
status = STATUS.UNKNOWN
174-
if check_verif_timestamp(fh) == True:
173+
if check_verif_timestamp(fh):
175174
log_level = log.error
176-
msg = '{}: | file: "{}" | cert decoding status: {} | attempting as PEM encoded private key'
177-
log_level(msg.format(short_fname, fh.name, status, digest, code, depth, message))
175+
log_level('%s: | file: "%s" | cert decoding status: %s | attempting as PEM encoded private key',
176+
short_fname, fh.name, status)
178177
yield load_pem_private_key(ret, password=None, backend=default_backend())
179178
ret = None
180179

@@ -193,11 +192,11 @@ def read_certs(*fnames):
193192
with open(fname, 'r') as fh:
194193
for i in split_certs(fh):
195194
yield i
196-
except Exception as E:
195+
except Exception as exception_object:
197196
log_level = log.debug
198-
if check_verif_timestamp(fname) == True:
197+
if check_verif_timestamp(fname):
199198
log_level = log.error
200-
log_level('error while reading "{}": {}'.format( fname, E))
199+
log_level('error while reading "%s": %s', fname, exception_object)
201200

202201

203202
def stringify_cert_files(cert):
@@ -206,8 +205,7 @@ def stringify_cert_files(cert):
206205
return ', '.join([str(c) for c in cert])
207206
elif type(cert) is file:
208207
return cert.name
209-
else:
210-
return str(cert)
208+
return str(cert)
211209

212210

213211
class X509AwareCertBucket:
@@ -232,7 +230,7 @@ def authenticate_cert(self):
232230
def __init__(self, public_crt, ca_crt):
233231
try:
234232
import hubblestack.pre_packaged_certificates as HPPC
235-
# if we have hardcoded certs then we're meant to ignore any other
233+
# iff we have hardcoded certs then we're meant to ignore any other
236234
# configured value
237235
if hasattr(HPPC, 'public_crt'):
238236
log.debug('using pre-packaged-public_crt')
@@ -243,11 +241,11 @@ def __init__(self, public_crt, ca_crt):
243241
except ImportError:
244242
pass
245243

244+
untrusted_crt = list()
245+
246246
if isinstance(ca_crt, (list, tuple)):
247247
untrusted_crt = ca_crt[1:]
248248
ca_crt = ca_crt[0]
249-
else:
250-
untrusted_crt = list()
251249

252250
if not isinstance(public_crt, (list, tuple)):
253251
public_crt = [ public_crt ]
@@ -268,12 +266,12 @@ def __init__(self, public_crt, ca_crt):
268266
self.store.add_cert(i)
269267
self.trusted.append(digest)
270268
log_level = log.debug
271-
if check_verif_timestamp(digest, dampener_limit=seconds_day) == True:
269+
if check_verif_timestamp(digest, dampener_limit=seconds_day):
272270
log_level = log.splunk
273271
status = STATUS.VERIFIED
274272
str_ca = stringify_cert_files(ca_crt)
275-
msg = 'ca cert | file: "{}" | status: {} | digest "{}" | added to verify store'
276-
log_level(msg.format(str_ca, status, digest))
273+
log_level('ca cert | file: "%s" | status: %s | digest "%s" | added to verify store',
274+
str_ca, status, digest)
277275

278276
for i in read_certs(*untrusted_crt):
279277
digest = i.digest('sha1')
@@ -285,19 +283,21 @@ def __init__(self, public_crt, ca_crt):
285283
ossl.X509StoreContext(self.store, i).verify_certificate()
286284
self.store.add_cert(i)
287285
self.trusted.append(digest)
288-
status = STATUS.VERIFIED
286+
status = STATUS.VERIFIED
289287
log_level = log.debug
290288
except ossl.X509StoreContextError as exception_object:
291289
# log at either log.error or log.critical according to the error code
292290
status = STATUS.FAIL
293291
pass
294-
if check_verif_timestamp(digest, dampener_limit=seconds_day) == True:
295-
if status == STATUS.FAIL: log_level = log.critical
296-
elif status == STATUS.UNKNOWN: log_level = log.error
297-
else: log_level = log.splunk
292+
if check_verif_timestamp(digest, dampener_limit=seconds_day):
293+
log_level = log.splunk
294+
if status == STATUS.FAIL:
295+
log_level = log.critical
296+
elif status == STATUS.UNKNOWN:
297+
log_level = log.error
298298
str_untrusted = stringify_cert_files(untrusted_crt)
299-
msg = 'intermediate certs | file: "{}" | status: {} | digest "{}"'
300-
log_level(msg.format(str_untrusted, status, digest))
299+
log_level('intermediate certs | file: "%s" | status: %s | digest "%s"',
300+
str_untrusted, status, digest)
301301

302302
self.public_crt = list()
303303
for i in read_certs(*public_crt):
@@ -312,13 +312,15 @@ def __init__(self, public_crt, ca_crt):
312312
ossl.X509StoreContext(self.store, i).verify_certificate()
313313
status = STATUS.VERIFIED
314314
self.trusted.append(digest)
315-
if check_verif_timestamp(digest, dampener_limit=seconds_day) == True:
316-
if status == STATUS.FAIL: log_level = log.critical
317-
elif status == STATUS.UNKNOWN: log_level = log.error
318-
else: log_level = log.splunk
315+
if check_verif_timestamp(digest, dampener_limit=seconds_day):
316+
log_level = log.splunk
317+
if status == STATUS.FAIL:
318+
log_level = log.critical
319+
elif status == STATUS.UNKNOWN:
320+
log_level = log.error
319321
str_public = stringify_cert_files(public_crt)
320-
msg = 'public cert | file: "{}" | status : "{}" | digest: "{}"'
321-
log_level(msg.format(str_public, status, digest))
322+
log_level('public cert | file: "%s" | status : "%s" | digest: "%s"',
323+
str_public, status, digest)
322324
except ossl.X509StoreContextError as exception_object:
323325
code, depth, message = exception_object.args[0]
324326
if code in (2,3,20,27,33):
@@ -335,12 +337,14 @@ def __init__(self, public_crt, ca_crt):
335337
# X509_V_ERR_CRL_HAS_EXPIRED 12
336338
status = STATUS.FAIL
337339
# log at either log.error or log.critical according to the error code
338-
if check_verif_timestamp(digest, dampener_limit=seconds_day) == True:
339-
if status == STATUS.FAIL: log_level = log.critical
340-
elif status == STATUS.UNKNOWN: log_level = log.error
341-
else: log_level = log.splunk
342-
msg = 'public cert | file: "{}" | status: {} | digest: "{}" | X509 error code: {} | depth: {} | message: "{}"'
343-
log_level(msg.format(str_public, status, digest, code, depth, message))
340+
if check_verif_timestamp(digest, dampener_limit=seconds_day):
341+
log_level = log.splunk
342+
if status == STATUS.FAIL:
343+
log_level = log.critical
344+
elif status == STATUS.UNKNOWN:
345+
log_level = log.error
346+
log_level('public cert | file: "%s" | status: %s | digest: "%s" | X509 error code: %s | depth: %s | message: "%s"',
347+
str_public, status, digest, code, depth, message)
344348

345349
self.public_crt.append(self.PublicCertObj(i, digest, status))
346350

@@ -440,7 +444,7 @@ def sign_target(fname, ofname, private_key='private.key', **kwargs): # pylint: d
440444
args['algorithm'] = utils.Prehashed(chosen_hash)
441445
sig = first_key.sign(**args)
442446
with open(ofname, 'w') as fh:
443-
log.debug('writing signature of {} to {}'.format(os.path.abspath(fname), os.path.abspath(ofname)))
447+
log.debug('writing signature of %s to %s', os.path.abspath(fname), os.path.abspath(ofname))
444448
fh.write(PEM.encode(sig, 'Detached Signature of {}'.format(fname)))
445449
fh.write('\n')
446450

@@ -461,10 +465,9 @@ def verify_signature(fname, sfname, public_crt='public.crt', ca_crt='ca-root.crt
461465
except IOError:
462466
status = STATUS.UNKNOWN
463467
verif_key = ':'.join([fname, sfname])
464-
if check_verif_timestamp(verif_key) == True:
468+
if check_verif_timestamp(verif_key):
465469
log_level = log.error
466-
msg = '{} | file "{}" | status: {} '
467-
log_level(msg.format(short_fname, fname, status))
470+
log_level('%s | file "%s" | status: %s ', short_fname, fname, status)
468471
return STATUS.UNKNOWN
469472
x509 = X509AwareCertBucket(public_crt, ca_crt)
470473
hasher, chosen_hash = hash_target(fname, obj_mode=True)
@@ -474,21 +477,22 @@ def verify_signature(fname, sfname, public_crt='public.crt', ca_crt='ca-root.crt
474477
for crt,txt,status in x509.public_crt:
475478
log_level = log.debug
476479
sha256sum = hash_target(fname)
477-
msg = '{} | file "{}" | status: {} | sha256sum: "{}" | public cert fingerprint and requester: "{}"'
478480
pubkey = crt.get_pubkey().to_cryptography_key()
479481
if isinstance(pubkey, rsa.RSAPublicKey):
480482
args['padding'] = padding.PSS( mgf=padding.MGF1(hashes.SHA256()),
481483
salt_length=padding.PSS.MAX_LENGTH)
482484
args['algorithm'] = utils.Prehashed(chosen_hash)
483485
try:
484486
pubkey.verify(**args)
485-
log_level(msg.format(short_fname, fname, status, sha256sum, txt ))
487+
log_level('%s | file "%s" | status: %s | sha256sum: "%s" | public cert fingerprint and requester: "%s"',
488+
short_fname, fname, status, sha256sum, txt )
486489
return status
487490
except InvalidSignature:
488491
status = STATUS.FAIL
489-
if check_verif_timestamp(fname) == True:
492+
if check_verif_timestamp(fname):
490493
log_level = log.critical
491-
log_level(msg.format(short_fname, fname, status, sha256sum, txt))
494+
log_level('%s | file "%s" | status: %s | sha256sum: "%s" | public cert fingerprint and requester: "%s"',
495+
short_fname, fname, status, sha256sum, txt )
492496
pass
493497
return STATUS.FAIL
494498

@@ -521,8 +525,9 @@ def verify_files(targets, mfname='MANIFEST', sfname='SIGNATURE', public_crt='pub
521525
522526
return a mapping from the input target list to the status values (a dict of filename: status)
523527
"""
524-
msg = "verifying: files: {} | mfname: {} | sfname: {} | public_crt: {}| ca_crt: {}"
525-
log.debug(msg.format(targets, mfname, sfname, public_crt, ca_crt))
528+
529+
log.debug("verifying: files: %s | mfname: %s | sfname: %s | public_crt: %s| ca_crt: %s",
530+
targets, mfname, sfname, public_crt, ca_crt)
526531
ret = OrderedDict()
527532
ret[mfname] = verify_signature(mfname, sfname=sfname, public_crt=public_crt, ca_crt=ca_crt)
528533
# ret[mfname] is the strongest claim we can make about the files we're
@@ -547,7 +552,7 @@ def verify_files(targets, mfname='MANIFEST', sfname='SIGNATURE', public_crt='pub
547552
for otarget in targets:
548553
target = normalize_path(otarget, trunc=trunc)
549554

550-
log.debug('found manifest for {} ({})'.format(otarget, target))
555+
log.debug('found manifest for %s (%s)', otarget, target)
551556
if otarget != target:
552557
xlate[target] = otarget
553558
if target in digests or target in (mfname, sfname):
@@ -590,12 +595,14 @@ def verify_files(targets, mfname='MANIFEST', sfname='SIGNATURE', public_crt='pub
590595
# We do have a MANIFEST entry and it doesn't match: FAIL with or
591596
# without a matching SIGNATURE
592597
status = STATUS.FAIL
593-
if check_verif_timestamp(digest) == True:
594-
if status == STATUS.FAIL: log_level = log.critical
595-
elif status == STATUS.UNKNOWN: log_level = log.error
598+
if check_verif_timestamp(digest):
599+
if status == STATUS.FAIL:
600+
log_level = log.critical
601+
elif status == STATUS.UNKNOWN:
602+
log_level = log.error
596603
# logs according to the STATUS of target file
597-
msg = 'file: "{}" | status: {} | manifest sha256: "{}" | real sha256: "{}"'
598-
log_level(msg.format(vfname, status, digest, new_hash))
604+
log_level('file: "%s" | status: %s | manifest sha256: "%s" | real sha256: "%s"',
605+
vfname, status, digest, new_hash)
599606
ret[vfname] = status
600607

601608
# fix any normalized names so the caller gets back their specified targets
@@ -625,13 +632,13 @@ def inner(path, saltenv, *a, **kwargs):
625632
real_path = _p(f_path)
626633
mani_path = _p(f_mani)
627634
sign_path = _p(f_sign)
628-
log.debug('path: {} | manifest: "{}" | signature: "{}"'.format(
629-
path, mani_path, sign_path))
635+
log.debug('path: %s | manifest: "%s" | signature: "%s"',
636+
path, mani_path, sign_path)
630637
if not real_path:
631638
return f_path
632639
verify_res = verify_files([real_path],
633-
mfname=mani_path, sfname=sign_path,
634-
public_crt=Options.public_crt, ca_crt=Options.ca_crt)
640+
mfname=mani_path, sfname=sign_path,
641+
public_crt=Options.public_crt, ca_crt=Options.ca_crt)
635642
log.debug('verify: %s', dict(**verify_res))
636643
vrg = verify_res.get(real_path, STATUS.UNKNOWN)
637644
if vrg == STATUS.VERIFIED:

0 commit comments

Comments
 (0)