Exemple #1
0
 def test_verify_final(self):
     from M2Crypto import X509
     pkey = EVP.load_key('tests/signer_key.pem')
     pkey.sign_init()
     pkey.sign_update('test  message')
     sig = pkey.sign_final()
     
     # OK
     x509 = X509.load_cert('tests/signer.pem')
     pubkey = x509.get_pubkey()
     pubkey.verify_init()
     pubkey.verify_update('test  message')
     assert pubkey.verify_final(sig) == 1
     
     # wrong cert
     x509 = X509.load_cert('tests/x509.pem')
     pubkey = x509.get_pubkey()
     pubkey.verify_init()
     pubkey.verify_update('test  message')
     assert pubkey.verify_final(sig) == 0
     
     # wrong message
     x509 = X509.load_cert('tests/signer.pem')
     pubkey = x509.get_pubkey()
     pubkey.verify_init()
     pubkey.verify_update('test  message not')
     assert pubkey.verify_final(sig) == 0
    def test_get_certs_from_string_valid(self):
        root_ca_path = os.path.join(CA_CHAIN_TEST_DATA, "certs/ROOT_CA/root_ca.pem")
        sub_ca_path = os.path.join(CA_CHAIN_TEST_DATA, "certs/SUB_CA/sub_ca.pem")
        ca_chain_path = os.path.join(CA_CHAIN_TEST_DATA, "certs/ca_chain")

        expected_root_ca_cert = X509.load_cert(root_ca_path)
        self.assertTrue(expected_root_ca_cert.check_ca())

        expected_sub_ca_cert = X509.load_cert(sub_ca_path)
        self.assertTrue(expected_sub_ca_cert.check_ca())

        data = open(ca_chain_path).read()
        certs = self.utils.get_certs_from_string(data)
        self.assertEquals(len(certs), 3)
        self.assertTrue(certs[0].check_ca())
        self.assertTrue(expected_root_ca_cert.get_subject().as_hash(),
                        certs[0].get_subject().as_hash())
        self.assertTrue(expected_root_ca_cert.get_issuer().as_hash(),
                        certs[0].get_issuer().as_hash())

        self.assertTrue(certs[1].check_ca())
        self.assertTrue(expected_sub_ca_cert.get_subject().as_hash(),
                        certs[1].get_subject().as_hash())
        self.assertTrue(expected_sub_ca_cert.get_issuer().as_hash(),
                        certs[1].get_issuer().as_hash())
Exemple #3
0
    def _ok_to_renew_cert(self, pkcs12, name, extract):
        res = False
        if os.path.exists(pkcs12):
            x509 = self._extractPKCS12Certificate(pkcs12)
            if self._expired(x509):
                if not extract:
                    res = True
                else:
                    if x509.verify(
                        X509.load_cert(
                            oenginecons.FileLocations.
                            OVIRT_ENGINE_PKI_ENGINE_CA_CERT
                        ).get_pubkey()
                    ):
                        self.logger.debug(
                            'certificate is an internal certificate'
                        )

                        # sanity check, make sure user did not manually
                        # change cert
                        x509x = X509.load_cert(
                            os.path.join(
                                (
                                    oenginecons.FileLocations.
                                    OVIRT_ENGINE_PKICERTSDIR
                                ),
                                '%s.cer' % name,
                            )
                        )

                        if x509x.as_pem() == x509.as_pem():
                            self.logger.debug('certificate is sane')
                            res = True
        return res
def validate_cert(cert_str, subca_str):
    cert = X509.load_cert_string(cert_str)
    sub_ca = X509.load_cert_string(subca_str)
    ecraiz = X509.load_cert(ecraiz_cert)

    if "001" not in sub_ca.get_issuer().as_text():
        cccert = X509.load_cert(cc_cert2, format=0)
    else:
        cccert = X509.load_cert(cc_cert1, format=0)

    if sub_ca.get_subject().as_text() == cert.get_issuer().as_text():
        pkey = sub_ca.get_pubkey()
        if not cert.verify(pkey):
            return False
        elif cccert.get_subject().as_text() == sub_ca.get_issuer().as_text():
            pkey = cccert.get_pubkey()
            if not sub_ca.verify(pkey):
                return False
            elif ecraiz.get_subject().as_text() == cccert.get_issuer().as_text():
                pkey = ecraiz.get_pubkey()
                if cccert.verify(pkey):
                    if ecraiz.verify(pkey):
                        return True

    return False
Exemple #5
0
    def test_long_serial(self):
        from M2Crypto import X509
        cert = X509.load_cert('tests/long_serial_cert.pem')
        self.assertEquals(cert.get_serial_number(), 17616841808974579194)

        cert = X509.load_cert('tests/thawte.pem')
        self.assertEquals(cert.get_serial_number(), 127614157056681299805556476275995414779)
Exemple #6
0
    def test_verify_with_add_crls(self):
        ca = X509.load_cert("tests/crl_data/certs/revoking_ca.pem")
        valid_cert = X509.load_cert('tests/crl_data/certs/valid_cert.pem')
        revoked_cert = X509.load_cert('tests/crl_data/certs/revoked_cert.pem')
        crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem')

        # Verify that a good cert is verified OK
        store = X509.X509_Store()
        store.add_x509(ca)
        store.set_flags(X509.m2.X509_V_FLAG_CRL_CHECK |
                       X509.m2.X509_V_FLAG_CRL_CHECK_ALL)
        crl_stack = X509.CRL_Stack()
        crl_stack.push(crl)
        store_ctx = X509.X509_Store_Context()
        store_ctx.init(store, valid_cert)
        store_ctx.add_crls(crl_stack)
        self.assertTrue(store_ctx.verify_cert())

        # Verify that a revoked cert is not verified
        store = X509.X509_Store()
        store.add_x509(ca)
        store.set_flags(X509.m2.X509_V_FLAG_CRL_CHECK |
                       X509.m2.X509_V_FLAG_CRL_CHECK_ALL)
        crl_stack = X509.CRL_Stack()
        crl_stack.push(crl)
        store_ctx = X509.X509_Store_Context()
        store_ctx.init(store, revoked_cert)
        store_ctx.add_crls(crl_stack)
        self.assertFalse(store_ctx.verify_cert())
Exemple #7
0
    def _late_setup(self):
        if (
            X509.load_cert(file=(oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT), format=X509.FORMAT_PEM)
            .get_pubkey()
            .get_rsa()
            .pub()
            != X509.load_cert(file=oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT, format=X509.FORMAT_PEM)
            .get_pubkey()
            .get_rsa()
            .pub()
        ):
            self.logger.warning(_("The CA certificate of Apache is changed"))
            self.dialog.note(
                text=_(
                    "{apache_ca} is different from {ca} .\n"
                    "It was probably replaced with a 3rd party certificate.\n"
                    "You might want to replace it again with a certificate\n"
                    "for the new host name.\n"
                ).format(
                    apache_ca=(oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT),
                    ca=(oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT),
                )
            )
        else:
            self._enabled = True

            self.environment[osetupcons.RenameEnv.FILES_TO_BE_MODIFIED].extend(
                (
                    oenginecons.FileLocations.OVIRT_ENGINE_PKI_APACHE_STORE,
                    oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_KEY,
                    oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CERT,
                )
            )
Exemple #8
0
 def test_load(self):
     x509 = X509.load_cert('tests/x509.pem')
     x5092 = X509.load_cert('tests/x509.der', format=X509.FORMAT_DER)
     self.assertEqual(x509.as_text(), x5092.as_text())
     self.assertEqual(x509.as_pem(), x5092.as_pem())
     self.assertEqual(x509.as_der(), x5092.as_der())
     return
Exemple #9
0
    def test_verify(self):
        ca = X509.load_cert("tests/crl_data/certs/revoking_ca.pem")
        crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem')
        self.assertTrue(crl.verify(ca.get_pubkey()))

        wrong_ca = X509.load_cert('tests/ca.pem')
        self.assertFalse(crl.verify(wrong_ca.get_pubkey()))
Exemple #10
0
    def test_easy_rsa_generated(self):
        """ Test loading a cert generated by easy RSA.

        https://github.com/fedora-infra/fedmsg/pull/389
        """
        # Does this raise an exception?
        X509.load_cert('tests/easy_rsa.pem')
Exemple #11
0
 def test_load(self):
     x509 = X509.load_cert('tests/x509.pem')
     x5092 = X509.load_cert('tests/x509.der', format=X509.FORMAT_DER)
     assert x509.as_text() == x5092.as_text()
     assert x509.as_pem() == x5092.as_pem()
     assert x509.as_der() == x5092.as_der()
     return
Exemple #12
0
    def test_data_is_valid(self):
        root_ca = X509.load_cert(ROOT_CA)
        self.assertTrue(root_ca.check_ca())

        sub_ca = X509.load_cert(SUB_CA)
        self.assertTrue(sub_ca.check_ca())

        test_cert = X509.load_cert(TEST_CERT)
        self.assertFalse(test_cert.check_ca())
Exemple #13
0
    def test_verify_with_missing_root_CA(self):
        sub_ca = X509.load_cert(SUB_CA)
        test_cert = X509.load_cert(TEST_CERT)

        store = X509.X509_Store()
        store.add_x509(sub_ca)
        store_ctx = X509.X509_Store_Context()
        store_ctx.init(store, test_cert)
        self.assertFalse(store_ctx.verify_cert())
Exemple #14
0
    def test_get_issuer(self):
        ca = X509.load_cert("tests/crl_data/certs/revoking_ca.pem")
        crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem')
        ca_issuer = ca.get_issuer()
        crl_issuer = crl.get_issuer()
        self.assertEqual(ca_issuer.as_hash(), crl_issuer.as_hash())

        wrong_ca = X509.load_cert('tests/ca.pem')
        wrong_ca_issuer = wrong_ca.get_issuer()
        self.assertNotEqual(wrong_ca_issuer.as_hash(), crl_issuer.as_hash())
Exemple #15
0
 def load_pub(self):
   if (self.loaded & 2) == 2:
     return
   l = os.listdir(self.ca_path)
   l.sort()
   for e in l:
     if re.match("(part.*)\.pem", e) != None:
       self.cert.append(X509.load_cert(self.ca_path + e))
   self.acert = X509.load_cert(self.ca_path + 'arbiter.pem')
   self.akey  = RSA.load_key(self.ca_path + 'arbiter.key')
   self.loaded |= 2
Exemple #16
0
    def test_verify_with_full_chain(self):
        root_ca = X509.load_cert(ROOT_CA)
        sub_ca = X509.load_cert(SUB_CA)
        test_cert = X509.load_cert(TEST_CERT)

        store = X509.X509_Store()
        store.add_x509(root_ca)
        store.add_x509(sub_ca)
        store_ctx = X509.X509_Store_Context()
        store_ctx.init(store, test_cert)
        self.assertTrue(store_ctx.verify_cert())
Exemple #17
0
def pki_verify_certificate(cert_loc, ca_cert_loc):
	"""
	Verifies a certificate by using CA certificate.
	Parameters:
		cert_loc = location of file with certificate to verify
		ca_cert_loc = location of file with CA certificate
	Return:
		1 if client certificate is valid, 0 otherwise.
	"""
	cert = X509.load_cert(cert_loc)
	ca_cert = X509.load_cert(ca_cert_loc)
	return cert.verify(ca_cert.get_pubkey())
    def test_singlehost_rename_old_certs(self):
        """Test repeated requests for the same host to make sure
        we aren't overwriting files.

        https://jira.opensciencegrid.org/browse/OSGPKI-137
        https://jira.opensciencegrid.org/browse/OSGPKI-139
        """
        hostname = 'test.' + DOMAIN
        initial_req = OIM()
        rc, _, _, msg = initial_req.gridadmin_request('--hostname', hostname)
        self.assertEqual(rc, 0, "Failed to request initial certificate\n%s" % msg)

        # Request another cert that will move the previous cert out of the way
        rc, stdout, _, msg = OIM().gridadmin_request('--hostname', hostname)
        self.assertEqual(rc, 0, "Failed to request second certificate\n%s" % msg)

        # Verify that the moved key/cert pair is the same as in the initial request
        try:
            # TODO: The format of the output is not text wrapped like it should be.
            # When that is fixed, the regex should be updated
            old_cert_path = re.search(r'Renaming existing file from.*to (.*)', stdout).group(1)
            old_key_path = re.search(r'Renaming existing key from.*to (.*)', stdout).group(1)
        except AttributeError:
            self.fail('Failed to move old cert or key\n' + msg)

        # Cert objects don't seem to handle equality checks well, compare the pem versions
        old_cert = X509.load_cert(old_cert_path).as_pem()
        self.assertEqual(initial_req.certs[0].as_pem(), old_cert,
                         'Renamed cert is not the same as the initial cert\n' + msg)
        # Need to grab pem formats without a cipher to compare keys
        old_key = RSA.load_key(old_key_path, OIM.simple_pass_callback)
        old_key_pem = old_key.as_pem(cipher=None, callback=OIM.simple_pass_callback)
        initial_key_pem = initial_req.keys[0].as_pem(cipher=None, callback=OIM.simple_pass_callback)
        self.assertEqual(initial_key_pem, old_key_pem,
                         'Renamed key is not the same as the initial key\n' + msg)
Exemple #19
0
def encrypt_block(blob, pubkey):
    """
    Encrypt the given blob of data, given the public key provided.

    :return The encrypted blob.
    """
    # Make a MemoryBuffer of the message.
    inbuf = BIO.MemoryBuffer(blob)

    # Seed the PRNG.
    Rand.rand_seed(os.urandom(1024))

    # Instantiate an SMIME object.
    s = SMIME.SMIME()

    # Load target cert to encrypt to.
    x509 = X509.load_cert(pubkey)
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Set cipher: AES 256 bit in CBC mode.
    s.set_cipher(SMIME.Cipher('aes_256_cbc'))

    # Encrypt the buffer.
    p7 = s.encrypt(inbuf)
    temp_buff = BIO.MemoryBuffer()
    s.write(temp_buff, p7)
    x = temp_buff.read()
    return x
Exemple #20
0
 def test_as_der(self):
     stack = X509.X509_Stack()
     cert = X509.load_cert("tests/x509.pem")
     issuer = X509.load_cert("tests/ca.pem")
     cert_subject1 = cert.get_subject()
     issuer_subject1 = issuer.get_subject()
     stack.push(cert)
     stack.push(issuer)
     der_seq = stack.as_der() 
     stack2 = X509.new_stack_from_der(der_seq)
     issuer_pop = stack2.pop() 
     cert_pop = stack2.pop() 
     cert_subject2 = cert_pop.get_subject() 
     issuer_subject2 = issuer.get_subject()
     assert str(cert_subject1) == str(cert_subject2)
     assert str(issuer_subject1) == str(issuer_subject2)
    def test_encrypt(self):
        buf = BIO.MemoryBuffer(self.cleartext)
        s = SMIME.SMIME()

        x509 = X509.load_cert('test/recipient.pem')
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        self.assertRaises(ValueError, SMIME.Cipher, 'nosuchcipher')

        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        p7 = s.encrypt(buf)
        
        assert len(buf) == 0
        assert p7.type() == SMIME.PKCS7_ENVELOPED, p7.type()
        assert isinstance(p7, SMIME.PKCS7), p7
        out = BIO.MemoryBuffer()
        p7.write(out)
    
        buf = out.read()
        
        assert buf[:len('-----BEGIN PKCS7-----')] == '-----BEGIN PKCS7-----'
        buf = buf.strip()
        assert buf[-len('-----END PKCS7-----'):] == '-----END PKCS7-----'
        assert len(buf) > len('-----END PKCS7-----') + len('-----BEGIN PKCS7-----')
        
        s.write(out, p7)
        return out
Exemple #22
0
 def test_save_der_string(self):
     x509 = X509.load_cert('tests/x509.pem')
     s = x509.as_der()
     f = open('tests/x509.der', 'rb')
     s2 = f.read()
     f.close()
     assert s == s2
Exemple #23
0
def store_certificate(certificate, bitcoin_address):
    # Load ACA cert and public key
    aca_cert = X509.load_cert(ACA_CERT)
    pk = RSA.importKey(aca_cert.get_pubkey().as_der())

    # Obtain the TBS certificate
    cert_hash = certificate_hashing(certificate)
    asn1_cert = decoder.decode(certificate, asn1Spec=Certificate())[0]

    # Extract the certificate signature
    signature_bin = asn1_cert.getComponentByName("signatureValue")

    # Parse the signature
    signature_str = ""
    for i in signature_bin:
        signature_str += str(i)
    signature = long(signature_str, 2)

    # Check the parsed signature matches with the signature of the obtained hash
    if pk.verify(cert_hash, [signature, 0]):
        utils_store_certificate(certificate, CS_CERTS_PATH + bitcoin_address, '.pem')
        response = "Certificate correctly stored"
    else:
        response = json.dumps({'data': "Bad certificate\n"}), 500

    return response
Exemple #24
0
def get_modulus_exponent_from_cert_and_pkey_pemfile(cert_path='/tmp/xmppwebid_cert.pem', 
        key_path='/tmp/xmppwebid_key.key'):
    """Get the modulus and exponent of RSA key from a PEM Certificate and
    key files
    m2.rsa_get_e(rsa.rsa) return something like '\x00\x00\x00\x03\x01\x00\x01'
    so to get the decimal value (65537), two crufty methods
    
    :param cert_path: certificate path
    :type cert_path: string
    :param key_path: key path
    :type key_path: string
    :return: tuple(modulus, exponent)
    :rtype: tuple (hex, int)

    .. TODO::
       replace the exponent method with something cleaner

    """
    cert=X509.load_cert(cert_path)
    pubkey = cert.get_pubkey()
    modulus = pubkey.get_modulus()
    
    pkey_rsa = RSA.load_key(key_path)
    e  = m2.rsa_get_e(pkey_rsa.rsa)
#    exponent = int(eval(repr(e[-3:]).replace('\\x', '')),16)
    exponent = int(''.join(["%2.2d" % ord(x) for x in e[-3:]]),16)
    
    return modulus, exponent
    def __init__(self, pub_key, priv_key, ca_cert, passphrase):
        """ Create a Certification Subject Object.

        Arguments:
            pub_key: file system path of the Subject's Public Key.
            priv_key: file system path of the Subject's Private Key (encrypted).
            ca_cert: file system path of the Certification Authority's Certificate.
            passphrase: Symmetric key for priv_key decryption.
        """
        def getPassphrase(*args):
            """ Callback for private key decrypting.
            """
            return str(passphrase.encode('utf-8'))

        self.pub_key = RSA.load_pub_key(pub_key.encode('utf-8'))
        self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase)
        self.ca_cert = X509.load_cert(ca_cert.decode('utf-8'))

        # Private key for signing
        self.signEVP = EVP.PKey()
        self.signEVP.assign_rsa(self.priv_key)

        # CA Key for validations
        self.verifyEVP = EVP.PKey()
        self.verifyEVP.assign_rsa(self.ca_cert.get_pubkey().get_rsa())
Exemple #26
0
 def test_with_incomplete_chain_file(self):
     test_cert = X509.load_cert(TEST_CERT)
     store = X509.X509_Store()
     self.assertEquals(store.load_info(SUB_CA), 1)
     store_ctx = X509.X509_Store_Context()
     store_ctx.init(store, test_cert)
     self.assertFalse(store_ctx.verify_cert())
def cert_fingerprint(cert_location):
	try:
		from M2Crypto import X509	
		cert = X509.load_cert(cert_location)
		return cert.get_fingerprint('sha1')
	except ImportError:
		return cert_fingerprint_via_openssl(cert_location)	
Exemple #28
0
def loadCert(name):
    """Load a cert and its private key and return them both."""
    p = name + ".pem"
    c = X509.load_cert(p)
    k = EVP.PKey()
    k.assign_rsa(RSA.load_key(p, callback=pwCb))
    return c, k
Exemple #29
0
def verify_pkcs7(pkcs7_sig, document):
    try:
        # raw_sig = pkcs7_sig
        raw_sig = str(pkcs7_sig).encode('ascii')
        msg = document

        sm_obj = SMIME.SMIME()
        x509 = X509.load_cert(os.path.join(config.APP_STATIC, 'AWSpubkey'))  # public key cert used by the remote
        # client when signing the message
        sk = X509.X509_Stack()
        sk.push(x509)
        sm_obj.set_x509_stack(sk)

        st = X509.X509_Store()
        st.load_info(os.path.join(config.APP_STATIC, 'AWSpubkey'))  # Public cert for the CA which signed
        # the above certificate
        sm_obj.set_x509_store(st)

        # re-wrap signature so that it fits base64 standards
        cooked_sig = '\n'.join(raw_sig[pos:pos + 76] for pos in xrange(0, len(raw_sig), 76))
        # cooked_sig = raw_sig
        # now, wrap the signature in a PKCS7 block
        sig = ("-----BEGIN PKCS7-----\n" + cooked_sig + "\n-----END PKCS7-----").encode('ascii')

        # and load it into an SMIME p7 object through the BIO I/O buffer:
        buf = BIO.MemoryBuffer(sig)
        p7 = SMIME.load_pkcs7_bio(buf)

        # finally, try to verify it:
        if dict(json.loads(sm_obj.verify(p7))) == dict(json.loads(msg)):
            return True
        else:
            return False
    except Exception as e:
        raise Exception("INVALID CLIENT MESSAGE SIGNATURE")
Exemple #30
0
 def test_with_single_chain_file(self):
     test_cert = X509.load_cert(TEST_CERT)
     store = X509.X509_Store()
     self.assertEquals(store.load_info(CA_CHAIN), 1)
     store_ctx = X509.X509_Store_Context()
     store_ctx.init(store, test_cert)
     self.assertTrue(store_ctx.verify_cert())
    def verify(self):

        # Instantiate an SMIME object.
        s = SMIME.SMIME()

        # Load the signer's cert.
        x509 = X509.load_cert(signer_cert)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        # Load the signer's CA cert.
        st = X509.X509_Store()
        st.load_info(ca_cert)
        s.set_x509_store(st)

        # Load the data, verify it.
        p7, data = SMIME.smime_load_pkcs7('smime-m2-sign.txt')
        v = s.verify(p7)

        print v
        print data
        print data.read()
Exemple #32
0
    def _createSignature(self, manifest, certificate, key,
                         wwdr_certificate, password):
        def passwordCallback(*args, **kwds):
            return password

        smime = SMIME.SMIME()
        # we need to attach wwdr cert as X509
        wwdrcert = X509.load_cert(wwdr_certificate)
        stack = X509_Stack()
        stack.push(wwdrcert)
        smime.set_x509_stack(stack)

        # need to cast to string since load_key doesnt work with unicode paths
        smime.load_key(str(key), certificate, callback=passwordCallback)
        pk7 = smime.sign(SMIME.BIO.MemoryBuffer(manifest.encode('utf8')), flags=SMIME.PKCS7_DETACHED | SMIME.PKCS7_BINARY)

        pem = SMIME.BIO.MemoryBuffer()
        pk7.write(pem)
        # convert pem to der

        der = b''.join(l.strip() for l in pem.read().split(b'-----')[2].splitlines())
        der = base64.b64decode(der)
        return der
def create_endpoints(sysinfo):
    """Find all the StorageEndpoints on this DPM
    and return an array of them"""
    cert_subject = None
    try:
        from M2Crypto import X509
        x509 = X509.load_cert(sysinfo.cert, X509.FORMAT_PEM)
        cert_subject = "/%s" % '/'.join(
            x509.get_issuer().as_text().split(', '))
    except:
        pass

    ret = []
    if 9000 in sysinfo.ports:
        ret.append(
            Endpoint("https", sysinfo.host, 9000, "", cert_subject,
                     *sysinfo.getprotinfo("https")))
    if 1094 in sysinfo.ports:
        ret.append(
            Endpoint("xroot", sysinfo.host, 1094, "/", cert_subject,
                     *sysinfo.getprotinfo("root")))

    return ret
Exemple #34
0
 def test_save(self):
     x509 = X509.load_cert('tests/x509.pem')
     f = open('tests/x509.pem', 'r')
     lTmp = f.readlines()
     #x509_pem = ''.join(lTmp[44:60]) # -----BEGIN CERTIFICATE----- : -----END CERTIFICATE-----
     x509_pem = ''.join(lTmp[lTmp.index('-----BEGIN CERTIFICATE-----\n'):(
         lTmp.index('-----END CERTIFICATE-----\n') + 1)])
     f.close()
     f = open('tests/x509.der', 'rb')
     x509_der = f.read()
     f.close()
     x509.save('tests/tmpcert.pem')
     f = open('tests/tmpcert.pem')
     s = f.read()
     f.close()
     self.assertEquals(s, x509_pem)
     os.remove('tests/tmpcert.pem')
     x509.save('tests/tmpcert.der', format=X509.FORMAT_DER)
     f = open('tests/tmpcert.der', 'rb')
     s = f.read()
     f.close()
     self.assertEquals(s, x509_der)
     os.remove('tests/tmpcert.der')
Exemple #35
0
    def _createSignature(self, manifest, certificate, key, wwdr_certificate,
                         password):
        def passwordCallback(*args, **kwds):
            return password

        smime = SMIME.SMIME()
        #we need to attach wwdr cert as X509
        wwdrcert = X509.load_cert(wwdr_certificate)
        stack = X509_Stack()
        stack.push(wwdrcert)
        smime.set_x509_stack(stack)

        smime.load_key(key, certificate, callback=passwordCallback)
        pk7 = smime.sign(SMIME.BIO.MemoryBuffer(manifest),
                         flags=SMIME.PKCS7_DETACHED | SMIME.PKCS7_BINARY)

        pem = SMIME.BIO.MemoryBuffer()
        pk7.write(pem)
        # convert pem to der
        der = ''.join(l.strip() for l in pem.read().split('-----')
                      [2].splitlines()).decode('base64')

        return der
Exemple #36
0
def mk_temporary_cert(cacert_file, ca_key_file, cn):
    """
	Create a temporary certificate signed by the given CA, and with the given common name.

	If cacert_file and ca_key_file is None, the certificate will be self-signed.

	Args:
	  cacert_file -- file containing the CA certificate
	  ca_key_file -- file containing the CA private key
	  cn -- desired common name
	Returns a namedtemporary file with the certificate and private key
	"""
    cert_req, pk2 = mk_request(1024, cn=cn)
    if cacert_file and ca_key_file:
        cacert = X509.load_cert(cacert_file)
        pk1 = EVP.load_key(ca_key_file)
    else:
        cacert = None
        pk1 = None

    cert = mk_cert()
    cert.set_subject(cert_req.get_subject())
    cert.set_pubkey(cert_req.get_pubkey())

    if cacert and pk1:
        cert.set_issuer(cacert.get_issuer())
        cert.sign(pk1, 'sha1')
    else:
        cert.set_issuer(cert.get_subject())
        cert.sign(pk2, 'sha1')

    certf = namedtmp()
    certf.write(cert.as_pem())
    certf.write(pk2.as_pem(None))
    certf.flush()

    return certf
Exemple #37
0
    def _aia(self):
        x509 = X509.load_cert(
            file=oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT,
            format=X509.FORMAT_PEM,
        )

        try:
            authorityInfoAccess = x509.get_ext(
                'authorityInfoAccess').get_value()

            self.logger.warning(_('AIA extension found in CA certificate'))
            self.dialog.note(text=_(
                'Please note:\n'
                'The certificate for the CA contains the\n'
                '"Authority Information Access" extension pointing\n'
                'to the old hostname:\n'
                '{aia}'
                'Currently this is harmless, but it might affect future\n'
                'upgrades. In version 3.3 the default was changed to\n'
                'create new CA certificate without this extension. If\n'
                'possible, it might be better to not rely on this\n'
                'program, and instead backup, cleanup and setup again\n'
                'cleanly.\n'
                '\n'
                'More details can be found at the following address:\n'
                'http://www.ovirt.org/Changing_Engine_Hostname\n').format(
                    aia=authorityInfoAccess, ), )
            if not dialog.queryBoolean(
                    dialog=self.dialog,
                    name='OVESETUP_RENAME_AIA_BYPASS',
                    note=_(
                        'Do you want to continue? (@VALUES@) [@DEFAULT@]: '),
                    prompt=True,
            ):
                raise RuntimeError(_('Aborted by user'))
        except LookupError:
            pass
Exemple #38
0
def verify(client: Client, args: Dict):
    """ Verify the signature

    Args:
        client: Client
        args: Dict

    """
    signed_message = demisto.getFilePath(args.get('signed_message'))

    x509 = X509.load_cert(client.public_key_file)
    sk = X509.X509_Stack()
    sk.push(x509)
    client.smime.set_x509_stack(sk)

    st = X509.X509_Store()
    st.load_info(client.public_key_file)
    client.smime.set_x509_store(st)

    p7, data = SMIME.smime_load_pkcs7(signed_message['path'])
    v = client.smime.verify(p7, data, flags=SMIME.PKCS7_NOVERIFY)

    human_readable = f'The signature verified\n\n{v}'
    return human_readable, {}
Exemple #39
0
def encrypt_email_body(client: Client, args: Dict):
    """ generate an S/MIME-encrypted message

    Args:
        client: Client
        args: Dict

    """
    message_body = args.get('message', '').encode('utf-8')

    buf = makebuf(message_body)

    x509 = X509.load_cert(client.public_key_file)
    sk = X509.X509_Stack()
    sk.push(x509)
    client.smime.set_x509_stack(sk)

    client.smime.set_cipher(SMIME.Cipher('des_ede3_cbc'))

    p7 = client.smime.encrypt(buf)

    out = BIO.MemoryBuffer()

    client.smime.write(out, p7)
    encrypted_message = out.read().decode('utf-8')
    message = encrypted_message.split('\n\n')
    headers = message[0]
    new_headers = headers.replace(': ', '=').replace('\n', ',')

    entry_context = {
        'SMIME.Encrypted': {
            'Message': encrypted_message,
            'Headers': new_headers
        }
    }
    return encrypted_message, entry_context
Exemple #40
0
def verify_s(cert_list, signature, data):
    """returns the subject of the first certificate in <cert_list> that makes the
    <signature> match the SHA hash of the data.
    If no certificate does it, return None"""

    #signature = unhexlify(hexlify(signature))
    #data = unhexlify(hexlify(data))
    cert_extension = ".crt"
    cert_dir = './certificates/'
    certs = [ cert_dir + x for x in os.listdir(cert_dir) if len(x) > 4 and x[-len(cert_extension):] == cert_extension ]
    for cert_file in certs:
        try:
            cert = X509.load_cert(cert_file)
            pub_k = cert.get_pubkey()
            pub_k.verify_init()
            if pub_k.verify_update(data) != 1:
                raise Exception("error verify update")
            if pub_k.verify_final(signature) == 1:
                sub = cert.get_subject()
                return str(sub) # there is an hidden free() when using the
                    # return value outside this function: str() forces the copy
        except BaseException as e:
            print str(e)
    return None
Exemple #41
0
    def updateVdcOptions(
        self,
        options,
    ):
        for option in options:
            value = option['value']

            if option.get('encrypt', False):
                x509 = X509.load_cert(
                    file=(
                        osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CERT),
                    format=X509.FORMAT_PEM,
                )
                value = base64.b64encode(
                    x509.get_pubkey().get_rsa().public_encrypt(
                        data=value,
                        padding=RSA.pkcs1_padding,
                    ), )

            if isinstance(value, bool):
                value = 'true' if value else 'false'

            self.execute(
                statement="""
                    update vdc_options
                    set
                        option_value=%(value)s,
                        version=%(version)s
                    where option_name=%(name)s
                """,
                args=dict(
                    name=option['name'],
                    value=value,
                    version=option.get('version', 'general'),
                ),
            )
Exemple #42
0
    def test_save(self):
        x509 = X509.load_cert('tests/x509.pem')
        with open('tests/x509.pem', 'r') as f:
            l_tmp = f.readlines()
            # -----BEGIN CERTIFICATE----- : -----END CERTIFICATE-----
            beg_idx = l_tmp.index('-----BEGIN CERTIFICATE-----\n')
            end_idx = l_tmp.index('-----END CERTIFICATE-----\n')
            x509_pem = ''.join(l_tmp[beg_idx:end_idx + 1])

        with open('tests/x509.der', 'rb') as f:
            x509_der = f.read()

        x509.save('tests/tmpcert.pem')
        with open('tests/tmpcert.pem') as f:
            s = f.read()

        self.assertEqual(s, x509_pem)
        os.remove('tests/tmpcert.pem')
        x509.save('tests/tmpcert.der', format=X509.FORMAT_DER)
        with open('tests/tmpcert.der', 'rb') as f:
            s = f.read()

        self.assertEqual(s, x509_der)
        os.remove('tests/tmpcert.der')
    def encrypt(self):

        # Make a MemoryBuffer of the message.
        buf = makebuf('a sign of our times')

        # Seed the PRNG.
        Rand.load_file(randpool, -1)

        # Instantiate an SMIME object.
        s = SMIME.SMIME()

        # Load target cert to encrypt to.
        x509 = X509.load_cert(recipient_cert)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        # Set cipher: 3-key triple-DES in CBC mode.
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

        # Encrypt the buffer.
        p7 = s.encrypt(buf)

        # Output p7 in mail-friendly format.
        out = BIO.MemoryBuffer()
        out.write('From: [email protected]\n')
        out.write('To: [email protected]\n')
        out.write('Subject: M2Crypto S/MIME testing\n')
        s.write(out, p7)

        result = out.read()

        # Save the PRNG's state.
        Rand.save_file(randpool)

        open('smime-m2-encrypt.txt', 'wt').write(result)
Exemple #44
0
 def test_fingerprint(self):
     x509 = X509.load_cert('tests/x509.pem')
     fp = x509.get_fingerprint('sha1')
     self.assertEqual(fp, self.expected_hash)
Exemple #45
0
def makebuf(text):
    return BIO.MemoryBuffer(bytes(text, 'utf-8'))


# Make a MemoryBuffer of the message.
buf = makebuf(message)

# Seed the PRNG.
Rand.load_file('randpool.dat', -1)

# Instantiate an SMIME object.
s = SMIME.SMIME()

# Load target cert to encrypt to.
x509 = X509.load_cert('sample_keys/recipient.pem')
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

# Set cipher: 3-key triple-DES in CBC mode.
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

# Encrypt the buffer.
p7 = s.encrypt(buf)

# Output p7 in mail-friendly format.
out = BIO.MemoryBuffer()
out.write('From: [email protected]\n')
out.write('To: [email protected]\n')
out.write('Subject: M2Crypto S/MIME testing\n')
# Need to reconstruct a Mail message with content type
# as SMIME wants it in that format
bio = BIO.MemoryBuffer("Content-Type: ")
bio.write(contentType)
bio.write("\r\n\r\n")
bio.write(data)

s = SMIME.SMIME()
s.load_key('src/main/resources/private.pem', 'src/main/resources/cert.pem')

p7, d = SMIME.smime_load_pkcs7_bio(bio)
out = s.decrypt(p7)

# Load the signer's cert.
x509 = X509.load_cert('src/main/resources/cert.pem')
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

# Load the signer's CA cert. In this case, because the signer's
# cert is self-signed, it is the signer's cert itself.
st = X509.X509_Store()
st.load_info('src/main/resources/cert.pem')
s.set_x509_store(st)

# Recall 'out' contains a PKCS #7 blob.
# Transform 'out'; verify the resulting PKCS #7 blob.
p7_bio = BIO.MemoryBuffer(out)
p7, data = SMIME.smime_load_pkcs7_bio(p7_bio)
v = s.verify(p7, data)
Exemple #47
0
 def __init__(self, ca, eku, peer=None):
     self._eku = eku
     if peer is not None:
         self._peer = X509.load_cert_string(peer)
     if ca is not None:
         self._ca = X509.load_cert(ca)
Exemple #48
0
 def test_x509_public_encrypt(self):
     x509 = X509.load_cert("tests/recipient.pem")
     rsa = x509.get_pubkey().get_rsa()
     rsa.public_encrypt(b"data", RSA.pkcs1_padding)
Exemple #49
0
from M2Crypto import SMIME, X509

# Instantiate an SMIME object.
s = SMIME.SMIME()

# Load the signer's cert.
x509 = X509.load_cert('signer.pem')
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

# Load the signer's CA cert. In this case, because the signer's
# cert is self-signed, it is the signer's cert itself.
st = X509.X509_Store()
st.load_info('signer.pem')
s.set_x509_store(st)

# Load the data, verify it.
p7, data = SMIME.smime_load_pkcs7('sign.p7')
'''
v = s.verify(p7,data)
print v
print data
print data.read()
'''
Exemple #50
0
    def generate_manifest(self,
                          path,
                          prefix,
                          parts,
                          parts_digest,
                          file,
                          key,
                          iv,
                          cert_path,
                          ec2cert_path,
                          private_key_path,
                          target_arch,
                          image_size,
                          bundled_size,
                          image_digest,
                          user,
                          kernel,
                          ramdisk,
                          mapping=None,
                          product_codes=None,
                          ancestor_ami_ids=None):
        user_pub_key = X509.load_cert(cert_path).get_pubkey().get_rsa()
        cloud_pub_key = \
            X509.load_cert(ec2cert_path).get_pubkey().get_rsa()

        user_encrypted_key = hexlify(
            user_pub_key.public_encrypt(key, RSA.pkcs1_padding))
        user_encrypted_iv = hexlify(
            user_pub_key.public_encrypt(iv, RSA.pkcs1_padding))

        cloud_encrypted_key = hexlify(
            cloud_pub_key.public_encrypt(key, RSA.pkcs1_padding))
        cloud_encrypted_iv = hexlify(
            cloud_pub_key.public_encrypt(iv, RSA.pkcs1_padding))

        user_priv_key = None
        if private_key_path:
            user_priv_key = RSA.load_key(private_key_path)

        manifest_file = '%s.manifest.xml' % os.path.join(path, prefix)
        if self.euca.debug:
            print 'Manifest: ', manifest_file

        print 'Generating manifest %s' % manifest_file

        manifest_out_file = open(manifest_file, 'wb')
        doc = Document()

        manifest_elem = doc.createElement('manifest')
        doc.appendChild(manifest_elem)

        # version

        version_elem = doc.createElement('version')
        version_value = doc.createTextNode(VERSION)
        version_elem.appendChild(version_value)
        manifest_elem.appendChild(version_elem)

        # bundler info

        bundler_elem = doc.createElement('bundler')
        bundler_name_elem = doc.createElement('name')
        bundler_name_value = doc.createTextNode(BUNDLER_NAME)
        bundler_name_elem.appendChild(bundler_name_value)
        bundler_version_elem = doc.createElement('version')
        bundler_version_value = doc.createTextNode(BUNDLER_VERSION)
        bundler_version_elem.appendChild(bundler_version_value)
        bundler_elem.appendChild(bundler_name_elem)
        bundler_elem.appendChild(bundler_version_elem)

        # release

        release_elem = doc.createElement('release')
        release_value = doc.createTextNode(RELEASE)
        release_elem.appendChild(release_value)
        bundler_elem.appendChild(release_elem)
        manifest_elem.appendChild(bundler_elem)

        # machine config

        machine_config_elem = doc.createElement('machine_configuration')
        manifest_elem.appendChild(machine_config_elem)

        target_arch_elem = doc.createElement('architecture')
        target_arch_value = doc.createTextNode(target_arch)
        target_arch_elem.appendChild(target_arch_value)
        machine_config_elem.appendChild(target_arch_elem)

        # block device mapping

        if mapping:
            block_dev_mapping_elem = \
                doc.createElement('block_device_mapping')
            for vname, dname in mapping.items():
                mapping_elem = doc.createElement('mapping')
                virtual_elem = doc.createElement('virtual')
                virtual_value = doc.createTextNode(vname)
                virtual_elem.appendChild(virtual_value)
                mapping_elem.appendChild(virtual_elem)
                device_elem = doc.createElement('device')
                device_value = doc.createTextNode(dname)
                device_elem.appendChild(device_value)
                mapping_elem.appendChild(device_elem)
                block_dev_mapping_elem.appendChild(mapping_elem)
            machine_config_elem.appendChild(block_dev_mapping_elem)

        if product_codes:
            product_codes_elem = doc.createElement('product_codes')
            for product_code in product_codes:
                product_code_elem = doc.createElement('product_code')
                product_code_value = doc.createTextNode(product_code)
                product_code_elem.appendChild(product_code_value)
                product_codes_elem.appendChild(product_code_elem)
            machine_config_elem.appendChild(product_codes_elem)

        # kernel and ramdisk

        if kernel:
            kernel_id_elem = doc.createElement('kernel_id')
            kernel_id_value = doc.createTextNode(kernel)
            kernel_id_elem.appendChild(kernel_id_value)
            machine_config_elem.appendChild(kernel_id_elem)

        if ramdisk:
            ramdisk_id_elem = doc.createElement('ramdisk_id')
            ramdisk_id_value = doc.createTextNode(ramdisk)
            ramdisk_id_elem.appendChild(ramdisk_id_value)
            machine_config_elem.appendChild(ramdisk_id_elem)

        image_elem = doc.createElement('image')
        manifest_elem.appendChild(image_elem)

        # name

        image_name_elem = doc.createElement('name')
        image_name_value = \
            doc.createTextNode(self.euca.get_relative_filename(file))
        image_name_elem.appendChild(image_name_value)
        image_elem.appendChild(image_name_elem)

        # user

        user_elem = doc.createElement('user')
        user_value = doc.createTextNode('%s' % user)
        user_elem.appendChild(user_value)
        image_elem.appendChild(user_elem)

        # type
        # TODO: fixme

        image_type_elem = doc.createElement('type')
        image_type_value = doc.createTextNode('machine')
        image_type_elem.appendChild(image_type_value)
        image_elem.appendChild(image_type_elem)

        # ancestor ami ids

        if ancestor_ami_ids:
            ancestry_elem = doc.createElement('ancestry')
            for ancestor_ami_id in ancestor_ami_ids:
                ancestor_id_elem = doc.createElement('ancestor_ami_id')
                ancestor_id_value = doc.createTextNode(ancestor_ami_id)
                ancestor_id_elem.appendChild(ancestor_id_value)
                ancestry_elem.appendChild(ancestor_id_elem)
            image_elem.appendChild(ancestry_elem)

        # digest

        image_digest_elem = doc.createElement('digest')
        image_digest_elem.setAttribute('algorithm', 'SHA1')
        image_digest_value = doc.createTextNode('%s' % image_digest)
        image_digest_elem.appendChild(image_digest_value)
        image_elem.appendChild(image_digest_elem)

        # size

        image_size_elem = doc.createElement('size')
        image_size_value = doc.createTextNode('%s' % image_size)
        image_size_elem.appendChild(image_size_value)
        image_elem.appendChild(image_size_elem)

        # bundled size

        bundled_size_elem = doc.createElement('bundled_size')
        bundled_size_value = doc.createTextNode('%s' % bundled_size)
        bundled_size_elem.appendChild(bundled_size_value)
        image_elem.appendChild(bundled_size_elem)

        # key, iv

        cloud_encrypted_key_elem = doc.createElement('ec2_encrypted_key')
        cloud_encrypted_key_value = doc.createTextNode('%s' %
                                                       cloud_encrypted_key)
        cloud_encrypted_key_elem.appendChild(cloud_encrypted_key_value)
        cloud_encrypted_key_elem.setAttribute('algorithm', AES)
        image_elem.appendChild(cloud_encrypted_key_elem)

        user_encrypted_key_elem = doc.createElement('user_encrypted_key')
        user_encrypted_key_value = doc.createTextNode('%s' %
                                                      user_encrypted_key)
        user_encrypted_key_elem.appendChild(user_encrypted_key_value)
        user_encrypted_key_elem.setAttribute('algorithm', AES)
        image_elem.appendChild(user_encrypted_key_elem)

        cloud_encrypted_iv_elem = doc.createElement('ec2_encrypted_iv')
        cloud_encrypted_iv_value = doc.createTextNode('%s' %
                                                      cloud_encrypted_iv)
        cloud_encrypted_iv_elem.appendChild(cloud_encrypted_iv_value)
        image_elem.appendChild(cloud_encrypted_iv_elem)

        user_encrypted_iv_elem = doc.createElement('user_encrypted_iv')
        user_encrypted_iv_value = doc.createTextNode('%s' % user_encrypted_iv)
        user_encrypted_iv_elem.appendChild(user_encrypted_iv_value)
        image_elem.appendChild(user_encrypted_iv_elem)

        # parts

        parts_elem = doc.createElement('parts')
        parts_elem.setAttribute('count', '%s' % len(parts))
        part_number = 0
        for part in parts:
            part_elem = doc.createElement('part')
            filename_elem = doc.createElement('filename')
            filename_value = \
                doc.createTextNode(self.euca.get_relative_filename(part))
            filename_elem.appendChild(filename_value)
            part_elem.appendChild(filename_elem)

            # digest

            part_digest_elem = doc.createElement('digest')
            part_digest_elem.setAttribute('algorithm', 'SHA1')
            part_digest_value = \
                doc.createTextNode(parts_digest[part_number])
            part_digest_elem.appendChild(part_digest_value)
            part_elem.appendChild(part_digest_elem)
            part_elem.setAttribute('index', '%s' % part_number)
            parts_elem.appendChild(part_elem)
            part_number += 1
        image_elem.appendChild(parts_elem)

        manifest_string = doc.toxml()

        if user_priv_key:
            string_to_sign = self.get_verification_string(manifest_string)
            signature_elem = doc.createElement('signature')
            sha_manifest = sha()
            sha_manifest.update(string_to_sign)
            signature_value = doc.createTextNode(
                '%s' % hexlify(user_priv_key.sign(sha_manifest.digest())))
            signature_elem.appendChild(signature_value)
            manifest_elem.appendChild(signature_elem)

        manifest_out_file.write(doc.toxml())
        manifest_out_file.close()
        return manifest_file
Exemple #51
0
    else:
        cert.set_issuer(cert.get_subject())
        cert.sign(pk2, 'sha1')

    certf = namedtmp()
    certf.write(cert.as_pem())
    certf.write(pk2.as_pem(None))
    certf.flush()

    return certf


if __name__ == '__main__':
    cacert, cert, pk = mk_casigned_cert()
    with open('cacert.crt', 'w') as f:
        f.write(cacert.as_pem())
    with open('cert.crt', 'w') as f:
        f.write(cert.as_pem())
        f.write(pk.as_pem(None))

    # Sanity checks...
    cac = X509.load_cert('cacert.crt')
    print cac.verify(), cac.check_ca()
    cc = X509.load_cert('cert.crt')
    print cc.verify(cac.get_pubkey())

# protips
# openssl verify -CAfile cacert.crt cacert.crt cert.crt
# openssl x509 -in cert.crt -noout -text
# openssl x509 -in cacert.crt -noout -text
 def load_ca_cert_file(self, ca_cert_file):
     """
     Load a CA cert from a PEM file, replacing any previous cert.
     """
     cert = X509.load_cert(ca_cert_file)
     self._load_cert(cert)
Exemple #53
0
def auth(username, password, **kwargs):
    """
    Returns True if the given user cert (password is the cert contents)
    was issued by the CA and if cert's Common Name is equal to username.

    Returns False otherwise.

    ``username``: we need it to run the auth function from CLI/API;
                  it should be in master config auth/acl
    ``password``: contents of user certificate (pem-encoded user public key);
                  why "password"? For CLI, it's the only available name

    Configure the CA cert in the master config file:

    .. code-block:: yaml

        external_auth:
          pki:
            ca_file: /etc/pki/tls/ca_certs/trusted-ca.crt
            your_user:
              - .*
    """
    pem = password
    cacert_file = __salt__["config.get"]("external_auth:pki:ca_file")

    log.debug("Attempting to authenticate via pki.")
    log.debug("Using CA file: %s", cacert_file)
    log.debug("Certificate contents: %s", pem)

    if HAS_M2:
        cert = X509.load_cert_string(pem, X509.FORMAT_PEM)
        cacert = X509.load_cert(cacert_file, X509.FORMAT_PEM)
        if cert.verify(cacert.get_pubkey()):
            log.info("Successfully authenticated certificate: %s", pem)
            return True
        else:
            log.info("Failed to authenticate certificate: %s", pem)
            return False

    c = OpenSSL.crypto
    cert = c.load_certificate(c.FILETYPE_PEM, pem)

    with salt.utils.files.fopen(cacert_file) as f:
        cacert = c.load_certificate(c.FILETYPE_PEM, f.read())

    # Get the signing algorithm
    algo = cert.get_signature_algorithm()

    # Get the ASN1 format of the certificate
    cert_asn1 = c.dump_certificate(c.FILETYPE_ASN1, cert)

    # Decode the certificate
    der = asn1.DerSequence()
    der.decode(cert_asn1)

    # The certificate has three parts:
    # - certificate
    # - signature algorithm
    # - signature
    # http://usefulfor.com/nothing/2009/06/10/x509-certificate-basics/
    der_cert = der[0]
    # der_algo = der[1]
    der_sig = der[2]

    # The signature is a BIT STRING (Type 3)
    # Decode that as well
    der_sig_in = asn1.DerObject()
    der_sig_in.decode(der_sig)

    # Get the payload
    sig0 = der_sig_in.payload

    # Do the following to see a validation error for tests
    # der_cert=der_cert[:20]+'1'+der_cert[21:]

    # First byte is the number of unused bits. This should be 0
    # http://msdn.microsoft.com/en-us/library/windows/desktop/bb540792(v=vs.85).aspx
    if sig0[0] != "\x00":
        raise Exception("Number of unused bits is strange")
    # Now get the signature itself
    sig = sig0[1:]

    # And verify the certificate
    try:
        c.verify(cacert, sig, der_cert, algo)
        assert (dict(cert.get_subject().get_components())["CN"] == username
                ), "Certificate's CN should match the username"
        log.info("Successfully authenticated certificate: %s", pem)
        return True
    except (OpenSSL.crypto.Error, AssertionError):
        log.info("Failed to authenticate certificate: %s", pem)
    return False
 def test_fingerprint(self):
     x509 = X509.load_cert('tests/x509.pem')
     fp = x509.get_fingerprint('sha1')
     expected = 'B2522F9B4F6F2461475D0C6267911537E738494F'
     self.assertEqual(fp, expected)
Exemple #55
0
 def test_date_after_2050_working(self):
     cert = X509.load_cert('tests/bad_date_cert.crt')
     self.assertEqual(str(cert.get_not_after()), 'Feb  9 14:57:46 2116 GMT')
Exemple #56
0
 def __init__(self, cert, key, lifetime=5):
     self._lifetime = lifetime
     self._x509 = X509.load_cert(cert)
     self._pkey = EVP.load_key(key)
Exemple #57
0
 def crt(self):
     if self._crt is None:
         self._crt = X509.load_cert(self._public_cert_filename)
     return self._crt
Exemple #58
0
    def updateVdcOptions(
        self,
        options,
        ownConnection=False,
    ):
        for option in options:
            name = option['name']
            value = option['value']
            version = option.get('version', 'general')

            if option.get('encrypt', False):
                x509 = X509.load_cert(
                    file=(oenginecons.FileLocations.
                          OVIRT_ENGINE_PKI_ENGINE_CERT),
                    format=X509.FORMAT_PEM,
                )
                value = base64.b64encode(
                    x509.get_pubkey().get_rsa().public_encrypt(
                        data=value,
                        padding=RSA.pkcs1_padding,
                    ), )

            if isinstance(value, bool):
                value = 'true' if value else 'false'

            res = self._statement.execute(
                statement="""
                    select count(*) as count
                    from vdc_options
                    where
                        option_name=%(name)s and
                        version=%(version)s
                """,
                args=dict(
                    name=name,
                    version=version,
                ),
                ownConnection=ownConnection,
            )
            if res[0]['count'] == 0:
                self._statement.execute(
                    statement="""
                        insert into vdc_options (
                            option_name,
                            option_value,
                            version
                        )
                        values (
                            %(name)s,
                            %(value)s,
                            %(version)s
                        )
                    """,
                    args=dict(
                        name=name,
                        version=version,
                        value=value,
                    ),
                    ownConnection=ownConnection,
                )
            else:
                self._statement.execute(
                    statement="""
                        update vdc_options
                        set
                            option_value=%(value)s
                        where
                            option_name=%(name)s and
                            version=%(version)s
                    """,
                    args=dict(
                        name=name,
                        version=version,
                        value=value,
                    ),
                    ownConnection=ownConnection,
                )
Exemple #59
0
def generate_json(f_name, share_code, mailid, phone_no):

    import xml
    import xml.etree.cElementTree as etree
    from xml.etree import ElementTree
    from base64 import b64encode, b64decode
    from zipfile import ZipFile
    import os
    from glob import glob
    import sys
    import hashlib
    from M2Crypto import BIO, RSA, EVP
    from M2Crypto import X509

    #with ZipFile('Offlineaadhaar.zip') as zf:
    #    zf.extractall(path='xml_folder/',pwd=share_code.encode())

    try:
        zipdata = ZipFile('uploads/' + f_name)
    except:
        return {"Wrong zip file": 422}

    zipinfos = zipdata.infolist()

    for zipinfo in zipinfos:
        zipinfo.filename = f_name.split('.')[0] + '.xml'
        try:
            zipdata.extract(zipinfo, path='uploads/', pwd=share_code.encode())
        except RuntimeError:
            return {"Bad sharecode or Zipfile Given": 422}
    #import os
    #from glob import glob
    #PATH = "uploads/"
    #EXT = "*.xml"
    #xml_path = glob(os.path.join(PATH, EXT))[0]
    import time
    import datetime

    import sys

    #print(xml_path, file=sys.stderr)
    #print(xml_path, file=sys.stdout)
    #print(xml_path)
    xml_path = 'uploads/' + f_name.split('.')[0] + '.xml'
    xmlDoc = open(xml_path, 'r').read()
    Tr = etree.XML(xmlDoc)

    Tr.keys()

    # Attribute
    #
    # * Normal  - n(Name), g(Gender), a(Address), d(Date of birth), r(aadhar + timestamp), v(XML version)
    # * Encrypt - e(Email), m(Mobile no), s(Signeture), i(Image)

    json_dict = dict()
    personal_data = dict()

    # ### Name

    Tr.get('n')
    personal_data['name'] = Tr.get('n')

    # ### Gender
    Tr.get('g')

    personal_data['gender'] = Tr.get('g')

    # ### Date of birth

    s = Tr.get('d')

    import time
    import datetime
    dob = datetime.datetime.strptime(s, "%d%m%Y").strftime('%d/%m/%Y')

    personal_data['dob'] = dob

    # ### Address

    Tr.get('a')
    personal_data['address'] = Tr.get('a')

    # ### Image

    imagestr = Tr.get('i')
    imagestr = bytes(imagestr, 'utf-8')
    personal_data['image'] = Tr.get('i')

    json_dict['personal_data'] = personal_data

    # ### Last 4 digit Aadhar

    last_4_digit = Tr.get('r')[:4]
    last_4_digit
    json_dict['Aadhaar_last_4digit'] = 'XXXX-XXXX-' + last_4_digit

    import time
    ts = time.time()
    import datetime
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    #print(st)

    json_dict['timestamp'] = st

    validation_dic = dict()

    # ### Email
    #
    # Logic - Sha256(Sha256(Email+SharePhrase))*number of times last digit of Aadhaar number

    import hashlib
    import sys

    def Secure(value, sharecode, laadhar, string):

        value = value + sharecode
        if laadhar == 0:
            laadhar = 1

        for x in range(0, laadhar):
            value = hashlib.sha256(value.encode('utf-8')).hexdigest()

        if string == value:
            return "Valid"
        else:
            return "Invalid"

    mailstr = Tr.get('e')

    is_valid_mail = Secure(mailid, str(share_code), int(last_4_digit[-1]),
                           mailstr)
    validation_dic['email'] = is_valid_mail
    mobile_str = Tr.get('m')

    is_valid_phone = Secure(phone_no, str(share_code), int(last_4_digit[-1]),
                            mobile_str)
    validation_dic['phone'] = is_valid_phone

    # Digital Signature Validation

    from M2Crypto import BIO, RSA, EVP
    from M2Crypto import X509

    x509 = X509.load_cert('certificate/ekyc_public_key.cer')
    rsa = x509.get_pubkey().get_rsa()
    pubkey = EVP.PKey()
    pubkey.assign_rsa(rsa)

    import lxml.etree as le

    with open(xml_path, 'r') as f:
        doc = le.parse(f)
        for elem in doc.xpath('//*[attribute::s]'):
            sign = elem.attrib['s']
            elem.attrib.pop('s')

    data_str = str(le.tostring(doc))[2:][:-1]
    data = data_str[:-2] + ' />'

    pubkey.reset_context(md='sha256')
    pubkey.verify_init()

    pubkey.verify_update(data.encode())

    is_valid_signeture = ""
    if (pubkey.verify_final(b64decode(sign)) != 1):
        #print('Digital Signeture not validated')
        is_valid_signeture = 'Invalid'
    else:
        #print('Digital Signeture validated')
        is_valid_signeture = 'Valid'

    validation_dic['digital_signeture'] = is_valid_signeture

    validation_dic['status'] = 'y'
    validation_dic['Description'] = 'Authenticated Successfully'

    if (is_valid_mail == 'Invalid' or is_valid_phone == 'Invalid'
            or is_valid_signeture == 'Invalid'):
        validation_dic['status'] = 'n'
        validation_dic['Description'] = 'Authentication Failed'

    json_dict['validation'] = validation_dic

    import json
    json_data = json.dumps(json_dict)

    return json_dict
Exemple #60
0
        def _response_body(self, resource, request, response):
            from pyspkac.spkac import SPKAC
            from M2Crypto import EVP, X509
            top = resource.top
            HTTP_Status = top.Status
            ca_path = top.cert_auth_path
            if not ca_path:
                raise HTTP_Status.Not_Found()
            try:
                ### Unicode argument to `EVP.load_key` fails [M2Crypto==0.21.1]
                cert = X509.load_cert(Filename(".crt", ca_path).name)
                pkey = EVP.load_key(str(Filename(".key", ca_path).name))
            except Exception:
                raise HTTP_Status.Not_Found()
            req_data = request.req_data
            spkac = req_data.get("SPKAC", "").replace("\n", "")
            if not spkac:
                exc = HTTP_Status.Bad_Request \
                    ( _T( "The parameter `SPKAC` is missing from the request. "
                          "Normally, the web browser should supply that "
                          "parameter automatically."
                        )

                    )
                resource.send_error_email(request, exc)
                raise exc
            challenge = request.session.get("spkac_challenge")
            desc = req_data.get("desc")
            email = request.user.name
            cn = "%s [%s]" % (email, desc) if desc else email
            ### Unicode arguments to `X509.new_email` fail [M2Crypto==0.21.1]
            X = X509.new_extension
            x1 = X(b"basicConstraints", b"CA:FALSE", critical=True)
            x2 = X \
                ( b"keyUsage"
                , b"digitalSignature, keyEncipherment, keyAgreement"
                , critical = True
                )
            x3 = X(b"extendedKeyUsage", b"clientAuth, emailProtection, nsSGC")
            s  = SPKAC \
                ( spkac, challenge, x1, x2, x3
                , CN     = cn
                , Email  = email
                , O      = cert.get_subject ().O
                )
            scope = top.scope
            CTM = scope.Auth.Certificate
            start = CTM.E_Type.validity.start.now()
            finis = start + datetime.timedelta(days=365 * 2)
            c_obj = CTM(email=email, validity=(start, finis), desc=desc)
            scope.commit()
            result = c_obj.pem = s.gen_crt \
                ( pkey, cert, c_obj.pid
                , not_before = self._timestamp (start)
                , not_after  = self._timestamp (finis)
                ).as_pem ()
            response.set_header \
                ( "content-disposition", "inline"
                , filename = "%s.crt" % (email, )
                )
            scope.commit()
            return result