From f77e9719c4192bd4a380843df06a0f57ab7296ad Mon Sep 17 00:00:00 2001 From: "Endi S. Dewata" Date: Mon, 4 Nov 2024 10:25:06 -0600 Subject: [PATCH] Add fallback for Certificate.not_valid_before/after_utc The Certificate.not_valid_before/after_utc is only available in Python Cryptography 42 or later. If the system does not have this version, it will use Certificate.not_valid_before/after and convert it to UTC. --- base/common/python/pki/nssdb.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/base/common/python/pki/nssdb.py b/base/common/python/pki/nssdb.py index 60cf18d978f..c3ecfeaa6fd 100644 --- a/base/common/python/pki/nssdb.py +++ b/base/common/python/pki/nssdb.py @@ -31,6 +31,7 @@ import stat import subprocess import tempfile +import datetime import grp import pwd @@ -2099,8 +2100,22 @@ def get_cert_info(self, nickname, token=None): cert['issuer'] = pki.convert_x509_name_to_dn(cert_obj.issuer) cert['subject'] = pki.convert_x509_name_to_dn(cert_obj.subject) - cert['not_before'] = self.convert_time_to_millis(cert_obj.not_valid_before_utc) - cert['not_after'] = self.convert_time_to_millis(cert_obj.not_valid_after_utc) + if hasattr(a, 'not_valid_before_utc'): + # only available in Python Cryptography 42 or later + not_before = cert_obj.not_valid_before_utc + else: + # convert to UTC + not_valid_before = cert_obj.not_valid_before.replace(tzinfo=datetime.timezone.utc) + cert['not_before'] = self.convert_time_to_millis(not_before) + + if hasattr(a, 'not_valid_after_utc'): + # only available in Python Cryptography 42 or later + not_after = cert_obj.not_valid_after_utc + else: + # convert to UTC + not_after = cert_obj.not_valid_after.replace(tzinfo=datetime.timezone.utc) + cert['not_after'] = self.convert_time_to_millis(not_after) + cert['trust_flags'] = self.get_trust(nickname=nickname, token=token) logger.debug('NSSDatabase.get_cert_info(%s) ends', nickname) @@ -2109,6 +2124,13 @@ def get_cert_info(self, nickname, token=None): @staticmethod def convert_time_to_millis(date): + ''' + Do not use the following code: + epoch = datetime.datetime.utcfromtimestamp(0) + return (date - epoch).total_seconds() * 1000 + since it will fail with the following error message: + TypeError: can't subtract offset-naive and offset-aware datetimes + ''' return date.timestamp() * 1000 def export_cert_from_db(self,