예제 #1
0
파일: options.py 프로젝트: m00dy/controller
 def sign_request(self, request, ca=False):
     if not isinstance(request, X509.Request):
         request = X509.load_request_string(str(request))
     ca_priv_evp = EVP.PKey()
     ca_priv_evp.assign_rsa(self.get_key())
     cert = X509.X509()
     cert.set_version(3)
     # Set Serial number
     serial = random.randrange(1, sys.maxint)
     cert.set_serial_number(serial)
     # Set Cert validity time
     cur_time = ASN1.ASN1_UTCTIME()
     cur_time.set_time(int(time.time()))
     expire_time = ASN1.ASN1_UTCTIME()
     expire_time.set_time(int(time.time()) + self.cert_exp_days*24*60*60)
     cert.set_not_before(cur_time)
     cert.set_not_after(expire_time)
     
     if ca:
         cert.set_issuer_name(request.get_subject())
         cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE'))
     else:
         ca_cert = self.get_cert()
         cert.set_issuer_name(ca_cert.get_subject())
     
     cert.set_subject(request.get_subject())
     cert.set_pubkey(request.get_pubkey())
     cert.sign(ca_priv_evp, md="sha256")
     return cert
예제 #2
0
    def _get_signing_request(self, der_blob):
        """ Extracts signing request from 
            MyProxy response. 
            
            der_blob --  sequence with PKCS10 encoded CSR string

            raise --  MyProxyError if no CSR could be extracted
        """
        ind = der_blob.find(MyProxy.ASN1_START)
        if ind < 0:
            raise MyProxyError("CSR missing", 
                "Could not extract any CSR from ASN1 sequence")
        _len = 256*ord(der_blob[ind+2]) + ord(der_blob[ind+3])

        c = der_blob[ind:ind+_len+4] # get CSR 
        
        if version.LooseVersion(m2_version) < '0.20': 
            # little hack to overcome missing method in versions < 0.20
            import tempfile
            tmp_fd, tmp_name = tempfile.mkstemp(suffix='.csr')
            f = os.fdopen(tmp_fd,'wb')
            f.write(c)
            f.close()
            req = X509.load_request(tmp_name, X509.FORMAT_DER)
            os.remove(tmp_name)
        else: 
            req = X509.load_request_der_string(c)
        return req
예제 #3
0
파일: pki.py 프로젝트: halober/ovirt-engine
    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,
                )
            )
예제 #4
0
파일: auth.py 프로젝트: bibstha/s2-appcert
def createCertM2():
    #set validity period of certificate here
    cur_time = ASN1.ASN1_UTCTIME()
    cur_time.set_time(int(time.time()) - 60*60*24)

    expire_time = ASN1.ASN1_UTCTIME()
    # Expire certs in 1 hour.
    expire_time.set_time(int(time.time()) + 60 * 60 * 24)
    
    
    
    cs_cert = X509.X509()
    cs_cert.set_not_before(cur_time)
    cs_cert.set_not_after(expire_time)
    #subject name details
    cs_name=X509.X509_Name()
    cs_name.C = "DE"
    cs_name.ST = "Munich"
    cs_name.L = "Munich"
    cs_name.O = "Android developer"
    cs_name.OU = "Android developer"
    cs_name.CN = gethostname()
    
    cs_cert.set_subject(cs_name)
    cs_cert.set_issuer(cs_name)
    cs_cert.set_serial_number(1000)
    cs_cert.set_pubkey(pk2)
    cs_cert.sign(pk2, md="sha256")
    
    #put into extension details
    cs_cert.add_ext(X509.new_extension("nsManifest",Check.get_file_checksum(MANIFEST_FILE) ))
    cs_cert.add_ext(X509.new_extension("nsModel", Check.get_file_checksum(MAXIMIZED_MODEL_FILE)))
    cs_cert.save_pem(CERT_FILE)
예제 #5
0
def MakeCACert(common_name="grr", issuer_cn="grr_test", issuer_c="US",
               bits=2048):
  """Generate a CA certificate.

  Args:
    common_name: Name for cert.
    issuer_cn: Name for issuer.
    issuer_c: Country for issuer.
    bits: Bit length of the key used.

  Returns:
    (Certificate, priv key, pub key).
  """
  req, pk = MakeCSR(bits, common_name=common_name)
  pkey = req.get_pubkey()
  cert = X509.X509()
  cert.set_serial_number(1)
  cert.set_version(2)
  SetCertValidityDate(cert, days=3650)

  issuer = X509.X509_Name()
  issuer.C = issuer_c
  issuer.CN = issuer_cn
  cert.set_issuer(issuer)

  cert.set_subject(cert.get_issuer())
  cert.set_pubkey(pkey)
  cert.add_ext(X509.new_extension("basicConstraints", "CA:TRUE"))
  cert.add_ext(X509.new_extension("subjectKeyIdentifier",
                                  cert.get_fingerprint()))
  cert.sign(pk, "sha256")
  return cert, pk, pkey
예제 #6
0
파일: pgcert.py 프로젝트: dimV36/UIR
def verify(certificate_path, ca_certificate_path, sign_request_path, output):
    certificate = None
    try:
        certificate = X509.load_cert(certificate_path)
    except (X509.X509Error, IOError):
        print('ERROR verify: Could not load certificate for verifying')
        exit(1)
    smime = SMIME.SMIME()
    stack = X509.X509_Stack()
    stack.push(certificate)
    smime.set_x509_stack(stack)
    store = X509.X509_Store()
    store.load_info(ca_certificate_path)
    smime.set_x509_store(store)
    pks7, data = SMIME.smime_load_pkcs7(sign_request_path)
    clear_text = smime.verify(pks7, data)
    if not output:
        output = path.abspath(path.curdir) + '/%s.csr' % DEFAULT_FIELDS['CN']
    if clear_text:
        request = X509.load_request_string(clear_text)
        request.save(output)
        print('Verification OK')
        print('Request file was saved to %s' % output)
    else:
        print('Verification failed')
예제 #7
0
파일: test_auth.py 프로젝트: lovocas/nova
    def test_can_generate_x509(self):
        # NOTE(todd): this doesn't assert against the auth manager
        #             so it probably belongs in crypto_unittest
        #             but I'm leaving it where I found it.
        with user_and_project_generator(self.manager) as (user, project):
            # NOTE(vish): Setup runs genroot.sh if it hasn't been run
            cloud.CloudController().setup()
            _key, cert_str = crypto.generate_x509_cert(user.id, project.id)
            LOG.debug(cert_str)

            full_chain = crypto.fetch_ca(project_id=project.id, chain=True)
            int_cert = crypto.fetch_ca(project_id=project.id, chain=False)
            cloud_cert = crypto.fetch_ca()
            LOG.debug("CA chain:\n\n =====\n%s\n\n=====", full_chain)
            signed_cert = X509.load_cert_string(cert_str)
            chain_cert = X509.load_cert_string(full_chain)
            int_cert = X509.load_cert_string(int_cert)
            cloud_cert = X509.load_cert_string(cloud_cert)
            self.assertTrue(signed_cert.verify(chain_cert.get_pubkey()))
            self.assertTrue(signed_cert.verify(int_cert.get_pubkey()))

            if not FLAGS.use_project_ca:
                self.assertTrue(signed_cert.verify(cloud_cert.get_pubkey()))
            else:
                self.assertFalse(signed_cert.verify(cloud_cert.get_pubkey()))
예제 #8
0
파일: test_evp.py 프로젝트: clsung/m2crypto
 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
예제 #9
0
파일: ca.py 프로젝트: iSECPartners/tcpprox
def makeCert(cn, ca=None, cak=None, CA=False, subjAltNames=None, bits=1024):
    """
    Make a certificate signed by signer (or self-signed).
    If CA is true, make a key for CA use, otherwise for SSL.
    """
    k = makeRSA(bits)
    cert = X509.X509()
    chain = [cert]
    if cak is None:  # self-signed
        ca, cak = cert, k
    else:
        chain.append(ca)
    cert.set_version(2)
    cert.set_serial_number(random.randint(0, 0xFFFFFFFF))  # arbitrary range
    now = int(time.time())
    certTimes(cert, now - 60 * 60 * 24 * 365 * 5, now + 60 * 60 * 24 * 365 * 5)
    cert.set_subject(certName(C="US", ST="CA", O="iSEC Partners", OU="port swiggers", CN=cn))
    cert.set_pubkey(k)
    if CA:
        cert.add_ext(X509.new_extension("basicConstraints", "CA:TRUE"))
        cert.add_ext(X509.new_extension("subjectKeyIdentifier", cert.get_fingerprint()))
    else:
        cert.add_ext(X509.new_extension("basicConstraints", "CA:FALSE"))
        cert.add_ext(X509.new_extension("nsComment", "SSL Server"))  # XXX?
        if subjAltNames != None:
            cert.add_ext(X509.new_extension("subjectAltName", subjAltNames))
    ## XXX for CA, keyid, dirname, serial?
    # cert.add_ext(X509.new_extension('authorityKeyIdentifier', ca.get_fingerprint()))
    cert.set_issuer(ca.get_subject())
    cert.sign(cak, "sha1")
    return chain, k
예제 #10
0
    def get_certs_from_string(self, data, log_func=None):
        """
        @param data: A single string of concatenated X509 Certificates in PEM format
        @type data: str

        @param log_func: logging function
        @type log_func: function accepting a single string

        @return list of X509 Certificates
        @rtype: [M2Crypto.X509.X509]
        """
        # Refer to OpenSSL crypto/x509/by_file.c
        # Function: X509_load_cert_file() to see how they parse a chain file and add
        # the certificates to a X509_Store.  Below follows a similar procedure.
        bio = BIO.MemoryBuffer(data)
        certs = []
        try:
            if not M2CRYPTO_HAS_CRL_SUPPORT:
                # Old versions of M2Crypto behave differently and would loop indefinitely over load_cert_bio
                return X509.load_cert_string(data)
            for index in range(0, self.max_num_certs_in_chain):
                # Read one cert at a time, 'bio' stores the last location read
                # Exception is raised when no more cert data is available
                cert = X509.load_cert_bio(bio)
                if not cert:
                    # This is likely to never occur, a X509Error should always be raised
                    break
                certs.append(cert)
                if index == (self.max_num_certs_in_chain - 1) and log_func:
                    log_func("**WARNING** Pulp reached maximum number of <%s> certs supported in a chain." % (self.max_num_certs_in_chain))

        except X509.X509Error:
            # This is the normal return path.
            return certs
        return certs
예제 #11
0
    def LoadServerCertificate(self, server_certificate=None, ca_certificate=None):
        """Loads and verifies the server certificate."""
        try:
            server_cert = X509.load_cert_string(str(server_certificate))
            ca_cert = X509.load_cert_string(str(ca_certificate))

            # Check that the server certificate verifies
            if server_cert.verify(ca_cert.get_pubkey()) != 1:
                self.server_name = None
                raise IOError("Server cert is invalid.")

            # Make sure that the serial number is higher.
            server_cert_serial = server_cert.get_serial_number()

            if server_cert_serial < config_lib.CONFIG["Client.server_serial_number"]:
                # We can not accept this serial number...
                raise IOError("Server cert is too old.")
            elif server_cert_serial > config_lib.CONFIG["Client.server_serial_number"]:
                logging.info("Server serial number updated to %s", server_cert_serial)
                config_lib.CONFIG.Set("Client.server_serial_number", server_cert_serial)

                # Save the new data to the config file.
                config_lib.CONFIG.Write()

        except X509.X509Error:
            raise IOError("Server cert is invalid.")

        self.server_name = self.pub_key_cache.GetCNFromCert(server_cert)
        self.server_certificate = server_certificate
        self.ca_certificate = ca_certificate

        # We need to store the serialised version of the public key due
        # to M2Crypto memory referencing bugs
        self.pub_key_cache.Put(self.server_name, self.pub_key_cache.PubKeyFromCert(server_cert))
    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())
예제 #13
0
def Marketplace_accept_offer():
    id = str(request.form['id'])
    nonce = str(request.form['nonce'])
    timestamp = str(request.form['timestamp'])
    x509 = str(request.form['x509'])
    signature = str(request.form['signature'])

    if not check_parameter([str(id),x509,nonce,timestamp,signature]):
        return jsonify(result="missing Parameter")
    
    tmp_cert = X509.load_cert_string(x509)
    if not checkCert(tmp_cert):
        return jsonify(result="Cert not Valid")
    
    if not checkSignature(tmp_cert.get_pubkey(),[str(id),nonce,timestamp], signature):#,encypted_data
        return jsonify(result= "Siganture Invalid")
    
    c = Contract.query.get(id)
    if not c:
        return jsonify(result="Contract Offer does not exist")
    mp = Marketplace.query.get(c.marketplace_id)
    if X509.load_cert_string(str(mp.x509)).as_pem() != tmp_cert.as_pem():
        return jsonify(result="Not your marketplace")
    
    c.active = True
    mp.state="ACTIVE"
    
    db.session.add(c)
    db.session.add(mp)
    db.session.commit()
    
    return jsonify(result="OK")
예제 #14
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())
예제 #15
0
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
예제 #16
0
파일: ca.py 프로젝트: nirs/ovirt-engine
    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
예제 #17
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()))
예제 #18
0
 def test_mkreq(self):
     (req, _) = self.mkreq(1024)
     req.save_pem('tests/tmp_request.pem')
     req2 = X509.load_request('tests/tmp_request.pem')
     os.remove('tests/tmp_request.pem')
     req.save('tests/tmp_request.pem')
     req3 = X509.load_request('tests/tmp_request.pem')
     os.remove('tests/tmp_request.pem')
     req.save('tests/tmp_request.der', format=X509.FORMAT_DER)
     req4 = X509.load_request('tests/tmp_request.der',
             format=X509.FORMAT_DER)
     os.remove('tests/tmp_request.der')
     assert req.as_pem() == req2.as_pem()
     assert req.as_text() == req2.as_text()
     assert req.as_der() == req2.as_der()
     assert req.as_pem() == req3.as_pem()
     assert req.as_text() == req3.as_text()
     assert req.as_der() == req3.as_der()
     assert req.as_pem() == req4.as_pem()
     assert req.as_text() == req4.as_text()
     assert req.as_der() == req4.as_der()
     self.assertEqual(req.get_version(), 0)
     req.set_version(1)
     self.assertEqual(req.get_version(), 1)
     req.set_version(0)
     self.assertEqual(req.get_version(), 0)
예제 #19
0
 def test_extstack(self):
     # new
     ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
     ext2 = X509.new_extension('nsComment', 'Hello there')
     extstack = X509.X509_Extension_Stack()
     
     # push
     extstack.push(ext1)
     extstack.push(ext2)
     assert(extstack[1].get_name() == 'nsComment')
     assert len(extstack) == 2
     
     # iterator
     i = 0
     for e in extstack:
         i += 1
         assert len(e.get_name()) > 0
     assert i == 2
     
     # pop
     ext3 = extstack.pop()
     assert len(extstack) == 1
     assert(extstack[0].get_name() == 'subjectAltName')
     extstack.push(ext3)
     assert len(extstack) == 2
     assert(extstack[1].get_name() == 'nsComment')
     
     assert extstack.pop() is not None
     assert extstack.pop() is not None
     assert extstack.pop() is None
예제 #20
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)
예제 #21
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
예제 #22
0
파일: test_x509.py 프로젝트: mcepl/M2Crypto
 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
예제 #23
0
def validate_cert(value):
    """Validate X.509 PEM-encoded certificate."""
    value = value.encode('ascii')
    try:
        X509.load_cert_string(value, X509.FORMAT_PEM)
    except X509.X509Error:
        raise ValidationError('Invalid X.509 PEM-encoded certificate.')
예제 #24
0
파일: test_x509.py 프로젝트: mcepl/M2Crypto
    def test_extstack(self):
        # new
        ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
        ext2 = X509.new_extension('nsComment', 'Hello there')
        extstack = X509.X509_Extension_Stack()

        # push
        extstack.push(ext1)
        extstack.push(ext2)
        self.assertEqual(extstack[1].get_name(), 'nsComment')
        self.assertEqual(len(extstack), 2)

        # iterator
        i = 0
        for e in extstack:
            i += 1
            self.assertGreater(len(e.get_name()), 0)
        self.assertEqual(i, 2)

        # pop
        ext3 = extstack.pop()
        self.assertEqual(len(extstack), 1)
        self.assertEqual(extstack[0].get_name(), 'subjectAltName')
        extstack.push(ext3)
        self.assertEqual(len(extstack), 2)
        self.assertEqual(extstack[1].get_name(), 'nsComment')

        self.assertIsNotNone(extstack.pop())
        self.assertIsNotNone(extstack.pop())
        self.assertIsNone(extstack.pop())
예제 #25
0
def main(argv):
    if len(argv) != 1 and len(argv) != 2:
        print "Usage: pin.py [<certificate_path> | <host> <port>]"
        return

    if (len(argv) == 1):
        cert        = X509.load_cert(argv[0])
    else:
        peerCert = ssl.get_server_certificate((argv[0], int(argv[1])))
        cert = X509.load_cert_string(peerCert)
    pubkey = cert.get_pubkey().as_der()

    digest = hashlib.sha256()
    digest.update(pubkey)
    sha256 = digest.digest()

    print "Calculating PIN for certificate: " + cert.get_subject().as_text()
    print "\n"
    print "Public Key Pins:"
    print "----------------"
    print "SHA256:" + binascii.hexlify(sha256)
    print "PLAIN:" + binascii.hexlify(pubkey)
    print "\n"
    print "Certificate Pins:"
    print "-----------------"
    print "CERTSHA256:" + cert.get_fingerprint('sha256')
    print "CERTPLAIN:" + binascii.hexlify(cert.as_der())
예제 #26
0
    def generate_cert_key_pair(self):
        private_key = EVP.PKey()
        rsa = M2RSA.gen_key(2048, 65537, lambda: None)
        private_key.assign_rsa(rsa)

        req = X509.Request()
        req.set_pubkey(private_key)
        name = req.get_subject()
        name.CN = "NVIDIA GameStream Client"
        req.sign(private_key, "sha1")

        public_key = req.get_pubkey()
        cert = X509.X509()
        cert.set_serial_number(1)
        cert.set_version(2)
        self.validate_cert(cert)
        cert.set_issuer(name)
        cert.set_subject(cert.get_issuer())
        cert.set_pubkey(public_key)
        cert.add_ext(X509.new_extension("basicConstraints", "CA:TRUE", 1))
        cert.add_ext(X509.new_extension("keyUsage", "keyCertSign, cRLSign", 1))
        cert.add_ext(X509.new_extension("subjectKeyIdentifier", cert.get_fingerprint()))
        cert.sign(private_key, "sha1")

        cert.save(self.cert_file, 1)

        with open(self.key_file, "wb") as key_file:
            key_file.write(private_key.as_pem(None))
            key_file.close()

        self.load_cert_key_pair()
예제 #27
0
파일: test_x509.py 프로젝트: mcepl/M2Crypto
    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')
예제 #28
0
def create_self_signed_cert(rsa, subject={'CN':'Testing'}, san=None):
	""" Creates a self-signed cert
	    Pass in an RSA private key object
	    Pass in a dictionary of subject name data, using C ST L O OU CN keys
	    Pass in an optional san like 'DNS:example.com'
	    Returns a X509.X509 object
	"""
	pk = EVP.PKey()
	pk.assign_rsa(rsa)

	name = X509.X509_Name()
	for key in ['C', 'ST', 'L', 'O', 'OU', 'CN']:
		if subject.get(key, None):
			setattr(name, key, subject[key])

	cert = X509.X509()
	cert.set_serial_number(1)
	cert.set_version(2)
	t = long(time.time())
	now = ASN1.ASN1_UTCTIME()
	now.set_time(t)
	expire = ASN1.ASN1_UTCTIME()
	expire.set_time(t + 365 * 24 * 60 * 60)
	cert.set_not_before(now)
	cert.set_not_after(expire)
	cert.set_issuer(name)
	cert.set_subject(name)
	cert.set_pubkey(pk)
	cert.add_ext(X509.new_extension('basicConstraints', 'CA:FALSE'))
	if san:
		cert.add_ext(X509.new_extension('subjectAltName', san))
	cert.add_ext(X509.new_extension('subjectKeyIdentifier', cert.get_fingerprint()))
	cert.sign(pk, 'sha1')
	return cert
예제 #29
0
    def generate_ssl_credential(self,
                                hostname,
                                
                                lifetime=24*60*60,
                                sign_hash="sha1"):
        """Generate credentials for a given target.

        Returns a tuple of X509 certificate and EVP key."""
        cert = X509.X509()
        cert.set_serial_number(self._get_next_serial_number())
        cert.set_version(2)
        name = self.get_relative_subject()
        name.CN = hostname
        cert.set_subject(name)
        cert.set_issuer(self.cert.get_subject())
        cert.set_pubkey(self.service_key)
        notBefore = m2.x509_get_not_before(cert.x509)
        notAfter  = m2.x509_get_not_after(cert.x509)
        m2.x509_gmtime_adj(notBefore, 0)
        m2.x509_gmtime_adj(notAfter, lifetime)
        ext = X509.new_extension('basicConstraints', 'CA:FALSE')
        ext.set_critical()
        cert.add_ext(ext)
        ext = X509.new_extension('keyUsage',
                                 'digitalSignature, keyEncipherment')
        ext.set_critical()
        cert.add_ext(ext)
        cert.sign(self.key, sign_hash)
        return cert, self.service_key
예제 #30
0
파일: test_x509.py 프로젝트: mcepl/M2Crypto
    def mkreq(self, bits, ca=0):
        pk = EVP.PKey()
        x = X509.Request()
        rsa = RSA.gen_key(bits, 65537, self.callback)
        pk.assign_rsa(rsa)
        rsa = None  # should not be freed here
        x.set_pubkey(pk)
        name = x.get_subject()
        name.C = "UK"
        name.CN = "OpenSSL Group"
        if not ca:
            ext1 = X509.new_extension('subjectAltName',
                                      'DNS:foobar.example.com')
            ext2 = X509.new_extension('nsComment', 'Hello there')
            extstack = X509.X509_Extension_Stack()
            extstack.push(ext1)
            extstack.push(ext2)
            x.add_extensions(extstack)

        with self.assertRaises(ValueError):
            x.sign(pk, 'sha513')

        x.sign(pk, 'sha1')
        self.assertTrue(x.verify(pk))
        pk2 = x.get_pubkey()
        self.assertTrue(x.verify(pk2))
        return x, pk
예제 #31
0
파일: ca.py 프로젝트: xinyuweb/tcpprox
def certName(**kw):
    n = X509.X509_Name()
    for k, v in kw.items():
        setattr(n, k, v)
    return n
예제 #32
0
 def GetX509Cert(self):
     return X509.load_cert_string(str(self))
예제 #33
0
    def testAllTheThings(self):
        """
        Test the full scenario: multiple encrypted and plaintext recipients.

        Tests that multiple recipients can all read a message, and that
        recipients with no Identity records get plain text.
        """
        count = 1
        sender = Identity.objects.get(address="*****@*****.**")
        recipients = [identity.address for identity in Identity.objects.all()]
        recipients.extend(["*****@*****.**", "*****@*****.**"])
        message = mail.EmailMultiAlternatives(
            self.text_template % count,
            self.text_template % count,
            sender.address,
            recipients,
        )
        message.attach_alternative(self.html_template % count, "text/html")
        message.send()

        backend = mail.get_connection()
        self.assertEqual(len(backend.messages), 2)

        #
        # verify the encryption and signature
        #
        s = SMIME.SMIME()

        # Load the sender's cert.
        x509 = X509.load_cert_string(data.RECIPIENT1_CERTIFICATE)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        # Load the sender's CA cert.
        st = X509.X509_Store()
        st.add_x509(x509)
        s.set_x509_store(st)

        # Decrypt the message as both encrypted recipients

        #
        # recipient 1
        #
        recipient1_cert = BIO.MemoryBuffer(
            data.RECIPIENT1_CERTIFICATE.encode("UTF-8"))
        recipient1_key = BIO.MemoryBuffer(data.RECIPIENT1_KEY.encode("UTF-8"))
        s.load_key_bio(recipient1_key, recipient1_cert)

        msg = BIO.MemoryBuffer(backend.messages[1]["message"].encode("UTF-8"))
        p7, msg_data = SMIME.smime_load_pkcs7_bio(msg)
        out = s.decrypt(p7)

        # Verify the message
        msg = BIO.MemoryBuffer(out)
        p7, msg_data = SMIME.smime_load_pkcs7_bio(msg)
        verified_msg = s.verify(p7, msg_data)
        self.assertTrue(verified_msg)

        #
        # recipient 2
        #
        recipient2_cert = BIO.MemoryBuffer(
            data.RECIPIENT2_CERTIFICATE.encode("UTF-8"))
        recipient2_key = BIO.MemoryBuffer(data.RECIPIENT2_KEY.encode("UTF-8"))
        s.load_key_bio(recipient2_key, recipient2_cert)

        msg = BIO.MemoryBuffer(backend.messages[1]["message"].encode("UTF-8"))
        p7, msg_data = SMIME.smime_load_pkcs7_bio(msg)
        out = s.decrypt(p7)

        # Verify the message
        msg = BIO.MemoryBuffer(out)
        p7, msg_data = SMIME.smime_load_pkcs7_bio(msg)
        self.assertTrue(s.verify(p7, msg_data))

        # verify that the plaintext also got through
        msg = BIO.MemoryBuffer(backend.messages[1]["message"].encode("UTF-8"))
예제 #34
0
def verify(input_bio, certstore_path, AUTO_SIGNED_CERT, type):
    """
    Retrieves X.509 certificate from input data and verifies signed message
    using as certificate store input certstore, inspired by:
    U{http://code.activestate.com/recipes/285211/}.

    @type input_bio: M2Crypto.BIO
    @param input_bio: input data to verify
    @type certstore_path: filepath
    @param certstore_path: path to the file of the trusted certificates,
        for example /etc/ssl/certs/ca-certificats.crt.
    @type type: str
    @keyword type: specifies the type of input PKCS#7 data: PEM or DER
    @type AUTO_SIGNED_CERT: boolean
    @keyword AUTOSIGNED_CERT: to accept or not auto signed certificates as
        valid for verification.
    @rtype: list or None
    @return: a list of verified certificates retrieved from the original data
        if verification success, else None.
    @raise CertStoreNotAvailable: the reference certstore for verification is
        not available.
    @raise MissingSignerCertificate: the input PKCS#7 is not a signed PKCS#7.
    """
    signer = SMIME.SMIME()
    cert_store = X509.X509_Store()
    if not os.access(certstore_path, os.R_OK):
        logging.error('certstore not available for verify')
        raise CertStoreNotAvailable('certstore not available %' %
                                    (certstore_path))
    cert_store.load_info(certstore_path)
    signer.set_x509_store(cert_store)
    data_bio = None
    try:
        if type == 'PEM':
            p7, data_bio = SMIME.smime_load_pkcs7_bio(input_bio)
        elif type == 'DER':
            p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(input_bio._ptr()), 1)
        else:
            logging.error('pkcs7 type error: unknown type')
            raise BadPKCS7Type('unknown type: ' + type +
                               '; possible values: PEM, DER')
    except SMIME.SMIME_Error as e:
        logging.error('load pkcs7 error: ' + str(e))
        raise
    if data_bio is not None:
        data = data_bio.read()
        data_bio = BIO_from_buffer(data)
    sk3 = p7.get0_signers(X509.X509_Stack())
    if len(sk3) == 0:
        logging.error('missing certificate')
        raise MissingSignerCertificate('missing certificate')
    signer_certs = []
    for cert in sk3:
        signer_certs.append(
            "-----BEGIN CERTIFICATE-----\n{}-----END CERTIFICATE-----\n".
            format(base64.encodestring(cert.as_der()).decode('ascii')))
    signer.set_x509_stack(sk3)
    v = None
    try:
        if AUTO_SIGNED_CERT:
            v = signer.verify(p7, data_bio, flags=SMIME.PKCS7_NOVERIFY)
        else:
            v = signer.verify(p7, data_bio)
    except SMIME.SMIME_Error as e:
        logging.error('smime error: ' + str(e))
        raise
    except SMIME.PKCS7_Error as e:
        logging.error('pkcs7 error: ' + str(e))
        raise
    if data_bio is not None and data != v and v is not None:
        return
    return signer_certs
예제 #35
0
  def Layout(self, request, response):
    # Present the certificate as text
    self.cert = X509.load_cert_string(str(self.proxy)).as_text()

    response = super(CertificateRenderer, self).RenderAjax(request, response)
    return self.CallJavascript(response, "CertificateRenderer.Layout")
예제 #36
0
 def test_ext_error(self):
     with self.assertRaises(X509.X509Error):
         X509.new_extension('nonsensicalName', 'blabla')
예제 #37
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)
예제 #38
0
def x509_name2list(name):
    for i in range(0, name.entry_count()):
        yield X509.X509_Name_Entry(m2.x509_name_get_entry(name._ptr(), i),
                                   _pyfree=0)
예제 #39
0
def verify_signature(original, signed, cert_str):
    cert = X509.load_cert_string(cert_str)
    pkey = cert.get_pubkey()
    pkey.verify_init()
    pkey.verify_update(original)
    return pkey.verify_final(signed)
예제 #40
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')
예제 #41
0
 def test_new(self):
     crl = X509.CRL()
     self.assertEqual(crl.as_text()[:34],
                      'Certificate Revocation List (CRL):')
예제 #42
0
def tuple2x509_name_entry(tup):
    obj, data = tup
    _x509_ne = m2.x509_name_entry_create_by_txt(None, obj, ASN1.MBSTRING_ASC, data, len(data))
    if not _x509_ne:
        raise ValueError("Invalid object indentifier: %s" % obj)
    return X509.X509_Name_Entry(_x509_ne, _pyfree = 1) # Prevent memory leaks
예제 #43
0
    def test_load_der_string(self):
        with open('tests/x509.der', 'rb') as f:
            x509 = X509.load_cert_der_string(f.read())

        fp = x509.get_fingerprint('sha1')
        self.assertEqual(fp, self.expected_hash)
예제 #44
0
    def test_mkcert(self):
        for utc in (True, False):
            req, pk = self.mkreq(1024)
            pkey = req.get_pubkey()
            self.assertTrue(req.verify(pkey))
            sub = req.get_subject()
            self.assertEqual(len(sub), 2,
                             'Subject should be long 2 items not %d' % len(sub))

            cert = X509.X509()
            cert.set_serial_number(1)
            cert.set_version(2)
            cert.set_subject(sub)
            t = int(time.time()) + time.timezone
            if utc:
                now = ASN1.ASN1_UTCTIME()
            else:
                now = ASN1.ASN1_TIME()
            now.set_time(t)
            now_plus_year = ASN1.ASN1_TIME()
            now_plus_year.set_time(t + 60 * 60 * 24 * 365)
            cert.set_not_before(now)
            cert.set_not_after(now_plus_year)
            self.assertEqual(str(cert.get_not_before()), str(now))
            self.assertEqual(str(cert.get_not_after()), str(now_plus_year))

            issuer = X509.X509_Name()
            issuer.CN = 'The Issuer Monkey'
            issuer.O = 'The Organization Otherwise Known as My CA, Inc.'
            cert.set_issuer(issuer)
            cert.set_pubkey(pkey)
            cert.set_pubkey(cert.get_pubkey())  # Make sure get/set work

            ext = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
            ext.set_critical(0)
            self.assertEqual(ext.get_critical(), 0)
            cert.add_ext(ext)

            cert.sign(pk, 'sha1')
            with self.assertRaises(ValueError):
                cert.sign(pk, 'nosuchalgo')

            self.assertTrue(cert.get_ext('subjectAltName').get_name(),
                            'subjectAltName')
            self.assertTrue(cert.get_ext_at(0).get_name(),
                            'subjectAltName')
            self.assertTrue(cert.get_ext_at(0).get_value(),
                            'DNS:foobar.example.com')
            self.assertEqual(cert.get_ext_count(), 1,
                             'Certificate should have now 1 extension not %d' %
                             cert.get_ext_count())
            with self.assertRaises(IndexError):
                cert.get_ext_at(1)
            self.assertTrue(cert.verify())
            self.assertTrue(cert.verify(pkey))
            self.assertTrue(cert.verify(cert.get_pubkey()))
            self.assertEqual(cert.get_version(), 2)
            self.assertEqual(cert.get_serial_number(), 1)
            self.assertEqual(cert.get_issuer().CN, 'The Issuer Monkey')

            if m2.OPENSSL_VERSION_NUMBER >= 0x90800f:
                self.assertFalse(cert.check_ca())
                self.assertFalse(cert.check_purpose(m2.X509_PURPOSE_SSL_SERVER, 1))
                self.assertFalse(cert.check_purpose(m2.X509_PURPOSE_NS_SSL_SERVER,
                                                    1))
                self.assertTrue(cert.check_purpose(m2.X509_PURPOSE_SSL_SERVER, 0))
                self.assertTrue(cert.check_purpose(m2.X509_PURPOSE_NS_SSL_SERVER,
                                                   0))
                self.assertTrue(cert.check_purpose(m2.X509_PURPOSE_ANY, 0))
            else:
                with self.assertRaises(AttributeError):
                    cert.check_ca()
예제 #45
0
 def test_fingerprint(self):
     x509 = X509.load_cert('tests/x509.pem')
     fp = x509.get_fingerprint('sha1')
     self.assertEqual(fp, self.expected_hash)
예제 #46
0
 def test_malformed_data(self):
     with self.assertRaises(X509.X509Error):
         X509.load_cert_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_cert_der_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.new_stack_from_der('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_cert('tests/alltests.py')
     with self.assertRaises(X509.X509Error):
         X509.load_request('tests/alltests.py')
     with self.assertRaises(X509.X509Error):
         X509.load_request_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_request_der_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_crl('tests/alltests.py')
예제 #47
0
 if proxy:
     try:
         x509 = X509.load_cert_string(proxy, X509.FORMAT_DER)
         fileCertString = X509.load_cert_string(cert, X509.FORMAT_DER)
     except X509Error, e:
         raise InvalidCredentials("Invalid X509 proxy: %s", str(e))
     #print the cert DN
     certDN =  '/' + '/'.join(fileCertString.get_subject().as_text().split(', '))
     proxyDN = '/' + '/'.join(x509.get_subject().as_text().split(', '))
     log.info("cert DN: "+ certDN)
     chain_pem =fileCertString.as_pem()
     chain_pem += x509.as_pem()
     chain = X509.load_cert_string(chain_pem)
 else:
     try:
         x509 = X509.load_cert_string(cert, X509.FORMAT_DER)
     except X509Error, e:
         raise InvalidCredentials("Invalid X509 certificate: %s", str(e))
     certDN = '/' + '/'.join(x509.get_subject().as_text().split(', '))
 pubkey = x509.get_pubkey().get_rsa()
 verify = EVP.PKey()
 verify.assign_rsa(pubkey)
 verify.reset_context(cred['hash'])
 verify.verify_init()
 if proxy:
     verify.verify_update(proxy)
 else:
     verify.verify_update(cert)
 verify.verify_update(cred['ts'])
 if not verify.verify_final(sign):
     log.info("Signature verification failed")
예제 #48
0
def cmd_init(workingdir):
    cwd = os.getcwd()
    try:
        common.ch_dir(workingdir, logger)

        rmfiles("*.pem")
        rmfiles("*.crt")
        rmfiles("*.zip")
        rmfiles("*.der")
        rmfiles("private.yml")

        if common.CA_IMPL == 'cfssl':
            pk_str, cacert, ca_pk, _ = ca_impl.mk_cacert()
        elif common.CA_IMPL == 'openssl':
            cacert, ca_pk, _ = ca_impl.mk_cacert()
        else:
            raise Exception("Unknown CA implementation: %s" % common.CA_IMPL)

        priv = read_private()

        # write out keys
        with open('cacert.crt', 'wb') as f:
            f.write(cacert.as_pem())

        f = BIO.MemoryBuffer()
        ca_pk.save_key_bio(f, None)
        priv[0]['ca'] = f.getvalue()
        f.close()

        # store the last serial number created.
        # the CA is always serial # 1
        priv[0]['lastserial'] = 1

        write_private(priv)

        ca_pk.get_rsa().save_pub_key('ca-public.pem')

        # generate an empty crl
        if common.CA_IMPL == 'cfssl':
            crl = ca_impl.gencrl([], cacert.as_pem(), pk_str)
        elif common.CA_IMPL == 'openssl':
            crl = ca_impl.gencrl([], cacert.as_pem(), str(priv[0]['ca']))
        else:
            raise Exception("Unknown CA implementation: %s" % common.CA_IMPL)

        if isinstance(crl, str):
            crl = crl.encode('utf-8')

        with open('cacrl.der', 'wb') as f:
            f.write(crl)
        convert_crl_to_pem("cacrl.der", "cacrl.pem")

        # Sanity checks...
        cac = X509.load_cert('cacert.crt')
        if cac.verify():
            logger.info("CA certificate created successfully in %s" %
                        workingdir)
        else:
            logger.error("ERROR: Cert does not self validate")
    finally:
        os.chdir(cwd)
예제 #49
0
def cmd_certpkg(workingdir, name, insecure=False):
    cwd = os.getcwd()
    try:
        common.ch_dir(workingdir, logger)
        # zip up the crt, private key, and public key

        with open('cacert.crt', 'r') as f:
            cacert = f.read()

        with open("%s-public.pem" % name, 'r') as f:
            pub = f.read()

        with open("%s-cert.crt" % name, 'r') as f:
            cert = f.read()

        with open('cacrl.der', 'rb') as f:
            crl = f.read()

        with open('cacrl.pem', 'r') as f:
            crlpem = f.read()

        cert_obj = X509.load_cert_string(cert)
        serial = cert_obj.get_serial_number()
        subject = str(cert_obj.get_subject())

        priv = read_private()
        private = priv[0][name]

        with open("%s-private.pem" % name, 'r') as f:
            prot_priv = f.read()

        #code to create a pem formatted protected private key using the keystore password
    #     pk = EVP.load_key_string(str(priv[0][name]))
    #     f = BIO.MemoryBuffer()
    #     # globalcb will return the global password provided by the user
    #     pk.save_key_bio(f, 'aes_256_cbc', globalcb)
    #     prot_priv = f.getvalue()
    #     f.close()

    # no compression to avoid extraction errors in tmpfs
        sf = io.BytesIO()
        with zipfile.ZipFile(sf, 'w', compression=zipfile.ZIP_STORED) as f:
            f.writestr('%s-public.pem' % name, pub)
            f.writestr('%s-cert.crt' % name, cert)
            f.writestr('%s-private.pem' % name, private)
            f.writestr('cacert.crt', cacert)
            f.writestr('cacrl.der', crl)
            f.writestr('cacrl.pem', crlpem)
        pkg = sf.getvalue()

        if insecure:
            logger.warn(
                "Unprotected private keys in cert package being written to disk"
            )
            with open('%s-pkg.zip' % name, 'w') as f:
                f.write(pkg)
        else:
            # actually output the package to disk with a protected private key
            with zipfile.ZipFile('%s-pkg.zip' % name,
                                 'w',
                                 compression=zipfile.ZIP_STORED) as f:
                f.writestr('%s-public.pem' % name, pub)
                f.writestr('%s-cert.crt' % name, cert)
                f.writestr('%s-private.pem' % name, prot_priv)
                f.writestr('cacert.crt', cacert)
                f.writestr('cacrl.der', crl)
                f.writestr('cacrl.pem', crlpem)

        logger.info("Creating cert package for %s in %s-pkg.zip" %
                    (name, name))

        return pkg, serial, subject
    finally:
        os.chdir(cwd)
예제 #50
0
    def test_x509_name(self):
        n = X509.X509_Name()
        # It seems this actually needs to be a real 2 letter country code
        n.C = 'US'
        self.assertEqual(n.C, 'US')
        n.SP = 'State or Province'
        self.assertEqual(n.SP, 'State or Province')
        n.L = 'locality name'
        self.assertEqual(n.L, 'locality name')
        # Yes, 'orhanization' is a typo, I know it and you're smart.
        # However, fixing this typo would break later hashes.
        # I don't think it is worthy of troubles.
        n.O = 'orhanization name'
        self.assertEqual(n.O, 'orhanization name')
        n.OU = 'org unit'
        self.assertEqual(n.OU, 'org unit')
        n.CN = 'common name'
        self.assertEqual(n.CN, 'common name')
        n.Email = '*****@*****.**'
        self.assertEqual(n.Email, '*****@*****.**')
        n.serialNumber = '1234'
        self.assertEqual(n.serialNumber, '1234')
        n.SN = 'surname'
        self.assertEqual(n.SN, 'surname')
        n.GN = 'given name'
        self.assertEqual(n.GN, 'given name')
        self.assertEqual(n.as_text(),
                         'C=US, ST=State or Province, ' +
                         'L=locality name, O=orhanization name, ' +
                         'OU=org unit, CN=common ' +
                         'name/[email protected]' +
                         '/serialNumber=1234, ' +
                         'SN=surname, GN=given name')
        self.assertEqual(len(n), 10,
                         'X509_Name has inappropriate length %d ' % len(n))
        n.givenName = 'name given'
        self.assertEqual(n.GN, 'given name')  # Just gets the first
        self.assertEqual(n.as_text(), 'C=US, ST=State or Province, ' +
                         'L=locality name, O=orhanization name, ' +
                         'OU=org unit, ' +
                         'CN=common name/[email protected]' +
                         '/serialNumber=1234, ' +
                         'SN=surname, GN=given name, GN=name given')
        self.assertEqual(len(n), 11,
                         'After adding one more attribute X509_Name should ' +
                         'have 11 and not %d attributes.' % len(n))
        n.add_entry_by_txt(field="CN", type=ASN1.MBSTRING_ASC,
                           entry="Proxy", len=-1, loc=-1, set=0)
        self.assertEqual(len(n), 12,
                         'After adding one more attribute X509_Name should ' +
                         'have 12 and not %d attributes.' % len(n))
        self.assertEqual(n.entry_count(), 12, n.entry_count())
        self.assertEqual(n.as_text(), 'C=US, ST=State or Province, ' +
                         'L=locality name, O=orhanization name, ' +
                         'OU=org unit, ' +
                         'CN=common name/[email protected]' +
                         '/serialNumber=1234, ' +
                         'SN=surname, GN=given name, GN=name given, ' +
                         'CN=Proxy')

        with self.assertRaises(AttributeError):
            n.__getattr__('foobar')
        n.foobar = 1
        self.assertEqual(n.foobar, 1)

        # X509_Name_Entry tests
        l = 0
        for entry in n:
            self.assertIsInstance(entry, X509.X509_Name_Entry)
            self.assertIsInstance(entry.get_object(), ASN1.ASN1_Object)
            self.assertIsInstance(entry.get_data(), ASN1.ASN1_String)
            l += 1
        self.assertEqual(l, 12, l)

        l = 0
        for cn in n.get_entries_by_nid(m2.NID_commonName):
            self.assertIsInstance(cn, X509.X509_Name_Entry)
            self.assertIsInstance(cn.get_object(), ASN1.ASN1_Object)
            data = cn.get_data()
            self.assertIsInstance(data, ASN1.ASN1_String)
            t = data.as_text()
            self.assertIn(t, ("common name", "Proxy",))
            l += 1
        self.assertEqual(l, 2,
                         'X509_Name has %d commonName entries instead '
                         'of expected 2' % l)

        # The target list is not deleted when the loop is finished
        # https://docs.python.org/2.7/reference\
        #        /compound_stmts.html#the-for-statement
        # so this checks what are the attributes of the last value of
        # ``cn`` variable.
        cn.set_data(b"Hello There!")
        self.assertEqual(cn.get_data().as_text(), "Hello There!")

        # OpenSSL 1.0.1h switched from encoding strings as PRINTABLESTRING (the
        # first hash value) to UTF8STRING (the second one)
        self.assertIn(n.as_hash(), (1697185131, 1370641112),
                      'Unexpected value of the X509_Name hash %s' %
                      n.as_hash())

        self.assertRaises(IndexError, lambda: n[100])
        self.assertIsNotNone(n[10])
예제 #51
0
 def get_relative_subject(self):
     """Return a X509_NAME wthout the CN field set suitable for a EEC signed by the CA"""
     name = X509.X509_Name()
     ca_name = self.cert.get_subject()
     name.O = "My Org"  # TODO: Make this configurable
     return name
예제 #52
0
파일: ca.py 프로젝트: jtux270/translate
    def _miscUpgrade(self):
        #
        # In <3.6 setup did not store the organization and
        # country in post install file. Load it from CA certificate.
        #
        if self.environment[oenginecons.PKIEnv.ORG] is None:
            ca = X509.load_cert(
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT)
            self.environment[
                oenginecons.PKIEnv.ORG] = ca.get_subject().get_entries_by_nid(
                    X509.X509_Name.nid['O'])[0].get_data().as_text()
            self.environment[oenginecons.PKIEnv.COUNTRY] = ca.get_subject(
            ).get_entries_by_nid(
                X509.X509_Name.nid['C'])[0].get_data().as_text()

        self.logger.info(_('Upgrading CA'))

        #
        # LEGACY NOTE
        # Since 3.0 and maybe before the method of
        # allowing user to override AIA was to explict
        # edit files. Until we rewrite the entire PKI
        # we must preserve this approach.
        # The template may change over time, so regenerate.
        #
        aia = None
        template = oenginecons.FileLocations.OVIRT_ENGINE_PKI_CERT_TEMPLATE[:-len(
            '.in')]
        if os.path.exists(template):
            with open(template) as f:
                PREFIX = 'caIssuers;URI:'
                for l in f.read().splitlines():
                    if l.startswith('authorityInfoAccess'):
                        aia = l[l.find(PREFIX) + len(PREFIX):]
                        break

        uninstall_files = []
        self._setupUninstall(uninstall_files)
        if aia is not None:
            localtransaction = transaction.Transaction()
            with localtransaction:
                for name in (
                        oenginecons.FileLocations.OVIRT_ENGINE_PKI_CA_TEMPLATE,
                        oenginecons.FileLocations.
                        OVIRT_ENGINE_PKI_CERT_TEMPLATE,
                ):
                    localtransaction.append(
                        filetransaction.FileTransaction(
                            name=name[:-len('.in')],
                            content=outil.processTemplate(
                                name, {
                                    '@AIA@': aia,
                                }),
                            modifiedList=uninstall_files,
                        ), )
                    localtransaction.append(
                        filetransaction.FileTransaction(
                            name=name[:-len('.template.in')] + '.conf',
                            content=outil.processTemplate(
                                name, {
                                    '@AIA@': aia,
                                }),
                            modifiedList=uninstall_files,
                        ), )

        if self.environment[oenginecons.PKIEnv.RENEW]:
            if self._expired(
                    X509.load_cert(oenginecons.FileLocations.
                                   OVIRT_ENGINE_PKI_ENGINE_CA_CERT)):
                self._ca_was_renewed = True
                self.logger.info(_('Renewing CA'))
                self.execute(
                    args=(
                        oenginecons.FileLocations.OVIRT_ENGINE_PKI_CA_CREATE,
                        '--renew',
                        '--keystore-password=%s' %
                        (self.environment[oenginecons.PKIEnv.STORE_PASS], ),
                    ),
                    envAppend={
                        'JAVA_HOME':
                        self.environment[oengcommcons.ConfigEnv.JAVA_HOME],
                    },
                )

            self._enrollCertificates(True, uninstall_files)
예제 #53
0
 def from_file(cls, cert_file, key_file):
     logger = cls.__get_logger()
     logger.info("Loading CA from %s and %s" % (cert_file, key_file))
     cert = X509.load_cert(cert_file)
     key = EVP.load_key(key_file)
     return cls(cert, key)
예제 #54
0
def verify_sns_notification(request):
    """ Takes a notification request from Amazon push service SNS and verifies the origin of the notification.
        Kudos to Artur Rodrigues for suggesting M2Crypto: http://goo.gl/KAgPPc
        Args:
            request (HTTPRequest): The request object that is passed to the view function
        Returns (bool):
            True if he message passes the verification, False otherwise
        Raises:
            ValueError: If the body of the response couldn't be parsed
            M2CryptoError: If an error raises during the verification process
            URLError: If the SigningCertURL couldn't be opened
    """
    canonical_sub_unsub_format = [
        "Message", "MessageId", "SubscribeURL", "Timestamp", "Token",
        "TopicArn", "Type"
    ]
    canonical_notification_format = [
        "Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type"
    ]

    content = json.loads(request.body)
    decoded_signature = b64decode(content["Signature"])

    # Depending on the message type, canonical message format varies: http://goo.gl/oSrJl8
    try:
        message_type = get_sns_message_type(request)
    except KeyError:
        return False
    if message_type in (SNS_MESSAGE_TYPE_SUB_NOTIFICATION,
                        SNS_MESSAGE_TYPE_UNSUB_NOTIFICATION):
        canonical_message = canonical_message_builder(
            content, canonical_sub_unsub_format)
    elif message_type == SNS_MESSAGE_TYPE_NOTIFICATION:
        canonical_message = canonical_message_builder(
            content, canonical_notification_format)
    else:
        raise ValueError("Message Type (%s) is not recognized" % message_type)

    allow_http = os.getenv('SNS_VALIDATOR_ALLOW_HTTP', False)

    if not allow_http:
        if not VALID_AMAZON_URL.match(content["SigningCertURL"]):
            raise ValueError("Unexpected amazon url %s" %
                             content["SigningCertURL"])

    # Load the certificate and extract the public key
    cert = X509.load_cert_string(urlopen(content["SigningCertURL"]).read())
    pubkey = cert.get_pubkey()
    pubkey.reset_context(md='sha1')
    pubkey.verify_init()

    # Feed the canonical message to sign it with the public key from the certificate
    pubkey.verify_update(canonical_message)

    # M2Crypto uses EVP_VerifyFinal() from openssl as the underlying verification function.
    # http://goo.gl/Bk2G36: "EVP_VerifyFinal() returns 1 for a correct signature, 0 for failure and -1
    # if some other error occurred."
    verification_result = pubkey.verify_final(decoded_signature)

    if verification_result not in (0, 1):
        raise M2CryptoError(
            "Some error occurred while verifying the signature.")
    return bool(verification_result)
예제 #55
0
    def post(self):

        if not self.app.config['AUTHORITY_CERTIFICATE']:
            return 'The server lacks an authority certificate. Unable to sign the certificate request.', 403

        if not self.app.config['AUTHORITY_PRIVATE_KEY']:
            return 'The server lacks a private key. Unable to sign the certificate request.', 403

        certificate_request_der = base64.b64decode(
            request.json.get('certificate_request'))

        certificate_request = X509.load_request_der_string(
            certificate_request_der)

        if not (certificate_request.get_subject().CN == current_user.username):
            return 'I will not a sign certificate request for a different user ! (Got "%s" while "%s" was expected)' % (
                certificate_request.get_subject().CN,
                current_user.username), 403

        # Create a new certificate
        certificate = X509.X509()

        # Set the certificate version
        certificate.set_version(2)

        # Copy the certificate public key from the certificate request
        certificate.set_pubkey(certificate_request.get_pubkey())

        # Set the certificate issuer
        certificate.set_issuer(
            self.app.config['AUTHORITY_CERTIFICATE'].get_subject())

        # Set the certificate subject
        subject_name = X509.X509_Name()
        subject_name.CN = certificate_request.get_subject().CN or ''
        subject_name.OU = self.app.config['AUTHORITY_CERTIFICATE'].get_subject(
        ).OU or ''
        subject_name.O = self.app.config['AUTHORITY_CERTIFICATE'].get_subject(
        ).O or ''
        subject_name.L = self.app.config['AUTHORITY_CERTIFICATE'].get_subject(
        ).L or ''
        subject_name.ST = self.app.config['AUTHORITY_CERTIFICATE'].get_subject(
        ).ST or ''
        subject_name.C = self.app.config['AUTHORITY_CERTIFICATE'].get_subject(
        ).C or ''

        certificate.set_subject(subject_name)

        # Set the certificate "not before" timestamp
        not_before = ASN1.ASN1_UTCTIME()
        not_before.set_datetime(datetime.today() + timedelta(days=-1))

        certificate.set_not_before(not_before)

        # Set the certificate "not after" timestamp
        not_after = ASN1.ASN1_UTCTIME()
        not_after.set_datetime(
            datetime.today() +
            self.app.config['CERTIFICATE_VALIDITY_DURATION'])

        certificate.set_not_after(not_after)

        # The issued certificate shall not be used as a certificate authority
        certificate.add_ext(X509.new_extension('basicConstraints', 'CA:FALSE'))

        # Sign the certificate
        pkey = EVP.PKey()
        pkey.assign_rsa(self.app.config['AUTHORITY_PRIVATE_KEY'],
                        capture=False)

        certificate.sign(pkey, 'sha1')

        current_user.certificate = certificate

        DATABASE.session.commit()

        result = {
            'certificate': current_user.certificate_string,
        }

        return jsonify(result)
예제 #56
0
파일: ca.py 프로젝트: jtux270/translate
 def _extractPKCS12Certificate(self, pkcs12):
     return X509.load_cert_string(
         str(self._extractPKCS12CertificateString(pkcs12)))
예제 #57
0
from M2Crypto import BIO, SMIME, X509

s = SMIME.SMIME()

# Load private key and cert.
s.load_key('mycert-private.pem', 'mycert.pem')

# Load the signed/encrypted data.
p7, data = SMIME.smime_load_pkcs7('target/python_encrypted_signed.txt')

# After the above step, 'data' == None.
# Decrypt p7. 'out' now contains a PKCS #7 signed blob.
out = s.decrypt(p7)

# Load the signer's cert.
x509 = X509.load_cert('mycert.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('mycert.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)
예제 #58
0
 def _extractPKCS12Certificate(self, pkcs12):
     res = False
     cert = self._extractPKCS12CertificateString(pkcs12)
     if cert:
         res = X509.load_cert_string(str(cert))
     return res
예제 #59
0
p7 = smime.sign(data_bio,
                SMIME.PKCS7_NOATTR | SMIME.PKCS7_BINARY | SMIME.PKCS7_NOSIGS)

out = BIO.MemoryBuffer()
smime.write(out, p7)
ret = out.read()
base64_sign = ret[ret.index('base64') + len('base64'):]
base64_sign = base64_sign.strip()
print base64_sign
raw_sign = base64.b64decode(base64_sign)

print '\n\n'
print '++++' * 10
print '\n\n'

x509 = X509.load_cert(pub)
sk = X509.X509_Stack()
sk.push(x509)
#
# 'des_cbc',
# 'des_cfb',
# 'des_ecb',
# 'des_ede3_cbc',
# 'des_ede3_cfb',
# 'des_ede3_ecb',
# 'des_ede3_ofb',
# 'des_ede_cbc',
# 'des_ede_cfb',
# 'des_ede_ecb',
# 'des_ede_ofb',
# 'des_ofb',
예제 #60
0
파일: test_x509.py 프로젝트: pmp-p/M2Crypto
 def test_set_long_serial(self):
     cert = X509.X509()
     cert.set_serial_number(127614157056681299805556476275995414779)
     self.assertEqual(cert.get_serial_number(),
                      127614157056681299805556476275995414779)