From 73d52905ad55ab50abea26aa4714df121759d85f Mon Sep 17 00:00:00 2001 From: Carl George Date: Sep 22 2022 18:01:06 +0000 Subject: Migrate from pyOpenSSL to cryptography pyOpenSSL upstream "strongly suggests" switching to cryptography. https://github.com/pyca/pyopenssl/commit/959a031fa329a510f49f5fdbe1eb4a0d3f4103ef Resolves #52 --- diff --git a/requirements.txt b/requirements.txt index cccb358..0c4bbb0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ pycurl -pyOpenSSL +cryptography rpkg six GitPython \ No newline at end of file diff --git a/src/centpkg/centos_cert.py b/src/centpkg/centos_cert.py index 1d6e63f..9c467a3 100644 --- a/src/centpkg/centos_cert.py +++ b/src/centpkg/centos_cert.py @@ -1,8 +1,7 @@ - from __future__ import print_function import os -from OpenSSL import crypto +from cryptography import x509 import urlgrabber import datetime @@ -23,8 +22,13 @@ def _open_cert(): if not os.access(cert_file, os.R_OK): raise centos_cert_error("""!!! cannot read your centos cert file !!! !!! Ensure the file is readable and try again !!!""") - raw_cert = open(cert_file).read() - my_cert = crypto.load_certificate(crypto.FILETYPE_PEM, raw_cert) + raw_cert = open(cert_file, 'rb').read() + try: + my_cert = x509.load_pem_x509_certificate(raw_cert) + except TypeError: + # it was required to specify a backend prior to cryptography 3.1 + from cryptography.hazmat.backends import default_backend + my_cert = x509.load_pem_x509_certificate(raw_cert, default_backend()) return my_cert def verify_cert(): @@ -35,17 +39,13 @@ def verify_cert(): Expiry time warn if less than 21 days """ my_cert = _open_cert() - serial_no = my_cert.get_serial_number() - valid_until = my_cert.get_notAfter()[:8] # CRL verification would go here #crl = urlgrabber.urlread("https:///ca/crl.pem") - dateFmt = '%Y%m%d' - delta = datetime.datetime.now() + datetime.timedelta(days=21) - warn = datetime.datetime.strftime(delta, dateFmt) + warn = datetime.datetime.now() + datetime.timedelta(days=21) - print('cert expires: %s-%s-%s' % (valid_until[:4], valid_until[4:6], valid_until[6:8])) + print(my_cert.not_valid_after.strftime('cert expires: %Y-%m-%d')) - if valid_until < warn: + if my_cert.not_valid_after < warn: print('WARNING: Your cert expires soon.') @@ -57,10 +57,8 @@ def certificate_expired(): """ my_cert = _open_cert() - if my_cert.has_expired(): - return True - else: - return False + return my_cert.not_valid_after < datetime.datetime.now() + def read_user_cert(): """ @@ -69,9 +67,5 @@ def read_user_cert(): """ my_cert = _open_cert() - subject = str(my_cert.get_subject()) - subject_line = subject.split("CN=") - cn_parts = subject_line[1].split("/") - username = cn_parts[0] - return username - + [common_name] = my_cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME) + return common_name.value