def test_basic(self): # test the default view response = self.client.get( reverse('default', kwargs={'serial': self.ca.serial})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pkix-crl') crl = x509.load_der_x509_crl(response.content, default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, hashes.SHA512) self.assertEqual(list(crl), []) # revoke a certificate cert = Certificate.objects.get(serial=self.cert.serial) cert.revoke() # fetch again - we should see a cached response response = self.client.get( reverse('default', kwargs={'serial': self.ca.serial})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pkix-crl') crl = x509.load_der_x509_crl(response.content, default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, hashes.SHA512) self.assertEqual(list(crl), []) # clear the cache and fetch again cache.clear() response = self.client.get( reverse('default', kwargs={'serial': self.ca.serial})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pkix-crl') crl = x509.load_der_x509_crl(response.content, default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, hashes.SHA512) self.assertEqual(len(list(crl)), 1) self.assertEqual(crl[0].serial_number, cert.x509.serial)
def test_cache_all_crls(self): hash_cls = hashes.SHA512 enc_cls = Encoding.DER tasks.cache_crls() for ca, data in self.cas.items(): key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'ca') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, hash_cls) key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'user') crl = x509.load_der_x509_crl(cache.get(key), default_backend())
def test_cache_all_crls(self) -> None: """Test caching when all CAs are valid.""" hash_cls = hashes.SHA512 enc_cls = Encoding.DER tasks.cache_crls() for data in self.cas.values(): key = get_crl_cache_key(data.serial, hash_cls(), enc_cls, "ca") crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, hash_cls) key = get_crl_cache_key(data.serial, hash_cls(), enc_cls, "user") crl = x509.load_der_x509_crl(cache.get(key), default_backend())
def test_basic(self): """Test caching with a specific serial.""" hash_cls = hashes.SHA512 enc_cls = Encoding.DER for data in self.cas.values(): tasks.cache_crl(data.serial) key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'ca') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, hash_cls) key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'user') crl = x509.load_der_x509_crl(cache.get(key), default_backend())
def __init__(self, module): super(CRLInfo, self).__init__(module.params['path'] or '', 'present', False, module.check_mode) self.content = module.params['content'] self.module = module self.crl = None if self.content is None: try: with open(self.path, 'rb') as f: data = f.read() except Exception as e: self.module.fail_json( msg='Error while reading CRL file from disk: {0}'.format( e)) else: data = self.content.encode('utf-8') if not identify_pem_format(data): data = base64.b64decode(self.content) self.crl_pem = identify_pem_format(data) try: if self.crl_pem: self.crl = x509.load_pem_x509_crl(data, default_backend()) else: self.crl = x509.load_der_x509_crl(data, default_backend()) except Exception as e: self.module.fail_json( msg='Error while decoding CRL: {0}'.format(e))
def get_revok_date_and_ser_number(): with open(crl_path, 'rb') as crl_file: data = crl_file.read() crl = x509.load_der_x509_crl(data, default_backend()) for r in crl: print(f'{r.revocation_date} {r.serial_number}')
def _download_http_crl(endpoint, key_identifier): """ :param endpoint: url della crl :param key_identifier: chiave identificativa dell'issuer del certificato :return: """ crl_dest = make_crl_store_path(endpoint, key_identifier) + ".crl" crl_meta_dest = make_crl_store_path(endpoint, key_identifier) + ".txt" try: r = requests.get(endpoint) if r.status_code == 200: try: crl = crypto.load_crl(crypto.FILETYPE_PEM, r.content) except: crl_x509 = x509.load_der_x509_crl(r.content, default_backend()) crl = crypto.CRL.from_cryptography(crl_x509) with open(crl_dest, 'w') as f: f.write(crypto.dump_crl(crypto.FILETYPE_PEM, crl).decode()) with open(crl_meta_dest, 'w') as f: f.write(endpoint) else: LOG.error('Errore durante il download della CRL con endpoint = {}'. format(endpoint), extra=set_client_ip()) except Exception as e: LOG.error( 'Eccezione durante il download della CRL con key_identifier = {}'. format(key_identifier), extra=set_client_ip()) LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
def assertCRL(self, crl, certs=None, signer=None, expires=86400, algorithm=None, encoding=Encoding.PEM, idp=None, extensions=None, crl_number=0, skip_authority_key_identifier=False): certs = certs or [] signer = signer or self.cas['child'] algorithm = algorithm or ca_settings.CA_DIGEST_ALGORITHM extensions = extensions or [] expires = datetime.utcnow() + timedelta(seconds=expires) if idp is not None: # pragma: no branch, pragma: only cryptography>=2.5 extensions.append(idp) extensions.append(x509.Extension( value=x509.CRLNumber(crl_number=crl_number), critical=False, oid=ExtensionOID.CRL_NUMBER )) if not skip_authority_key_identifier: extensions.append(signer.authority_key_identifier.as_extension()) if encoding == Encoding.PEM: crl = x509.load_pem_x509_crl(crl, default_backend()) else: crl = x509.load_der_x509_crl(crl, default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, type(algorithm)) self.assertTrue(crl.is_signature_valid(signer.x509.public_key())) self.assertEqual(crl.issuer, signer.x509.subject) self.assertEqual(crl.last_update, datetime.utcnow()) self.assertEqual(crl.next_update, expires) self.assertCountEqual(list(crl.extensions), extensions) entries = {e.serial_number: e for e in crl} expected = {c.x509.serial_number: c for c in certs} self.assertCountEqual(entries, expected) for serial, entry in entries.items(): self.assertEqual(entry.revocation_date, datetime.utcnow()) self.assertEqual(list(entry.extensions), [])
def crl_verify(cert_path): """ Attempts to verify a certificate using CRL. :param cert_path: :return: True if certificate is valid, False otherwise :raise Exception: If certificate does not have CRL """ with open(cert_path, 'rt') as c: cert = parse_certificate(c.read()) distribution_points = cert.extensions.get_extension_for_oid( x509.OID_CRL_DISTRIBUTION_POINTS).value for p in distribution_points: point = p.full_name[0].value try: response = requests.get(point) if response.status_code != 200: raise Exception("Unable to retrieve CRL: {0}".format(point)) except ConnectionError: raise Exception("Unable to retrieve CRL: {0}".format(point)) crl = x509.load_der_x509_crl(response.content, backend=default_backend()) for r in crl: if cert.serial == r.serial_number: return return True
def test_basic(self): hash_cls = hashes.SHA512 enc_cls = Encoding.DER stdout, stderr = self.cmd('cache_crls') self.assertEqual(stdout, '') self.assertEqual(stderr, '') for name, ca in self.cas.items(): key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'ca') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl) self.assertIsInstance(crl.signature_hash_algorithm, hash_cls) key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'user') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl)
def crl_verify(cert_path): """ Attempts to verify a certificate using CRL. :param cert_path: :return: True if certificate is valid, False otherwise :raise Exception: If certificate does not have CRL """ with open(cert_path, 'rt') as c: cert = parse_certificate(c.read()) distribution_points = cert.extensions.get_extension_for_oid(x509.OID_CRL_DISTRIBUTION_POINTS).value for p in distribution_points: point = p.full_name[0].value try: response = requests.get(point) if response.status_code != 200: raise Exception("Unable to retrieve CRL: {0}".format(point)) except ConnectionError: raise Exception("Unable to retrieve CRL: {0}".format(point)) crl = x509.load_der_x509_crl(response.content, backend=default_backend()) for r in crl: if cert.serial == r.serial_number: return return True
def get_certificate_crls( certificate: x509.Certificate) -> List[x509.CertificateRevocationList]: """ Extract CRLs from given certificate. CRLs are not mandatory, so it's not a problem if for whatever reason they cannot be fetched or read at this exact moment. Args: certificate: SSL certificate of which CRLs will be retrieved from Returns: list of Certificate Revocation Lists """ try: distribution_points = certificate.extensions.get_extension_for_oid( oid=x509.ExtensionOID.CRL_DISTRIBUTION_POINTS, ) except x509.ExtensionNotFound: return [] crl_urls = [] for distribution_point in distribution_points.value: for crl in distribution_point.full_name: crl_urls.append(crl.value) crls = [] for url in crl_urls: try: data = requests.get(url=url).content crl = x509.load_der_x509_crl(data=data) except (RequestException, ValueError) as e: logger.warning(f'Could not get the CRL from {url}: {e}') else: crls.append(crl) return crls
def crl_verify(cert, cert_path): """ Attempts to verify a certificate using CRL. :param cert: :param cert_path: :return: True if certificate is valid, False otherwise :raise Exception: If certificate does not have CRL """ try: distribution_points = cert.extensions.get_extension_for_oid( x509.OID_CRL_DISTRIBUTION_POINTS).value except x509.ExtensionNotFound: current_app.logger.debug("No CRLDP extension in certificate {}".format( cert.serial_number)) return None for p in distribution_points: point = p.full_name[0].value if point not in crl_cache: current_app.logger.debug("Retrieving CRL: {}".format(point)) try: response = requests.get(point) if response.status_code != 200: raise Exception( "Unable to retrieve CRL: {0}".format(point)) except InvalidSchema: # Unhandled URI scheme (like ldap://); skip this distribution point. continue except ConnectionError: raise Exception("Unable to retrieve CRL: {0}".format(point)) crl_cache[point] = x509.load_der_x509_crl( response.content, backend=default_backend()) else: current_app.logger.debug("CRL point is cached {}".format(point)) for r in crl_cache[point]: if cert.serial_number == r.serial_number: try: reason = r.extensions.get_extension_for_class( x509.CRLReason).value # Handle "removeFromCRL" revoke reason as unrevoked; # continue with the next distribution point. # Per RFC 5280 section 6.3.3 (k): # https://tools.ietf.org/html/rfc5280#section-6.3.3 if reason == x509.ReasonFlags.remove_from_crl: break except x509.ExtensionNotFound: pass current_app.logger.debug("CRL reports certificate " "revoked: {}".format( cert.serial_number)) return False return True
def crl_verification(self): for value in self.crl.value: for full_name in value.full_name: request = requests.get(full_name.value) crl = x509.load_der_x509_crl(request.content,default_backend()) if not crl: return True else: return False
def load_crl_der(fn: str) -> CertificateRevocationList: crl_return = None if (fn and Path(fn).exists()): with open(fn, "rb") as file: data = file.read() if data and len(data) > 0: crl_return = load_der_x509_crl(data, default_backend()) return crl_return
def test_serial(self) -> None: """Test passing an explicit serial.""" stdout, stderr = self.cmd("cache_crls", self.ca.serial) self.assertEqual(stdout, "") self.assertEqual(stderr, "") key = get_crl_cache_key(self.ca.serial, hashes.SHA512(), Encoding.DER, "ca") crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl) self.assertIsInstance(crl.signature_hash_algorithm, hashes.SHA512) key = get_crl_cache_key(self.ca.serial, hashes.SHA512(), Encoding.DER, "user") crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl)
def is_certificate_revoked(serial_number, crl_url): r = requests.get(crl_url) try: crl = x509.load_der_x509_crl(r.content, default_backend()) except ValueError as e: crl = x509.load_pem_x509_crl(r.content, default_backend()) return crl.get_revoked_certificate_by_serial_number( serial_number) is not None
def updateCRL(self, crl, url): filename = self.cache[url]["filename"] crl_object = x509.load_der_x509_crl(crl, default_backend()) timestamp = crl_object.next_update.timestamp() self.cache[url] = {"timestamp": timestamp, "filename": filename} self.saveCRL(crl, filename) self.saveCRLDescription() return True
def load_crl(self): crl_path = "../../../crl/" files = [f for f in os.scandir(crl_path)] crl = [] for f in files: with open(f, "rb") as file: crlist = x509.load_der_x509_crl(file.read(), default_backend()) crl.append(crlist) return crl
def test_serial(self): """Test passing an explicit serial.""" ca = self.cas['root'] hash_cls = hashes.SHA512 enc_cls = Encoding.DER stdout, stderr = self.cmd('cache_crls', ca.serial) self.assertEqual(stdout, '') self.assertEqual(stderr, '') key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'ca') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl) self.assertIsInstance(crl.signature_hash_algorithm, hash_cls) key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'user') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl)
def _load_crl(self, crl_data, data_type): if data_type == "PEM": return x509.load_pem_x509_crl(crl_data, default_backend()) elif data_type == "DER": return x509.load_der_x509_crl(crl_data, default_backend()) else: raise InvalidCRLDataTypeException( 'crl data type %s not recognized' % data_type) return None
def load_cert_revocation_list(filename,file_type): with open(filename, "rb") as pem_file: pem_data = pem_file.read() if file_type=="der": cert = x509.load_der_x509_crl(pem_data, default_backend()) elif file_type=="pem": cert = x509.load_pem_x509_crl(pem_data, default_backend()) return cert
def crl_verify(cert, cert_path): """ Attempts to verify a certificate using CRL. :param cert: :param cert_path: :return: True if certificate is valid, False otherwise :raise Exception: If certificate does not have CRL """ try: distribution_points = cert.extensions.get_extension_for_oid( x509.OID_CRL_DISTRIBUTION_POINTS ).value except x509.ExtensionNotFound: current_app.logger.debug("No CRLDP extension in certificate {}".format(cert.serial_number)) return None for p in distribution_points: point = p.full_name[0].value if point not in crl_cache: current_app.logger.debug("Retrieving CRL: {}".format(point)) try: response = requests.get(point) if response.status_code != 200: raise Exception("Unable to retrieve CRL: {0}".format(point)) except InvalidSchema: # Unhandled URI scheme (like ldap://); skip this distribution point. continue except ConnectionError: raise Exception("Unable to retrieve CRL: {0}".format(point)) crl_cache[point] = x509.load_der_x509_crl(response.content, backend=default_backend()) else: current_app.logger.debug("CRL point is cached {}".format(point)) for r in crl_cache[point]: if cert.serial_number == r.serial_number: try: reason = r.extensions.get_extension_for_class(x509.CRLReason).value # Handle "removeFromCRL" revoke reason as unrevoked; # continue with the next distribution point. # Per RFC 5280 section 6.3.3 (k): # https://tools.ietf.org/html/rfc5280#section-6.3.3 if reason == x509.ReasonFlags.remove_from_crl: break except x509.ExtensionNotFound: pass current_app.logger.debug("CRL reports certificate " "revoked: {}".format(cert.serial_number)) return False return True
def assertCRL( self, crl, expected=None, signer=None, expires=86400, # pylint: disable=invalid-name algorithm=None, encoding=Encoding.PEM, idp=None, extensions=None, crl_number=0): """Test the given CRL. Parameters ---------- crl : bytes The raw CRL expected : list List of CAs/certs to be expected in this CRL """ expected = expected or [] signer = signer or self.cas['child'] algorithm = algorithm or ca_settings.CA_DIGEST_ALGORITHM extensions = extensions or [] expires = datetime.utcnow() + timedelta(seconds=expires) if idp is not None: # pragma: no branch extensions.append(idp) extensions.append( x509.Extension(value=x509.CRLNumber(crl_number=crl_number), critical=False, oid=ExtensionOID.CRL_NUMBER)) extensions.append( x509.Extension(value=signer.get_authority_key_identifier(), oid=ExtensionOID.AUTHORITY_KEY_IDENTIFIER, critical=False)) if encoding == Encoding.PEM: crl = x509.load_pem_x509_crl(crl, default_backend()) else: crl = x509.load_der_x509_crl(crl, default_backend()) self.assertIsInstance(crl.signature_hash_algorithm, type(algorithm)) self.assertTrue(crl.is_signature_valid(signer.x509.public_key())) self.assertEqual(crl.issuer, signer.x509.subject) self.assertEqual(crl.last_update, datetime.utcnow()) self.assertEqual(crl.next_update, expires) self.assertCountEqual(list(crl.extensions), extensions) entries = {e.serial_number: e for e in crl} expected = {c.x509.serial_number: c for c in expected} self.assertCountEqual(entries, expected) for entry in entries.values(): self.assertEqual(entry.revocation_date, datetime.utcnow()) self.assertEqual(list(entry.extensions), [])
def update_revoked_keys(): from pki.models import RevokedCertificate crl = urllib.request.urlopen('http://crl.pki.gov.kz/rsa.crl') cert_crl = x509.load_der_x509_crl(crl.read(), default_backend()) now = datetime.now() for r in cert_crl: if (now - r.revocation_date).days == 0: RevokedCertificate.objects.get_or_create( revocation_date=make_aware(r.revocation_date), serial_number=r.serial_number)
def load_crl(self, crl_bytes): try: crl = x509.load_pem_x509_crl(crl_bytes, backend=default_backend()) return crl except: try: crl = x509.load_der_x509_crl(crl_bytes, backend=default_backend()) return crl except: return None
def test_basic(self) -> None: """Test the basic command. Note: Without an explicit serial expired CAs are excluded, that's why we need @freeze_time(). """ stdout, stderr = self.cmd("cache_crls") self.assertEqual(stdout, "") self.assertEqual(stderr, "") for ca in self.new_cas.values(): key = get_crl_cache_key(ca.serial, hashes.SHA512(), Encoding.DER, "ca") crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl) self.assertIsInstance(crl.signature_hash_algorithm, hashes.SHA512) key = get_crl_cache_key(ca.serial, hashes.SHA512(), Encoding.DER, "user") crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl)
def test_basic(self): """Test the basic command. Note: Without an explicit serial expired CAs are excluded, that's why we need @freeze_time(). """ hash_cls = hashes.SHA512 enc_cls = Encoding.DER stdout, stderr = self.cmd('cache_crls') self.assertEqual(stdout, '') self.assertEqual(stderr, '') for ca in self.cas.values(): key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'ca') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl) self.assertIsInstance(crl.signature_hash_algorithm, hash_cls) key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'user') crl = x509.load_der_x509_crl(cache.get(key), default_backend()) self.assertIsNotNone(crl)
def revokated(lst): rl = [] for i in range(4): i += 1 f = open("crl/cc_ec_cidadao_crl00" + str(i) + "_crl.crl", "rb") data = f.read() crl = x509.load_der_x509_crl(data, default_backend()) for x in crl: rl.append(x.serial_number) for x in lst: if x.serial_number in rl: return True return False
def load_crl(self, path): """Loads CRLs from disk""" try: with os.scandir(path) as it: for entry in it: if entry.name.endswith('crl') and entry.is_file(): with open(path + entry.name, 'rb') as f: crl_data = f.read() crl = x509.load_der_x509_crl(crl_data) self.crls_list.append(crl) logger.info("Certicates loaded!") except: logger.error( "Could not read Path!Make sure to run this file on the /client directory" )
def crl_verify(cert_path): """ Attempts to verify a certificate using CRL. :param cert_path: :return: True if certificate is valid, False otherwise :raise Exception: If certificate does not have CRL """ with open(cert_path, 'rt') as c: cert = parse_certificate(c.read()) distribution_points = cert.extensions.get_extension_for_oid( x509.OID_CRL_DISTRIBUTION_POINTS).value for p in distribution_points: point = p.full_name[0].value try: response = requests.get(point) if response.status_code != 200: raise Exception("Unable to retrieve CRL: {0}".format(point)) except InvalidSchema: # Unhandled URI scheme (like ldap://); skip this distribution point. continue except ConnectionError: raise Exception("Unable to retrieve CRL: {0}".format(point)) crl = x509.load_der_x509_crl(response.content, backend=default_backend()) for r in crl: if cert.serial == r.serial_number: try: reason = r.extensions.get_extension_for_class( x509.CRLReason).value # Handle "removeFromCRL" revoke reason as unrevoked; continue with the next distribution point. # Per RFC 5280 section 6.3.3 (k): https://tools.ietf.org/html/rfc5280#section-6.3.3 if reason == x509.ReasonFlags.remove_from_crl: break except x509.ExtensionNotFound: pass return return True
def addCRLToDescription(self, crl, url): crl_object = x509.load_der_x509_crl(crl, default_backend()) # Index of filename if len(self.cache) == 0: self.cache["global"] = {"index": 1} # Create filename and update the index filename = str(self.cache["global"]["index"]) + ".crl" self.cache["global"]["index"] += 1 timestamp = crl_object.next_update.timestamp() self.cache[url] = {"filename": filename, "timestamp": timestamp} self.saveCRL(crl, filename) self.saveCRLDescription() return True
def status(self, ca): # When the local node is not a CA, return "disabled" if not self.check_local_ca_instance(): print("CRL generation: disabled") return # Local node is a CA, check its configuration if ca.is_crlgen_enabled(): print("CRL generation: enabled") try: crl_filename = os.path.join(paths.PKI_CA_PUBLISH_DIR, 'MasterCRL.bin') with open(crl_filename, 'rb') as f: crl = x509.load_der_x509_crl(f.read(), default_backend()) print("Last CRL update: {}".format(crl.last_update)) for ext in crl.extensions: if ext.oid == x509.oid.ExtensionOID.CRL_NUMBER: print("Last CRL Number: {}".format( ext.value.crl_number)) except IOError: logger.error("Unable to find last CRL") else: print("CRL generation: disabled")
#!/usr/bin/env python3 """ Procesado de una lista CRL """ from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes crl_pem = open("crl_der.crt", "rb").read() crl = x509.load_der_x509_crl(crl_pem, default_backend()) print("Numero de Certificados revocados: %d" % len(crl)) print("Serial\t\t\t\t\tFecha Revocación") for cert in crl: print("%s\t%s" % (cert.serial_number, str(cert.revocation_date)))