Ejemplo n.º 1
0
 def test_add_invalid_extension(self):
     builder = ocsp.OCSPRequestBuilder()
     with pytest.raises(TypeError):
         builder.add_extension(
             "notanext",  # type:ignore[arg-type]
             False,
         )
Ejemplo n.º 2
0
def _construct_mock_ocsp_response(certificate_status, response_status):
    cert = x509.load_pem_x509_certificate(
        test_util.load_vector('ocsp_certificate.pem'), default_backend())
    issuer = x509.load_pem_x509_certificate(
        test_util.load_vector('ocsp_issuer_certificate.pem'),
        default_backend())
    responder = x509.load_pem_x509_certificate(
        test_util.load_vector('ocsp_responder_certificate.pem'),
        default_backend())
    builder = ocsp_lib.OCSPRequestBuilder()
    builder = builder.add_certificate(cert, issuer, hashes.SHA1())
    request = builder.build()

    return mock.Mock(
        response_status=response_status,
        certificate_status=certificate_status,
        serial_number=request.serial_number,
        issuer_key_hash=request.issuer_key_hash,
        issuer_name_hash=request.issuer_name_hash,
        responder_name=responder.subject,
        certificates=[responder],
        hash_algorithm=hashes.SHA1(),
        next_update=datetime.now() + timedelta(days=1),
        this_update=datetime.now() - timedelta(days=1),
        signature_algorithm_oid=x509.oid.SignatureAlgorithmOID.RSA_WITH_SHA1,
    )
Ejemplo n.º 3
0
def validate_revocation_certificate_chain(chain, error_messages):
    # a failed try to use ocsp validation
    for i in range(1, len(chain)):
        subject = chain[i - 1]
        issuer = chain[i]
        builder = ocsp.OCSPRequestBuilder()

        builder = builder.add_certificate(subject, issuer, SHA1())
        req = builder.build()
        data = req.public_bytes(serialization.Encoding.DER)

        for e in subject.extensions:

            if isinstance(e.value, AuthorityInformationAccess):
                url = e.value._descriptions[0].access_location.value
                print(url)
                headers = {"Content-Type": "application/ocsp-request"}
                r = requests.post(url, data=data, headers=headers)
                ocsp_resp = ocsp.load_der_ocsp_response(r.content)
                print(ocsp_resp.certificate_status)

                if ocsp_resp.response_status == ocsp.OCSPResponseStatus.SUCCESSFUL:
                    if ocsp_resp.certificate_status == ocsp.OCSPCertStatus.UNKNOWN:
                        status = validate_revocation_certificate_chain_crl(
                            [subject, issuer], error_messages)
                        if not status:
                            return False
                    elif ocsp_resp.certificate_status == ocsp.OCSPCertStatus.REVOKED:
                        error_messages.append(
                            "One of the certificates is revoked")
                        return False
                else:
                    return False
    return True
Ejemplo n.º 4
0
def get_oscp_request(cert, issuer_cert):
    builder = ocsp.OCSPRequestBuilder()
    builder = builder.add_certificate(cert, issuer_cert, SHA1())
    nonce = round(time.time() * 1000)
    builder = builder.add_extension(
        OCSPNonce(bytes(str(nonce), encoding='ascii')), True)
    req = builder.build()
    return req
Ejemplo n.º 5
0
    def test_create_ocsp_request_invalid_cert(self):
        cert, issuer = _cert_and_issuer()
        builder = ocsp.OCSPRequestBuilder()
        with pytest.raises(TypeError):
            builder.add_certificate(b"notacert", issuer, hashes.SHA1())

        with pytest.raises(TypeError):
            builder.add_certificate(cert, b"notacert", hashes.SHA1())
Ejemplo n.º 6
0
    def test_no_nonce(self) -> None:
        """Test fetching without a nonce."""
        builder = ocsp.OCSPRequestBuilder()
        builder = builder.add_certificate(self.cert.pub.loaded, self.cert.ca.pub.loaded, hashes.SHA1())
        data = base64.b64encode(builder.build().public_bytes(serialization.Encoding.DER))

        response = self.client.get(reverse("get", kwargs={"data": data.decode("utf-8")}))
        self.assertOCSP(response, requested=[self.cert], nonce=None)
Ejemplo n.º 7
0
 def test_create_ocsp_request(self):
     cert, issuer = _cert_and_issuer()
     builder = ocsp.OCSPRequestBuilder()
     builder = builder.add_certificate(cert, issuer, hashes.SHA1())
     req = builder.build()
     serialized = req.public_bytes(serialization.Encoding.DER)
     assert serialized == base64.b64decode(
         b"MEMwQTA/MD0wOzAJBgUrDgMCGgUABBRAC0Z68eay0wmDug1gfn5ZN0gkxAQUw5zz"
         b"/NNGCDS7zkZ/oHxb8+IIy1kCAj8g")
Ejemplo n.º 8
0
def _check_ocsp_cryptography(cert_path: str, chain_path: str, url: str,
                             timeout: int) -> bool:
    # Retrieve OCSP response
    with open(chain_path, 'rb') as file_handler:
        issuer = x509.load_pem_x509_certificate(file_handler.read(),
                                                default_backend())
    with open(cert_path, 'rb') as file_handler:
        cert = x509.load_pem_x509_certificate(file_handler.read(),
                                              default_backend())
    builder = ocsp.OCSPRequestBuilder()
    builder = builder.add_certificate(cert, issuer, hashes.SHA1())
    request = builder.build()
    request_binary = request.public_bytes(serialization.Encoding.DER)
    try:
        response = requests.post(
            url,
            data=request_binary,
            headers={'Content-Type': 'application/ocsp-request'},
            timeout=timeout)
    except requests.exceptions.RequestException:
        logger.info("OCSP check failed for %s (are we offline?)",
                    cert_path,
                    exc_info=True)
        return False
    if response.status_code != 200:
        logger.info("OCSP check failed for %s (HTTP status: %d)", cert_path,
                    response.status_code)
        return False

    response_ocsp = ocsp.load_der_ocsp_response(response.content)

    # Check OCSP response validity
    if response_ocsp.response_status != ocsp.OCSPResponseStatus.SUCCESSFUL:
        logger.warning("Invalid OCSP response status for %s: %s", cert_path,
                       response_ocsp.response_status)
        return False

    # Check OCSP signature
    try:
        _check_ocsp_response(response_ocsp, request, issuer, cert_path)
    except UnsupportedAlgorithm as e:
        logger.warning(str(e))
    except errors.Error as e:
        logger.warning(str(e))
    except InvalidSignature:
        logger.warning('Invalid signature on OCSP response for %s', cert_path)
    except AssertionError as error:
        logger.warning('Invalid OCSP response for %s: %s.', cert_path,
                       str(error))
    else:
        # Check OCSP certificate status
        logger.debug("OCSP certificate status for %s is: %s", cert_path,
                     response_ocsp.certificate_status)
        return response_ocsp.certificate_status == ocsp.OCSPCertStatus.REVOKED

    return False
Ejemplo n.º 9
0
 def test_create_ocsp_request_with_extension(self, ext, critical):
     cert, issuer = _cert_and_issuer()
     builder = ocsp.OCSPRequestBuilder()
     builder = builder.add_certificate(cert, issuer,
                                       hashes.SHA1()).add_extension(
                                           ext, critical)
     req = builder.build()
     assert len(req.extensions) == 1
     assert req.extensions[0].value == ext
     assert req.extensions[0].oid == ext.oid
     assert req.extensions[0].critical is critical
Ejemplo n.º 10
0
    def test_no_nonce(self):
        """Test fetching without a nonce."""
        cert = self.certs['child-cert']
        builder = ocsp.OCSPRequestBuilder()
        builder = builder.add_certificate(cert.x509, cert.ca.x509,
                                          hashes.SHA1())
        data = base64.b64encode(builder.build().public_bytes(
            serialization.Encoding.DER))

        response = self.client.get(
            reverse('get', kwargs={'data': data.decode('utf-8')}))
        self.assertOCSP(response, requested=[cert], nonce=None)
Ejemplo n.º 11
0
    def build_certificate_url(self, server, cert, issuer_cert):
        """Return the complete url to the ocsp"""
        orb = ocsp.OCSPRequestBuilder()

        # add_certificate returns an initialized OCSPRequestBuilder
        orb = orb.add_certificate(
            cert, issuer_cert, cryptography.hazmat.primitives.hashes.SHA256())
        request = orb.build()

        path = base64.b64encode(
            request.public_bytes(hazmat.primitives.serialization.Encoding.DER))
        url = urljoin(server, path.decode("ascii"))
        return url
Ejemplo n.º 12
0
def is_ocsp_valid(cert, issuer, hash_algo):
    if hash_algo == 'sha1':
        algorithm = hashes.SHA1
    elif hash_algo == 'sha224':
        algorithm = hashes.SHA224
    elif hash_algo == 'sha256':
        algorithm = hashes.SHA256
    elif hash_algo == 'sha385':
        algorithm = hashes.SHA384
    elif hash_algo == 'sha512':
        algorithm = hashes.SHA512
    else:
        log("Invalid hash algorithm '{}' used for OCSP validation. Validation ignored."
            .format(hash_algo),
            warning=True)
        return True

    if isinstance(issuer, list):
        issuer = issuer[
            0]  # First certificate in the CA chain is the immediate issuer

    try:
        ocsp_urls = []
        aia = cert.extensions.get_extension_for_oid(
            ExtensionOID.AUTHORITY_INFORMATION_ACCESS)
        for data in aia.value:
            if data.access_method == x509.OID_OCSP:
                ocsp_urls.append(data.access_location.value)

        # This is a bit of a hack due to validation problems within cryptography (TODO: Check if this is still true)
        # Correct replacement:  ocsprequest = ocsp.OCSPRequestBuilder().add_certificate(cert, issuer, algorithm).build()
        ocsprequest = ocsp.OCSPRequestBuilder(
            (cert, issuer, algorithm)).build()
        ocsprequestdata = ocsprequest.public_bytes(serialization.Encoding.DER)
        for ocsp_url in ocsp_urls:
            response = get_url(
                ocsp_url, ocsprequestdata, {
                    'Accept': 'application/ocsp-response',
                    'Content-Type': 'application/ocsp-request',
                })
            ocspresponsedata = response.read()
            ocspresponse = ocsp.load_der_ocsp_response(ocspresponsedata)
            if ocspresponse.response_status == ocsp.OCSPResponseStatus.SUCCESSFUL \
                    and ocspresponse.certificate_status == ocsp.OCSPCertStatus.REVOKED:
                return False
    except Exception as e:
        log("An exception occurred during OCSP validation (Validation will be ignored): {}"
            .format(e),
            error=True)

    return True
Ejemplo n.º 13
0
def validate_chain(cert_to_check,issuer_cert):
    cert_to_check_signature=cert_to_check.signature
    issuer_public_key=issuer_cert.public_key()
    
    # TODO check if host has the same name I think
    builder = ocsp.OCSPRequestBuilder()
    # SHA1 is in this example because RFC 5019 mandates its use.
    builder = builder.add_certificate(cert_to_check, issuer_cert, SHA1())
    req = builder.build()

    for j in cert_to_check.extensions.get_extension_for_class(x509.AuthorityInformationAccess).value:
        if j.access_method.dotted_string == "1.3.6.1.5.5.7.48.1": 
            rev_list=None

            #Downloading list
            der=req.public_bytes(serialization.Encoding.DER)

            ocsp_link=j.access_location.value
            r=requests.post(ocsp_link,data=der)

            ocsp_resp = ocsp.load_der_ocsp_response(r.content)
            print(ocsp_resp.certificate_status)



                

    
    



    
    print(cert_to_check.extensions.get_extension_for_class(x509.KeyUsage).value)


    if (get_issuer_common_name(cert_to_check)!=get_common_name(issuer_cert)):
        print(get_issuer_common_name(cert_to_check))
        print(get_common_name(issuer_cert))
        return False 
        

    try:
        issuer_public_key.verify(cert_to_check_signature,cert_to_check.tbs_certificate_bytes,padding.PKCS1v15(),cert_to_check.signature_hash_algorithm)
    except:
        print("Failed to verify signature.")
        return False
    
    return True
Ejemplo n.º 14
0
def _get_sample_request_for_root(root, hash_algorithm, pebble_urlopen):
    '''
    Returns an OCSP sample request for this root, together with the intermediate certificate and its key.
    '''
    cache_key = (root, hash_algorithm.name)
    if cache_key in SAMPLE_REQUEST_CACHE:
        return SAMPLE_REQUEST_CACHE[cache_key]

    # Get hold of intermediate certificate with key
    intermediate = x509.load_pem_x509_certificate(pebble_urlopen(
        "/intermediates/{0}".format(root)).read(),
                                                  backend=default_backend())
    intermediate_key = serialization.load_pem_private_key(
        pebble_urlopen("/intermediate-keys/{0}".format(root)).read(),
        None,
        backend=default_backend())

    one_day = datetime.timedelta(1, 0, 0)
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(intermediate.subject)
    builder = builder.issuer_name(intermediate.subject)
    builder = builder.not_valid_before(datetime.datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.datetime.today() + one_day)
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(intermediate.public_key())
    certificate = builder.sign(private_key=intermediate_key,
                               algorithm=hashes.SHA256(),
                               backend=default_backend())

    req = ocsp.OCSPRequestBuilder()
    req = req.add_certificate(certificate, intermediate, hash_algorithm)
    req = req.build()

    result = req, intermediate, intermediate_key
    SAMPLE_REQUEST_CACHE[cache_key] = result
    return result
Ejemplo n.º 15
0
def build_ocsp_request(cert_chain: List[str]) -> bytes:
    """Build an OCSP request out of the leaf and issuer pem certificates
    see: https://cryptography.io/en/latest/x509/ocsp/#cryptography.x509.ocsp.OCSPRequestBuilder
    for more information"""

    func_name: str = "build_ocsp_request"

    try:
        leaf_cert = x509.load_pem_x509_certificate(str.encode(cert_chain[0]),
                                                   default_backend())
        issuer_cert = x509.load_pem_x509_certificate(str.encode(cert_chain[1]),
                                                     default_backend())

    except ValueError:
        raise Exception(
            f"{func_name}: Unable to load x509 certificate.") from None

    # Build OCSP request
    builder = ocsp.OCSPRequestBuilder()
    builder = builder.add_certificate(leaf_cert, issuer_cert, SHA1())
    ocsp_data = builder.build()
    ocsp_request_data = ocsp_data.public_bytes(serialization.Encoding.DER)

    return ocsp_request_data
Ejemplo n.º 16
0
def sign(datau,
         key,
         cert,
         othercerts,
         hashalgo,
         attrs=True,
         signed_value=None,
         hsm=None,
         pss=False,
         timestampurl=None,
         timestampcredentials=None,
         timestamp_req_options=None,
         ocspurl=None,
         ocspissuer=None):
    if signed_value is None:
        signed_value = getattr(hashlib, hashalgo)(datau).digest()
    signed_time = datetime.now(tz=util.timezone.utc)

    if hsm is not None:
        keyid, cert = hsm.certificate()
        cert = cert2asn(cert, False)
    else:
        cert = cert2asn(cert)

    certificates = []
    certificates.append(cert)
    for i in range(len(othercerts)):
        certificates.append(cert2asn(othercerts[i]))

    hashalgo = unicode(hashalgo) if sys.version[0] < '3' else hashalgo

    signer = {
        'version':
        'v1',
        'sid':
        cms.SignerIdentifier({
            'issuer_and_serial_number':
            cms.IssuerAndSerialNumber({
                'issuer': cert.issuer,
                'serial_number': cert.serial_number,
            }),
        }),
        'digest_algorithm':
        algos.DigestAlgorithm({'algorithm': hashalgo}),
        'signature':
        signed_value,
    }
    if not pss:
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm(
            {'algorithm': 'rsassa_pkcs1v15'})
    else:
        if isinstance(key, keys.PrivateKeyInfo):
            salt_length = key.byte_size - hashes.SHA512.digest_size - 2
            salt_length = hashes.SHA512.digest_size
        else:
            salt_length = padding.calculate_max_pss_salt_length(
                key, hashes.SHA512)
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm({
            'algorithm':
            'rsassa_pss',
            'parameters':
            algos.RSASSAPSSParams({
                'hash_algorithm':
                algos.DigestAlgorithm({'algorithm': 'sha512'}),
                'mask_gen_algorithm':
                algos.MaskGenAlgorithm({
                    'algorithm':
                    algos.MaskGenAlgorithmId('mgf1'),
                    'parameters': {
                        'algorithm': algos.DigestAlgorithmId('sha512'),
                    }
                }),
                'salt_length':
                algos.Integer(salt_length),
                'trailer_field':
                algos.TrailerField(1)
            })
        })

    if attrs:
        if attrs is True:
            signer['signed_attrs'] = [
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('content_type'),
                    'values': ('data', ),
                }),
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('message_digest'),
                    'values': (signed_value, ),
                }),
                cms.CMSAttribute({
                    'type':
                    cms.CMSAttributeType('signing_time'),
                    'values':
                    (cms.Time({'utc_time': core.UTCTime(signed_time)}), )
                }),
            ]
        else:
            if isinstance(attrs, types.FunctionType):
                attrs = attrs(signed_value)
            signer['signed_attrs'] = attrs

    config = {
        'version':
        'v1',
        'digest_algorithms':
        cms.DigestAlgorithms((algos.DigestAlgorithm({'algorithm':
                                                     hashalgo}), )),
        'encap_content_info': {
            'content_type': 'data',
        },
        'certificates':
        certificates,
        'signer_infos': [
            signer,
        ],
    }
    if ocspurl and ocspissuer:
        from cryptography.hazmat.backends.openssl.backend import backend
        from cryptography.x509 import ocsp as cocsp
        from cryptography import x509 as cx509

        ocspuser = cert.dump()
        ocspuser = cx509.load_der_x509_certificate(ocspuser, backend=backend)

        builder = cocsp.OCSPRequestBuilder()
        builder = builder.add_certificate(ocspuser, ocspissuer, hashes.SHA1())
        req = builder.build()
        data = req.public_bytes(serialization.Encoding.DER)

        response = requests.post(
            ocspurl,
            headers={'Content-Type': 'application/ocsp-request'},
            data=data,
        )
        data = ocsp.OCSPResponse.load(response.content)
        other = cms.RevocationInfoChoice({
            'other':
            cms.OtherRevocationInfoFormat({
                'other_rev_info_format': 'ocsp_response',
                'other_rev_info': data
            })
        })
        config['crls'] = cms.RevocationInfoChoices([other])

    datas = cms.ContentInfo({
        'content_type': cms.ContentType('signed_data'),
        'content': cms.SignedData(config),
    })
    if attrs:
        tosign = datas['content']['signer_infos'][0]['signed_attrs'].dump()
        tosign = b'\x31' + tosign[1:]
    else:
        tosign = datau
    if hsm is not None:
        signed_value_signature = hsm.sign(keyid, tosign, hashalgo)
    elif isinstance(key, keys.PrivateKeyInfo):
        key = asymmetric.load_private_key(key)
        if pss:
            signed_value_signature = asymmetric.rsa_pss_sign(
                key, tosign, 'sha512')
        else:
            signed_value_signature = asymmetric.rsa_pkcs1v15_sign(
                key, tosign, hashalgo.lower())
    else:
        if pss:
            hasher = hashes.Hash(hashes.SHA512(),
                                 backend=backends.default_backend())
            hasher.update(tosign)
            digest = hasher.finalize()
            signed_value_signature = key.sign(
                digest,
                padding.PSS(mgf=padding.MGF1(hashes.SHA512()),
                            salt_length=salt_length),
                utils.Prehashed(hashes.SHA512()))
        else:
            signed_value_signature = key.sign(
                tosign, padding.PKCS1v15(),
                getattr(hashes, hashalgo.upper())())

    if timestampurl is not None:
        datas['content']['signer_infos'][0]['unsigned_attrs'] = timestamp(
            signed_value_signature,
            hashalgo,
            timestampurl,
            timestampcredentials,
            timestamp_req_options,
        )

    # signed_value_signature = core.OctetString(signed_value_signature)
    datas['content']['signer_infos'][0]['signature'] = signed_value_signature

    #open('signed-content-info', 'wb').write(datas.dump())
    return datas.dump()
def validate_revocation(cert, issuer):
    """
	Function used to check if a given certificate (or it's issuer) is revoked.
	:return: True, if it's revoked. False, otherwise.
	"""
    try:
        builder = ocsp.OCSPRequestBuilder()

        builder = builder.add_certificate(cert, issuer, SHA1())
        req = builder.build()

        for ext in cert.extensions.get_extension_for_class(
            x509.AuthorityInformationAccess
        ).value:
            if ext.access_method.dotted_string == "1.3.6.1.5.5.7.48.1":
                data = req.public_bytes(serialization.Encoding.DER)

                ocsp_url = ext.access_location.value
                request = requests.post(
                    ocsp_url,
                    headers={"Content-Type": "application/ocsp-request"},
                    data=data,
                )

                ocsp_resp = ocsp.load_der_ocsp_response(request.content)
                logger.warning(f"OCSP CERT STATUS: {ocsp_resp.certificate_status}")

                if (
                    ocsp_resp.certificate_status == ocsp.OCSPCertStatus.GOOD
                    or get_common_name(cert) == "ECRaizEstado"
                ):
                    return False
                else:
                    return True
    except:
        logger.debug("OCSP is not available for this certificate!")

    try:
        for ext in cert.extensions.get_extension_for_class(
            x509.CRLDistributionPoints
        ).value:
            for name in ext.full_name:
                file_name = wget.download(name.value)

                revocation_list = load_certificate_crl(file_name)

                if revocation_list is None:
                    return False

                cert_is_revoked = cert.serial_number in [
                    l.serial_number for l in revocation_list
                ]
        try:
            for ext in cert.extensions.get_extension_for_class(x509.FreshestCRL).value:
                for name in ext.full_name:
                    file_name = wget.download(name.value)

                    revocation_list = load_certificate_crl(file_name)

                    if revocation_list is None:
                        return False

                    cert_is_revoked = cert.serial_number in [
                        l.serial_number for l in revocation_list
                    ]
        except:
            logger.debug("DELTA CRL is not available for this certificate!")

        for ext in issuer.extensions.get_extension_for_class(
            x509.CRLDistributionPoints
        ).value:
            for name in ext.full_name:
                file_name = wget.download(name.value)

                revocation_list = load_certificate_crl(file_name)

                if revocation_list is None:
                    return False

                isser_is_revoked = issuer.serial_number in [
                    l.serial_number for l in revocation_list
                ]

        try:
            for ext in issuer.extensions.get_extension_for_class(
                x509.FreshestCRL
            ).value:
                for name in ext.full_name:
                    file_name = wget.download(name.value)

                    revocation_list = load_certificate_crl(file_name)

                    if revocation_list is None:
                        return False

                    isser_is_revoked = issuer.serial_number in [
                        l.serial_number for l in revocation_list
                    ]
        except:
            logger.debug("DELTA CRL is not available for this certificate!")

        return cert_is_revoked or isser_is_revoked
    except:
        logger.debug("CRL is not available for this certificate!")

    return True
Ejemplo n.º 18
0
 def test_add_extension_twice(self):
     builder = ocsp.OCSPRequestBuilder()
     builder = builder.add_extension(x509.OCSPNonce(b"123"), False)
     with pytest.raises(ValueError):
         builder.add_extension(x509.OCSPNonce(b"123"), False)
Ejemplo n.º 19
0
 def test_create_ocsp_request_invalid_alg(self):
     cert, issuer = _cert_and_issuer()
     builder = ocsp.OCSPRequestBuilder()
     with pytest.raises(ValueError):
         builder.add_certificate(cert, issuer, hashes.MD5())
Ejemplo n.º 20
0
 def test_create_ocsp_request_no_req(self):
     builder = ocsp.OCSPRequestBuilder()
     with pytest.raises(ValueError):
         builder.build()
Ejemplo n.º 21
0
 def test_add_two_certs(self):
     cert, issuer = _cert_and_issuer()
     builder = ocsp.OCSPRequestBuilder()
     builder = builder.add_certificate(cert, issuer, hashes.SHA1())
     with pytest.raises(ValueError):
         builder.add_certificate(cert, issuer, hashes.SHA1())
Ejemplo n.º 22
0
    def validate_revocation(self, cert_to_check, issuer_cert):

        try:
            builder = ocsp.OCSPRequestBuilder()

            builder = builder.add_certificate(cert_to_check, issuer_cert,
                                              SHA1())
            req = builder.build()
            for j in cert_to_check.extensions.get_extension_for_class(
                    x509.AuthorityInformationAccess).value:
                if j.access_method.dotted_string == "1.3.6.1.5.5.7.48.1":
                    rev_list = None

                    #Downloading list
                    der = req.public_bytes(serialization.Encoding.DER)

                    ocsp_link = j.access_location.value
                    r = requests.post(
                        ocsp_link,
                        headers={'Content-Type': 'application/ocsp-request'},
                        data=der)

                    ocsp_resp = ocsp.load_der_ocsp_response(r.content)
                    if ocsp_resp.certificate_status == ocsp.OCSPCertStatus.GOOD:
                        return False
                    else:
                        return True

        except Exception as e:
            logger.debug("OCSP not available")

        try:
            for i in cert_to_check.extensions.get_extension_for_class(
                    x509.CRLDistributionPoints).value:
                for b in i.full_name:
                    rev_list = None
                    #Downloading list
                    file_name = wget.download(b.value)
                    print()
                    #read revocation list
                    try:
                        rev_list = self.load_cert_revocation_list(
                            file_name, "pem")
                    except Exception as e:
                        logger.debug(e)
                    try:
                        rev_list = self.load_cert_revocation_list(
                            file_name, "der")
                    except:
                        logger.debug("Not der.")
                    if rev_list is None:
                        return False

                    flag = cert_to_check.serial_number in [
                        l.serial_number for l in rev_list
                    ]
            try:
                for i in cert_to_check.extensions.get_extension_for_class(
                        x509.FreshestCRL).value:
                    for b in i.full_name:
                        rev_list = None
                        #Downloading list
                        file_name = wget.download(b.value)
                        #read revocation list
                        try:
                            rev_list = self.load_cert_revocation_list(
                                file_name, "pem")
                        except Exception as e:
                            logger.debug(e)
                        try:
                            rev_list = self.load_cert_revocation_list(
                                file_name, "der")
                        except:
                            logger.debug("Not der.")
                        if rev_list is None:
                            return False

                        flag = cert_to_check.serial_number in [
                            l.serial_number for l in rev_list
                        ]
            except:
                logger.debug("DELTA CRL not available.")

            for i in issuer_cert.extensions.get_extension_for_class(
                    x509.CRLDistributionPoints).value:
                for b in i.full_name:
                    rev_list = None
                    #Downloading list
                    file_name = wget.download(b.value)
                    print()

                    #read revocation list
                    try:
                        rev_list = self.load_cert_revocation_list(
                            file_name, "pem")
                    except Exception as e:
                        logger.debug(e)

                    try:
                        rev_list = self.load_cert_revocation_list(
                            file_name, "der")
                    except:
                        logger.debug("Not der.")
                    if rev_list is None:
                        return False

                    flag1 = issuer_cert.serial_number in [
                        l.serial_number for l in rev_list
                    ]

                    return flag1 or flag

            try:
                for i in issuer_cert.extensions.get_extension_for_class(
                        x509.FreshestCRL).value:
                    for b in i.full_name:
                        rev_list = None
                        #Downloading list
                        file_name = wget.download(b.value)

                        #read revocation list
                        try:
                            rev_list = self.load_cert_revocation_list(
                                file_name, "pem")
                        except Exception as e:
                            logger.debug(e)

                        try:
                            rev_list = self.load_cert_revocation_list(
                                file_name, "der")
                        except:
                            logger.debug("Not der.")
                        if rev_list is None:
                            return False

                        flag1 = issuer_cert.serial_number in [
                            l.serial_number for l in rev_list
                        ]

            except:
                logger.debug("DELTA CRL not available.")
            return flag1 or flag

        except Exception as e:
            logger.debug("CRL not available")

        return True
Ejemplo n.º 23
0
                expires=data[name]["expires"],
                password=pwd,
                extensions=data[name]["extensions"],
            )
        data[name].update(
            data[name].pop("extensions"))  # cert_data expects this to be flat
        copy_cert(cert, data[name], key_path, csr_path)

    # Rebuild example OCSP requests
    if args.ocsp:
        from cryptography.x509 import ocsp

        ocsp_base = os.path.join(args.dest, "ocsp")
        if not os.path.exists(ocsp_base):
            os.makedirs(ocsp_base)
        ocsp_builder = ocsp.OCSPRequestBuilder()
        ocsp_builder = ocsp_builder.add_certificate(
            data["child-cert"]["parsed_cert"].pub.loaded,
            CertificateAuthority.objects.get(
                name=data["child-cert"]["ca"]).pub.loaded,
            hashes.SHA1(),
        )

        no_nonce_req = ocsp_builder.build().public_bytes(Encoding.DER)
        with open(os.path.join(ocsp_base, ocsp_data["no-nonce"]["filename"]),
                  "wb") as stream:
            stream.write(no_nonce_req)

        ocsp_builder = ocsp_builder.add_extension(x509.OCSPNonce(
            hex_to_bytes(ocsp_data["nonce"]["nonce"])),
                                                  critical=False)