def test_build_basic_request(self):
        issuer_cert = asymmetric.load_certificate(
            os.path.join(fixtures_dir, 'test.crt'))
        subject_cert = asymmetric.load_certificate(
            os.path.join(fixtures_dir, 'test-inter.crt'))

        builder = OCSPRequestBuilder(subject_cert, issuer_cert)
        ocsp_request = builder.build()
        der_bytes = ocsp_request.dump()

        new_request = asn1crypto.ocsp.OCSPRequest.load(der_bytes)
        tbs_request = new_request['tbs_request']

        self.assertEqual(None, new_request['optional_signature'].native)
        self.assertEqual('v1', tbs_request['version'].native)
        self.assertEqual(None, tbs_request['requestor_name'].native)
        self.assertEqual(1, len(tbs_request['request_list']))

        request = tbs_request['request_list'][0]
        self.assertEqual(
            'sha1', request['req_cert']['hash_algorithm']['algorithm'].native)
        self.assertEqual(issuer_cert.asn1.subject.sha1,
                         request['req_cert']['issuer_name_hash'].native)
        self.assertEqual(issuer_cert.asn1.public_key.sha1,
                         request['req_cert']['issuer_key_hash'].native)
        self.assertEqual(subject_cert.asn1.serial_number,
                         request['req_cert']['serial_number'].native)
        self.assertEqual(0, len(request['single_request_extensions']))

        self.assertEqual(1, len(tbs_request['request_extensions']))
        extn = tbs_request['request_extensions'][0]

        self.assertEqual('nonce', extn['extn_id'].native)
        self.assertEqual(16, len(extn['extn_value'].parsed.native))
示例#2
0
    def ocsp_validation(self, subject_cert, issuer_cert):
        ocsp_link = self.get_ocsp_link(subject_cert)

        subject_cert = asymmetric.load_certificate(
            crypto.dump_certificate(
                crypto.FILETYPE_ASN1,
                subject_cert
                )
            )

        issuer_cert = asymmetric.load_certificate(  
            crypto.dump_certificate(
                crypto.FILETYPE_ASN1,
                issuer_cert
            ))
        builder = OCSPRequestBuilder(subject_cert, issuer_cert)
        ocsp_request = builder.build()

        flag = False

        for x in range(1,3):
            try:
                r = requests.post(
                ocsp_link,
                data = ocsp_request.dump(),
                headers={"Content-Type": "application/ocsp-request"}
                )
                resposta = asn1crypto.ocsp.OCSPResponse.load(r.content)
                break
            except Exception as e:
                print("failed OCSP {0} times".format(x))

        return "good" == resposta['response_bytes']['response'].parsed['tbs_response_data']["responses"][0]["cert_status"].name
    def test_build_signed_request(self):
        issuer_cert = asymmetric.load_certificate(os.path.join(fixtures_dir, "test.crt"))
        subject_cert = asymmetric.load_certificate(os.path.join(fixtures_dir, "test-inter.crt"))

        requestor_cert = asymmetric.load_certificate(os.path.join(fixtures_dir, "test-third.crt"))
        requestor_key = asymmetric.load_private_key(os.path.join(fixtures_dir, "test-third.key"))

        builder = OCSPRequestBuilder(subject_cert, issuer_cert)
        ocsp_request = builder.build(requestor_key, requestor_cert, [subject_cert, issuer_cert])
        der_bytes = ocsp_request.dump()

        new_request = asn1crypto.ocsp.OCSPRequest.load(der_bytes)
        tbs_request = new_request["tbs_request"]
        signature = new_request["optional_signature"]

        self.assertEqual("sha256", signature["signature_algorithm"].hash_algo)
        self.assertEqual("rsassa_pkcs1v15", signature["signature_algorithm"].signature_algo)
        self.assertEqual(3, len(signature["certs"]))
        self.assertEqual("v1", tbs_request["version"].native)
        self.assertEqual(requestor_cert.asn1.subject, tbs_request["requestor_name"].chosen)
        self.assertEqual(1, len(tbs_request["request_list"]))

        request = tbs_request["request_list"][0]
        self.assertEqual("sha1", request["req_cert"]["hash_algorithm"]["algorithm"].native)
        self.assertEqual(issuer_cert.asn1.subject.sha1, request["req_cert"]["issuer_name_hash"].native)
        self.assertEqual(issuer_cert.asn1.public_key.sha1, request["req_cert"]["issuer_key_hash"].native)
        self.assertEqual(subject_cert.asn1.serial_number, request["req_cert"]["serial_number"].native)
        self.assertEqual(0, len(request["single_request_extensions"]))

        self.assertEqual(1, len(tbs_request["request_extensions"]))
        extn = tbs_request["request_extensions"][0]

        self.assertEqual("nonce", extn["extn_id"].native)
        self.assertEqual(16, len(extn["extn_value"].parsed.native))
    def test_build_basic_request(self):
        issuer_cert = asymmetric.load_certificate(os.path.join(fixtures_dir, "test.crt"))
        subject_cert = asymmetric.load_certificate(os.path.join(fixtures_dir, "test-inter.crt"))

        builder = OCSPRequestBuilder(subject_cert, issuer_cert)
        ocsp_request = builder.build()
        der_bytes = ocsp_request.dump()

        new_request = asn1crypto.ocsp.OCSPRequest.load(der_bytes)
        tbs_request = new_request["tbs_request"]

        self.assertEqual(None, new_request["optional_signature"].native)
        self.assertEqual("v1", tbs_request["version"].native)
        self.assertEqual(None, tbs_request["requestor_name"].native)
        self.assertEqual(1, len(tbs_request["request_list"]))

        request = tbs_request["request_list"][0]
        self.assertEqual("sha1", request["req_cert"]["hash_algorithm"]["algorithm"].native)
        self.assertEqual(issuer_cert.asn1.subject.sha1, request["req_cert"]["issuer_name_hash"].native)
        self.assertEqual(issuer_cert.asn1.public_key.sha1, request["req_cert"]["issuer_key_hash"].native)
        self.assertEqual(subject_cert.asn1.serial_number, request["req_cert"]["serial_number"].native)
        self.assertEqual(0, len(request["single_request_extensions"]))

        self.assertEqual(1, len(tbs_request["request_extensions"]))
        extn = tbs_request["request_extensions"][0]

        self.assertEqual("nonce", extn["extn_id"].native)
        self.assertEqual(16, len(extn["extn_value"].parsed.native))
示例#5
0
    def get_ocsp_status(self,cert,is_cert,cert_url,is_cert_url):
        t0 = time.clock()
        #print "Issuer Certificate is >> %s" %(is_cert_name)
        c = OpenSSL.crypto
        
        if not isinstance(cert, c.X509) or not isinstance(is_cert, c.X509):
            return False
        
        id_cert_buf = c.dump_certificate(c.FILETYPE_PEM, cert)
        issuer_cert_buf = c.dump_certificate(c.FILETYPE_PEM, is_cert)
        # with open(cert_name,"rb") as f:
        #     id_cert_buf = f.read()
        # with open(is_cert_name,"rb") as f:
        #     issuer_cert_buf = f.read()

        id_cert = asymmetric.load_certificate(id_cert_buf)
        issuer_cert = asymmetric.load_certificate(issuer_cert_buf)

        builder = OCSPRequestBuilder(id_cert, issuer_cert)
        ocsp_request = builder.build()

        ocsp_req_dump = ocsp_request.dump()

        cert_ocsp_url = cert_url 
        is_ocsp_url = is_cert_url 
        
        resp = requests.post(cert_ocsp_url, ocsp_req_dump)

        ocsp_response = resp.content

        ocspResponse = OCSPResponse()
        basicOcspResponse = BasicOCSPResponse()

        decoded_resp = der_decoder.decode(ocsp_response, asn1Spec=ocspResponse)
        
        for resp in decoded_resp:
        
            if isinstance(resp, OCSPResponse):
                ocsp_response_status = resp.getComponentByName('responseStatus')
                
                ocsp_resp_bytes = resp.getComponentByName('responseBytes')
                ocsp_resp = ocsp_resp_bytes.getComponentByName('response') 
                basic_ocsp_response, _ = der_decoder.decode(ocsp_resp, asn1Spec=basicOcspResponse)
                tbs_response_data = basic_ocsp_response.getComponentByName('tbsResponseData')
                responses = tbs_response_data.getComponentByName('responses')
                for response in responses:
                    
                    serial_no = response.getComponentByName('certID').getComponentByName('serialNumber')                
                    #print str(serial_no)
                    #print response.getComponentByName('certStatus').getName()
                    print time.clock() - t0
                    if response.getComponentByName('certStatus').getName() == "good":
                        return True
                    else:
                        return False
def isRevoked(url, rawCert):
    subject_cert = asymmetric.load_certificate(base64.b64decode(rawCert))
    builder = OCSPRequestBuilder(subject_cert, issuerCerts[url])
    ocsp_request = builder.build()
    url = urlparse(url)
    headers = {}
    conn = httplib.HTTPConnection(url.netloc)
    conn.request("POST", url.path, ocsp_request.dump(), headers)
    res = conn.getresponse().read()
    ocspResponseClass = ocsp.OCSPResponse.load(res)
    return (ocspResponseClass.response_data['responses'][0]['cert_status'].name != 'good')
def verifycert(certificate,store,server=False):
	# Load do cert ja feito
	# DO OCSP para ver as crl
	if server == False:
		cert = oscrypto.load_certificate(openssl.dump_certificate(openssl.FILETYPE_ASN1, certificate))
		issuer_cert = oscrypto.load_certificate(getIssuer(certificate))
		ocsp_builder = OCSPRequestBuilder(cert, issuer_cert)

		ocsp_request = ocsp_builder.build().dump()

		CN = certificate.get_subject().commonName

		if CN in ('Baltimore CyberTrust Root', 'ECRaizEstado'):
			url = 'http://ocsp.omniroot.com/baltimoreroot/'
		elif CN[:-4] == 'Cartao de Cidadao':
			url = 'http://ocsp.ecee.gov.pt/'
		elif CN[:-5] == 'EC de Autenticacao do Cartao de Cidadao':
			url = 'http://ocsp.root.cartaodecidadao.pt/publico/ocsp'
		else:
			url = 'http://ocsp.auc.cartaodecidadao.pt/publico/ocsp'

		http_req = urllib2.Request(
			url,
			data=ocsp_request,
			headers={'Content-Type': 'application/ocsp-request'}
		)

		http = urllib2.urlopen(http_req)
		ocsp_response = http.read()

		ocsp_response = asn1crypto.ocsp.OCSPResponse.load(ocsp_response)
		response_data = ocsp_response.basic_ocsp_response['tbs_response_data']
		cert_response = response_data['responses'][0]

		#print cert_response['cert_status'].name

		if cert_response['cert_status'].name != 'good':
			return False

	try:
		certV = openssl.X509StoreContext(store, certificate)
		certV.verify_certificate()
	except:
		return False
	return True
    def test_build_signed_request(self):
        issuer_cert = asymmetric.load_certificate(
            os.path.join(fixtures_dir, 'test.crt'))
        subject_cert = asymmetric.load_certificate(
            os.path.join(fixtures_dir, 'test-inter.crt'))

        requestor_cert = asymmetric.load_certificate(
            os.path.join(fixtures_dir, 'test-third.crt'))
        requestor_key = asymmetric.load_private_key(
            os.path.join(fixtures_dir, 'test-third.key'))

        builder = OCSPRequestBuilder(subject_cert, issuer_cert)
        ocsp_request = builder.build(requestor_key, requestor_cert,
                                     [subject_cert, issuer_cert])
        der_bytes = ocsp_request.dump()

        new_request = asn1crypto.ocsp.OCSPRequest.load(der_bytes)
        tbs_request = new_request['tbs_request']
        signature = new_request['optional_signature']

        self.assertEqual('sha256', signature['signature_algorithm'].hash_algo)
        self.assertEqual('rsassa_pkcs1v15',
                         signature['signature_algorithm'].signature_algo)
        self.assertEqual(3, len(signature['certs']))
        self.assertEqual('v1', tbs_request['version'].native)
        self.assertEqual(requestor_cert.asn1.subject,
                         tbs_request['requestor_name'].chosen)
        self.assertEqual(1, len(tbs_request['request_list']))

        request = tbs_request['request_list'][0]
        self.assertEqual(
            'sha1', request['req_cert']['hash_algorithm']['algorithm'].native)
        self.assertEqual(issuer_cert.asn1.subject.sha1,
                         request['req_cert']['issuer_name_hash'].native)
        self.assertEqual(issuer_cert.asn1.public_key.sha1,
                         request['req_cert']['issuer_key_hash'].native)
        self.assertEqual(subject_cert.asn1.serial_number,
                         request['req_cert']['serial_number'].native)
        self.assertEqual(0, len(request['single_request_extensions']))

        self.assertEqual(1, len(tbs_request['request_extensions']))
        extn = tbs_request['request_extensions'][0]

        self.assertEqual('nonce', extn['extn_id'].native)
        self.assertEqual(16, len(extn['extn_value'].parsed.native))
示例#9
0
def validateCert(store, cert, server=False):

    if not server:
        issuer = getIssuerCertificate(cert)

        subject_cert = asymmetric.load_certificate(dumpCertificate(
            cert, False))
        issuer_cert = asymmetric.load_certificate(
            dumpCertificate(issuer, False))

        builder = OCSPRequestBuilder(subject_cert, issuer_cert)
        ocsp_request_der = builder.build().dump()

        cert_name = cert.get_subject().commonName

        if cert_name in ('Baltimore CyberTrust Root', 'ECRaizEstado'):
            ocsp_url = 'http://ocsp.omniroot.com/baltimoreroot/'
        elif cert_name[:-4] == 'Cartao de Cidadao':
            ocsp_url = 'http://ocsp.ecee.gov.pt/'
        elif cert_name[:-5] == 'EC de Autenticacao do Cartao de Cidadao':
            ocsp_url = 'http://ocsp.root.cartaodecidadao.pt/publico/ocsp'
        else:
            ocsp_url = 'http://ocsp.auc.cartaodecidadao.pt/publico/ocsp'

        http_req = urllib2.Request(
            ocsp_url,
            data=ocsp_request_der,
            headers={'Content-Type': 'application/ocsp-request'})
        http = urllib2.urlopen(http_req)
        ocsp_response_der = http.read()
        ocsp_response = asn1crypto.ocsp.OCSPResponse.load(ocsp_response_der)
        response_data = ocsp_response.basic_ocsp_response['tbs_response_data']
        cert_response = response_data['responses'][0]

        if cert_response['cert_status'].name != 'good':
            return False

    context_store = openssl.X509StoreContext(store, cert)
    try:
        context_store.verify_certificate()

        return True
    except:
        return False
示例#10
0
def create_ocsp_request(cert, issuer):
    """Takes a certificate and the issuing certificate in oscrypto._openssl.asymmetric.Certificate format and creates
    an OCSP request body. """
    builder = OCSPRequestBuilder(cert, issuer)
    return builder.build().dump()
示例#11
0
id_cert_buf = open(id_cert_path, 'r').read()
issuer_cert_buf = open(issuer_cert_path, 'r').read()

id_cert = asymmetric.load_certificate(id_cert_buf)
issuer_cert = asymmetric.load_certificate(issuer_cert_buf)

id_cert_filebuf = open(id_cert_path, 'r').read()
id_cert_x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, id_cert_filebuf)

#print dir(id_cert_x509)
#print id_cert_x509.get_serial_number()
id_cert_serial_number = format(id_cert_x509.get_serial_number(), 'x')
print "Checking OCSP status for cert : " + id_cert_serial_number
print '\n'

builder = OCSPRequestBuilder(id_cert, issuer_cert)
ocsp_request = builder.build()
#print type(ocsp_request)

ocsp_req_dump = ocsp_request.dump()

with open('ocsp_request_citi.der', 'wb') as f:
    f.write(ocsp_request.dump())
    

ocsp_request_file_contents = open('ocsp_request.der', 'r').read()

#import httplib

ocsp_url = 'http://clients1.google.com/ocsp'
ocsp_url_citi = 'http://sr.symcd.com'