Skip to content

Commit

Permalink
Add fallback for Certificate.not_valid_before/after_utc
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
edewata committed Nov 4, 2024
1 parent 8ba5157 commit f77e971
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions base/common/python/pki/nssdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import stat
import subprocess
import tempfile
import datetime
import grp
import pwd

Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down

0 comments on commit f77e971

Please sign in to comment.