Exemple #1
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 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.')
Exemple #3
0
    def testCertificateLoading(self):
        """Load x509 certificate
        """
        #before = datetime(2010, 01, 01, 6, tzinfo=ASN1.UTC)
        #after = datetime(2015, 01, 01, 6, tzinfo=ASN1.UTC)
        x509_text = X509.load_cert_string(CA_CERT, X509.FORMAT_PEM).as_text()

        cert = Certificate.new_from_pem(CA_CERT)
        cert.save()
        self.assertTrue(cert.CN == "Admin")
        self.assertTrue(cert.country == "FR")
        #self.assertTrue(cert.begin == before)
        #self.assertTrue(cert.end == after)
        self.assertTrue(cert.is_ca)
        self.assertTrue(cert.auth_kid)
        self.assertTrue(cert.subject_kid)
        self.assertTrue(cert.certhash)
        self.assertTrue(" " not in cert.auth_kid)
        self.assertTrue(" " not in cert.subject_kid)
        # Just test Certificate.m2_x509() method
        x509 = X509.load_cert_string(cert.pem, X509.FORMAT_PEM)
        m2x509 = cert.m2_x509()
        self.assertTrue(x509.as_text() == m2x509.as_text())

        self.assertTrue(cert.auth_kid in m2x509.as_text())
        self.assertTrue(cert.subject_kid in m2x509.as_text())
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
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")
Exemple #6
0
    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()))
Exemple #7
0
 def test_load_string(self):
     f = open('tests/x509.pem')
     s = f.read()
     f.close()
     f2 = open('tests/x509.der', 'rb')
     s2 = f2.read()
     f2.close()
     x509 = X509.load_cert_string(s)
     x5092 = X509.load_cert_string(s2, 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())
Exemple #8
0
    def test_load_string(self):
        with open('tests/x509.pem') as f:
            s = f.read()

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

        x509 = X509.load_cert_string(s)
        x5092 = X509.load_cert_string(s2, 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())
Exemple #9
0
 def clean_certificate(self):
     if not check_smime_status():
         raise forms.ValidationError(_('Improperly configured S/MIME: Email backend is incompatible'))
     try:
         from M2Crypto import X509
         certificate = self.cleaned_data['certificate']
         X509.load_cert_string(str(certificate))
     except ImportError:
         raise forms.ValidationError(_('Improperly configured S/MIME: missing dependencies'))
     except X509.X509Error:
         raise forms.ValidationError(_('Invalid certificate: unknown format'))
     return certificate
Exemple #10
0
def validate_cert(cert_pem):
    """
    @param cert_pem: certificate pem to verify
    @type cert_pem str
    @return: True if valid, else False
    @rtype bool
    """
    try:
        X509.load_cert_string(cert_pem)
    except X509.X509Error:
        return False
    return True
Exemple #11
0
def testRead():
    certText1 = request.form['cert']
    certText = certText1.encode('ascii')
    foo = open('foo.pem')
    bar = foo.read()
    if (bar == certText):
        logging.debug('Read OK')
    else:
        logging.debug('stored:\n%s\nread:\n%s' % (bar, certText))
    logging.debug('Creating cert from file\n')
    certBar = X509.load_cert_string(bar, X509.FORMAT_PEM)
    logging.debug('Creating cert from POST data')
    cert = X509.load_cert_string(certText, X509.FORMAT_PEM)
Exemple #12
0
 def test_load_string(self):
     f = open('test/x509.pem')
     s = f.read()
     f.close()
     f2 = open('test/x509.der', 'rb')
     s2 = f2.read()
     f2.close()
     x509 = X509.load_cert_string(s)
     x5092 = X509.load_cert_string(s2, 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 #13
0
 def add_pem(self,filename,load_keys=False):
     # parse a bundle PEM with multiple key / certificates
     lines = open(filename,'r').read().splitlines()
     inkey = False
     incert = False
     tmplines = []
     for line in lines:
         if line == self.BEGIN_CERTIFICATE:
             tmplines = [line]
             incert = True
         elif line == self.END_CERTIFICATE:
             tmplines.append(line)
             crt =  X509.load_cert_string('\n'.join(tmplines))
             self._certificates[crt.get_fingerprint(md='sha1')] = SSLCertificate(filename,crt=crt)
             incert = False
             tmplines = []
         elif line == self.BEGIN_KEY:
             tmplines = [line]
             inkey = True
         elif line == self.END_KEY:
             tmplines.append(line)
             if load_keys:
                 key = EVP.load_key_string('\n'.join(tmplines),callback=self.callback)
                 self._keys[key.get_modulus()] = SSLPrivateKey(filename,key=key,callback=self.callback)
             inkey = False
             tmplines = []
         else:
             if inkey or incert:
                 tmplines.append(line)
def marketplace_put_offer():
    id = str(request.form['id'])#request.args.get("id",type=int)
    encypted_data = str(request.form['data'])#request.args.get("data",type=str)
    key = str(request.form['key'])#request.args.get("key",type=str)
    IV = str(request.form['IV'])#request.args.get("IV",type=str)
    signature = str(request.form['signature'])#request.args.get("signature",type=str)
    x509 = str(request.form['x509'])#request.args.get("x509",type=str)
    if not check_parameter([str(id),x509,key,IV,encypted_data]):
        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),IV,key,encypted_data], signature):#,encypted_data
        return jsonify(result= "Siganture Invalid")
    mp = Marketplace.query.get(id)
    if not mp:
        return jsonify(result="Offer does not exist")
    if mp.state != "OPEN":
        return jsonify(result="Offer not OPEN")
    tmp_contract = Contract(key=key,data=encypted_data,IV=IV)
    mp.contracts.append(tmp_contract)
    db.session.add(tmp_contract)
    db.session.add(mp)
    db.session.commit()
    return jsonify(result=tmp_contract.to_json)
Exemple #15
0
def buildTokenCache(authztoken):
    """ build in memory cache for security tokens """
    # find all pub keys in agent and encrypt the security token with them
    appGlobal = config['pylons.app_globals']
    pubKeyDir = os.path.join(manifestutil.manifestPath('agent'), 'agent', 'cronus', 'keys')
    LOG.info('key directory %s' % pubKeyDir)
    if os.path.exists(pubKeyDir):
        try:
            import pki
            from M2Crypto import X509
            pubKeyFiles = [f for f in os.listdir(pubKeyDir) if re.match(r'.*\.cert', f)]
            LOG.info('key files %s' % pubKeyFiles)
            for pubKeyFile in pubKeyFiles:
                # reload the certs from disk
                certf = open(os.path.join(pubKeyDir, pubKeyFile), 'r')
                ca_cert_content = certf.read()
                certf.close()

                cert = X509.load_cert_string(ca_cert_content)
                #            pub = RSA.load_pub_key(os.path.join(pubKeyDir, pubKeyFile))
                encryptedToken = pki.encrypt(cert.get_pubkey(), authztoken)
                appGlobal.encryptedtokens[pubKeyFile] = encryptedToken    
                LOG.info('token %s=%s' % (pubKeyFile, encryptedToken))
        except BaseException as excep:
            LOG.error('Error loading pki keys %s - %s' % (str(excep), traceback.format_exc(2)))
def doCron():
    engine = create_engine('sqlite:///test.db')
    session = sessionmaker()
    session.configure(bind=engine)
    #Base.metadata.create_all(engine)


    s = session()
    s._model_changes = {}
    for mp in s.query(Marketplace).all():
        if "ACTIVE" not in mp.state:
            continue
        n=  RSA.importKey(X509.load_cert_string(str(mp.x509)).get_pubkey().get_rsa().as_pem()).key.n
        pubKey = PublicKey(n)
        for con in mp.contracts:
            if not con.accudata:
                accu_data = defaultdict(lambda: 0)
            else:
                accu_data = loads(con.accudata.data)
            for data in con.flowdata:
                for key , value in loads(data.data)['AccuData'].iteritems():
                    #print key , value
                    if accu_data[key]:
                        accu_data[key] = e_add(pubKey, accu_data[key], value)
                    else:
                        accu_data[key] = value
            data_string = dumps(accu_data)
            #pprint.pprint(accu_data)
            if con.accudata:
                con.accudata.data = data_string
                con.accudata.timestamp = datetime.datetime.utcnow()
            else:
                con.accudata = AccuData(data=data_string)
            s.add(con)
            s.commit()
Exemple #17
0
    def get_extension(self, name):

        # pyOpenSSL does not have a way to get extensions
        m2x509 = X509.load_cert_string(self.save_to_string())
        value = m2x509.get_ext(name).get_value()

        return value
def getCA(certfile):
	global caURL_by_serial
	global caCRT_by_caURL

	# Extract serial from cert.
	serial = get_serial_from_cert(certfile)

	# Return cert, if it is known already.
	if serial in caURL_by_serial and caURL_by_serial[serial] in caCRT_by_caURL:
		return caCRT_by_caURL[caURL_by_serial[serial]]

	# Get URL of cert from serial (ask LE) - it now returns the full URL
	caURL = get_caURL_from_serial(serial)
	if caURL == "":
		raise ValueError("LE returned empty CA URL for serial <"+serial+">.")
	else:
		caURL_by_serial[serial] = caURL

	# Get actual cert from URL
	if caURL in caCRT_by_caURL:
		return caCRT_by_caURL[caURL_by_serial[serial]]

	# cert is not yet know, get it from LE
	print "-> Retrieving lets encrypt intermediate cert <" + caURL + ">."
	try:
		f = urllib2.urlopen(caURL)
	except Exception as err:
		raise ValueError("Could not get CA cert from LE (" + str(err) + ").")

	caCRT_by_caURL[caURL] = X509.load_cert_string(f.read().strip(), X509.FORMAT_DER).as_pem()
	return caCRT_by_caURL[caURL_by_serial[serial]]
Exemple #19
0
def check_hashes_validity(certificates, rands):
    """ Check if the provided blind hashes matches with the blinded hashes of the provided certificates.

    :param certificates: the provided certificates.
    :type certificates: DER str list
    :param rands: the provided blinding factors.
    :return: True if all the hashes match. False otherwise.
    :rtype: bool
    """
    response = True

    # Load key
    f = open(ACA_CERT)
    aca_cert_text = f.read()
    f.close()
    aca_cert = X509.load_cert_string(aca_cert_text)

    for i in range(len(certificates)):
        if i is not r:
            validity = check_blind_hash(certificates[i], blinded_hashes[i], rands[i], aca_cert)

            # Check that the provided blind signatures match with the calculated ones
            if not validity:
                response = validity
                break
    return response
Exemple #20
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
Exemple #21
0
    def testPostConnectionCheck(self):
        pemSite = '''-----BEGIN CERTIFICATE-----
MIID9TCCA16gAwIBAgIBBjANBgkqhkiG9w0BAQQFADCBmjELMAkGA1UEBhMCVVMx
CzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRowGAYDVQQKExFv
c2Fmb3VuZGF0aW9uLm9yZzELMAkGA1UECxMCQ0ExEDAOBgNVBAMTB09TQUYgQ0Ex
KzApBgkqhkiG9w0BCQEWHGhvc3RtYXN0ZXJAb3NhZm91bmRhdGlvbi5vcmcwHhcN
MDUwNDIwMTgxMTE3WhcNMDYwNDIwMTgxMTE3WjCBuzELMAkGA1UEBhMCVVMxEzAR
BgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xGjAYBgNV
BAoTEW9zYWZvdW5kYXRpb24ub3JnMREwDwYDVQQLEwhidWd6aWxsYTEjMCEGA1UE
AxMaYnVnemlsbGEub3NhZm91bmRhdGlvbi5vcmcxKzApBgkqhkiG9w0BCQEWHGhv
c3RtYXN0ZXJAb3NhZm91bmRhdGlvbi5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A
MIGJAoGBAN4CWLF6RZaCDZc6kGijgUSfRDO6JD9Utllr2PCMot07D6oA30XEZKWQ
+9KvvMwt3BEHHWG9ngog2gI/bhk7XvFqsreG35jch/Q0f6fU/dk/Dqz1Q0pYb+j0
d2MwDEDOrV2nJuaQkOur0k/oM38kLjVW849XFNmNEfdhRzPGp8f7AgMBAAGjggEm
MIIBIjAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRl
ZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUT7Sg/404L9rptjl3gnAPCKb3EJ0wgccG
A1UdIwSBvzCBvIAUUBSZO/t3VgCaayxM9NxoTcVaB0uhgaCkgZ0wgZoxCzAJBgNV
BAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEaMBgG
A1UEChMRb3NhZm91bmRhdGlvbi5vcmcxCzAJBgNVBAsTAkNBMRAwDgYDVQQDEwdP
U0FGIENBMSswKQYJKoZIhvcNAQkBFhxob3N0bWFzdGVyQG9zYWZvdW5kYXRpb24u
b3JnggEAMA0GCSqGSIb3DQEBBAUAA4GBAK/YvXsGbDLuLUEENZsxppcsi5DZM7wd
lqEfJmSam9E585dsOdZylBrypR2X5RRPgEP2qXUDLXW9WHPwztXMM3s42NT5wX51
QzAXPN7hH0vJ3sbpb84tziV5VkvqDT51+WP4MGrk44oVQEjylxnboMkdtCi08Ts5
QUW4hRYWNNbb
-----END CERTIFICATE-----'''
        x509 = X509.load_cert_string(pemSite)
        
        assert ssl.postConnectionCheck(x509, 'bugzilla.osafoundation.org')
        self.assertRaises(Checker.WrongHost, ssl.postConnectionCheck, x509, 'example.com')
        self.assertRaises(Checker.NoCertificate, ssl.postConnectionCheck, None, 'example.com')
Exemple #22
0
def create_account(request):

    if request.method == 'POST':

        with open('certs/cert-admin.pem', 'r') as pem:
            ca_crt = pem.read()
        cert = X509.load_cert_string(ca_crt)

        with open('certs/key-admin.pem', 'r') as pem:
            ca_pkey = pem.read()
        pkey  = EVP.load_key_string(ca_pkey)

        # ne = X509.new_extension
        email = request.params['email']
        username = request.params['username']
        spkac = SPKAC(request.params['spkac'],
                      None,
                      # ne,
                      CN=username,
                      Email=email
                      )
        serial = 1000  # XXX must be incremented
        try:
            crt = spkac.gen_crt(pkey, cert, serial, hash_algo='sha512')
        except TypeError:
            crt = spkac.gen_crt(pkey, cert, serial)
        response = Response(body=crt.as_pem(),
                            headers={'Accept-Ranges': 'bytes',
                                     'Content-Type': 'application/x-x509-user-cert'
                                     },
                            content_type='application/x-x509-user-cert')
        return response
    return {}
    def __init__(self):
        self.request = current.request
        self.ssl_client_raw_cert = self.request.env.ssl_client_raw_cert

        # rebuild the certificate passed by the env
        # this is double work, but it is the only way
        # since we cannot access the web server ssl engine directly

        if self.ssl_client_raw_cert:

            x509=X509.load_cert_string(self.ssl_client_raw_cert, X509.FORMAT_PEM)
            # extract it from the cert
            self.serial = self.request.env.ssl_client_serial or ('%x' % x509.get_serial_number()).upper()


            subject = x509.get_subject()

            # Reordering the subject map to a usable Storage map
            # this allows us a cleaner syntax:
            # cn = self.subject.cn
            self.subject = Storage(filter(None,
                                          map(lambda x:
                                                  (x,map(lambda y: 
                                                         y.get_data().as_text(),
                                                         subject.get_entries_by_nid(subject.nid[x]))),
                                              subject.nid.keys())))
def dataFlow_put():

    id = str(request.form['id'])
    data = str(request.form['data'])
    IV = str(request.form['IV'])
    key = str(request.form['key'])
    timestamp =  str(request.form['timestamp'])
    signature = str(request.form['signature'])
    x509 = str(request.form['x509'])
    if not check_parameter([str(id),x509,signature,data,timestamp,IV,key]):
        return jsonify(result="missing Parameter")
    if int(timestamp) + 10 < time.time():
        return jsonify(result="Old data")
    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(),[id,data,IV,key,timestamp], signature):#,encypted_data
        return jsonify(result= "Siganture Invalid")
    con = Contract.query.get(id)
    if not con:
        return jsonify(result="Unkown ID")
    jobj = json.loads(data)
    dataflow = Dataflow(data = data, iv = IV , key = key)
    con.flowdata.append(dataflow)
    db.session.add(con)
    db.session.add(dataflow)
    db.session.commit()
    # TODO Check ob gleiche fimra wie vertrag
    return jsonify(result ="OK")
Exemple #25
0
def check_signature(temp_path, developer_cert):	
	tfile = tarfile.open(temp_path, 'r:gz')
	tempAppPath = os.path.join(settings.MEDIA_ROOT,'tempApp')
	tfile.extractall(tempAppPath)
	tfile.close()	
	for root,dirs, files in os.walk(tempAppPath):
		for item in fnmatch.filter(files,"*"):
			if item.endswith(".sign"):
				signatureFile  = item
			else:		
				binary_path = root +"/" +item		
				size = int(os.path.getsize(binary_path))/float(1024)							
				appFile = item
	print root			
	if signatureFile is None or appFile is None:
		shutil.rmtree(tempAppPath)
		return False, 0	
	else:		
		signature = open(os.path.join(root,signatureFile),'rt').read()
		appData = open(os.path.join(root,appFile),'rt').read()
		data = hashlib.sha256(appData).digest()  
		dev_cert_file = open(developer_cert,'rt').read()
		dev_cert = X509.load_cert_string(dev_cert_file,X509.FORMAT_PEM)
		public_key = dev_cert.get_pubkey()
		public_key_rsa = public_key.get_rsa()
		shutil.rmtree(tempAppPath)	
	try :		
		return	public_key_rsa.verify(data,signature,algo='sha256'), size
	except Exception as e:
		print e
		return False, 0
def dataFlow_get():
    id = str(request.form['id'])
    timestamp =  str(request.form['timestamp'])
    signature = str(request.form['signature'])
    accu = str(request.form['accu'])
    x509 = str(request.form['x509'])
    if not check_parameter([str(id),x509,signature,timestamp]):
        return jsonify(result="missing Parameter")
    if int(timestamp) + 10 < time.time():
        return jsonify(result="Old data")
    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(),[id,accu,timestamp], signature):#,encypted_data
        return jsonify(result= "Siganture Invalid")
    
    c = Contract.query.get(id)
    if accu == "0":
        if c.flowdata:
            return jsonify(result=[i.to_json for i in c.flowdata ])
    if accu == "1":
        if(c.accudata):
            return jsonify(result=c.accudata.data)
        else:
            return jsonify(result="Not ready yet")
    else:
        return jsonify(result = "Wrong accu param")
Exemple #27
0
 def update(self, content):
     if content:
         x509 = X509.load_cert_string(content)
     else:
         x509 = X509.X509()
     self.__ext = Extensions(x509)
     self.x509 = x509
Exemple #28
0
 def __is_server(self, req):
     cert = req.get_ssl_certificate(binary_form=True)
     x509 = X509.load_cert_string(cert, X509.FORMAT_DER)
     if x509.get_fingerprint('sha1') == settings.SERVER_CERT_FINGERPRINT:
         return True
     else:
         return False
Exemple #29
0
    def sign_m2(keyfile, content):
        """
        Sign content with a keyfile using M2Crypto
        """

        try:
            # load intermediate certs if any
            stack = M2X509.X509_Stack()
            _, _, certificates = parse_keyfile(keyfile)
            for c in certificates:
                cert = M2X509.load_cert_string(c)
                # skip the main CA cert, as this must be built-in anyway
                if cert.check_ca() and str(cert.get_issuer()) == str(cert.get_subject()):
                    continue
                stack.push(cert)

            # actual signing
            smime = M2S.SMIME()
            smime.load_key(keyfile)
            smime.set_x509_stack(stack)

            pkcs7 = M2Buffer()
            smime.sign(M2Buffer(content), M2S.PKCS7_DETACHED | M2S.PKCS7_BINARY).write_der(pkcs7)
            return pkcs7.read()

        except M2EVPError, ex:
            if re.search("ANY PRIVATE KEY", ex.message):
                raise ValueError("Key file does not contain a private key")
            raise ValueError("Signing failed. Wrong password?")
Exemple #30
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())
Exemple #31
0
    def _importAndFind(self, pem, trust):
        x509 = X509.load_cert_string(pem)
        fingerprint = certificate._fingerprint(x509)
        certificate._importCertificate(x509, fingerprint, trust, self.rep.view)

        qString = u'for i in "//parcels/osaf/framework/certstore/Certificate" where i.fingerprint == "%s"' % fingerprint

        qName = 'fpCertQuery' + fingerprint
        q = self.rep.view.findPath('//Queries/%s' % (qName))
        if q is None:
            p = self.rep.view.findPath('//Queries')
            k = self.rep.view.findPath('//Schema/Core/Query')
            q = Query.Query(qName, p, k, qString)

        assert len(q) == 1

        for cert in q:  #q[0] does not seem to work
            return cert
Exemple #32
0
    def _importAndFind(self, pem, trust):
        x509 = X509.load_cert_string(pem)
        fingerprint = utils.fingerprint(x509)
        certificate.importCertificate(x509, fingerprint, trust, self.view)

        view = self.view

        matchingCerts = FilteredCollection(
            'fpCertQuery' + fingerprint,
            itsView=view,
            source=utils.getExtent(certificate.Certificate, view, exact=True),
            filterExpression=u"view.findValue(uuid, 'fingerprint') == '%s'" %
            fingerprint,
            filterAttributes=['fingerprint'])

        self.assert_(len(matchingCerts) == 1)

        return iter(matchingCerts).next()
    def _extract_plain_cert(nvhttp, text):
        cert_text = nvhttp.get_xml_string(text, "plaincert")

        cert = X509.load_cert_string(cert_text.decode('hex'))

        der_cert = cert.as_der()
        der = asn1.DerSequence()
        der.decode(der_cert)
        der_sig_raw = der[2]

        der_sig_dec = asn1.DerObject()
        der_sig_dec.decode(der_sig_raw)

        sig0 = der_sig_dec.payload

        sig = sig0[1:]

        return cert, sig.encode('hex')
Exemple #34
0
 def _x509_load_cert(self, f):
     try:
         res = X509.load_cert(f)
     except X509.X509Error:
         # In the past we wrote the ca cert with 'text'.
         # This confuses newer m2crypto.
         # Try to read it with openssl instead.
         rc, stdout, stderr = self.execute(
             args=(
                 self.command.get('openssl'),
                 'x509',
                 '-in',
                 f,
             ),
             raiseOnError=False,
         )
         res = X509.load_cert_string(str('\n'.join(stdout)))
     return res
Exemple #35
0
    def get_extension(self, name):

        if name is None:
            return None

        certstr = self.save_to_string()
        if certstr is None or certstr == "":
            return None
        # pyOpenSSL does not have a way to get extensions
        m2x509 = X509.load_cert_string(certstr)
        if m2x509 is None:
            logger.warn("No cert loaded in get_extension")
            return None
        if m2x509.get_ext(name) is None:
            return None
        value = m2x509.get_ext(name).get_value()

        return value
Exemple #36
0
    def _enroll_cert_auto_ssh(self):
        cert = None
        self.logger.info(
            _("Signing the {base_touser} certificate on the engine server").
            format(base_touser=self._base_touser, ))

        tries_left = 30
        goodcert = False
        while not goodcert and tries_left > 0:
            try:
                self._remote_engine.copy_to_engine(
                    file_name='{pkireqdir}/{remote_name}.req'.format(
                        pkireqdir=self._engine_pki_requests_dir,
                        remote_name=self._remote_name,
                    ),
                    content=self._csr,
                )
                self._remote_engine.execute_on_engine(cmd=self._enroll_command)
                cert = self._remote_engine.copy_from_engine(
                    file_name='{pkicertdir}/{remote_name}.cer'.format(
                        pkicertdir=self._engine_pki_certs_dir,
                        remote_name=self._remote_name,
                    ), )
                goodcert = self._pubkey == X509.load_cert_string(
                    cert).get_pubkey().as_pem(cipher=None)
                if not goodcert:
                    self.logger.error(
                        _('Failed to sign {base_touser} certificate on '
                          'engine server').format(
                              base_touser=self._base_touser, ))
            except:
                self.logger.error(
                    _('Error while trying to sign {base_touser} certificate').
                    format(base_touser=self._base_touser, ))
                self.logger.debug('Error signing cert', exc_info=True)
            tries_left -= 1
            if not goodcert and tries_left > 0:
                self.dialog.note(text=_('Trying again...'))
                time.sleep(10)

        self.logger.info(
            _('{base_touser} certificate signed successfully').format(
                base_touser=self._base_touser, ))
        return cert
Exemple #37
0
    def decode(self, ticket):
        decoded = json.loads(base64.b64decode(ticket))

        if self._peer is not None:
            x509 = self._peer
        else:
            x509 = X509.load_cert_string(
                decoded['certificate'].encode('utf8')
            )

        if self._ca is not None:
            self._verifyCertificate(self._ca, x509)

        if self._eku is not None:
            if self._eku not in x509.get_ext(
                'extendedKeyUsage'
            ).get_value().split(','):
                raise ValueError('Certificate is not authorized for action')

        signedFields = [s.strip() for s in decoded['signedFields'].split(',')]
        if len(
            set(['salt', 'data']) &
            set(signedFields)
        ) == 0:
            raise ValueError('Invalid ticket')

        pkey = x509.get_pubkey()
        pkey.reset_context(md=decoded['digest'])
        pkey.verify_init()
        for field in signedFields:
            pkey.verify_update(decoded[field].encode('utf8'))
        if pkey.verify_final(
            base64.b64decode(decoded['signature'])
        ) != 1:
            raise ValueError('Invalid ticket signature')

        if not (
            self._parseDate(decoded['validFrom']) <=
            datetime.datetime.utcnow() <=
            self._parseDate(decoded['validTo'])
        ):
            raise ValueError('Ticket life time expired')

        return decoded['data']
Exemple #38
0
 def subject(self):
     """
     Get the certificate subject.
     note: Missing NID mapping for UID added to patch openssl.
     @return: A dictionary of subject fields.
     @rtype: dict
     """
     d = {}
     content = self.read()
     x509 = X509.load_cert_string(content)
     subject = x509.get_subject()
     subject.nid['UID'] = 458
     for key, nid in subject.nid.items():
         entry = subject.get_entries_by_nid(nid)
         if len(entry):
             asn1 = entry[0].get_data()
             d[key] = str(asn1)
             continue
     return d
Exemple #39
0
    def add_certificate(self, certificate):
        """
		Certificates are either packed binary strings in DER format, or
		instances of m2crypto.X509.X509
		"""
        if not isinstance(certificate, X509.X509):
            try:
                certificate = X509.load_cert_string(certificate,
                                                    X509.FORMAT_DER)
            except:  # pylint: disable=bare-except
                return 1

        newFingerprint = certificate.get_fingerprint()
        for oldcert in self.x509certs:
            if newFingerprint == oldcert.get_fingerprint():
                return -1

        self.x509certs.append(certificate)
        return 0
Exemple #40
0
def verify_signature(keys, message):
    # get public key
    url = message['SigningCertURL']
    if url not in certs:
        r = requests.get(url)
        cert_string = r.text
        certs[url] = cert_string
    else:
        cert_string = certs[url]
    cert = X509.load_cert_string(str(cert_string))
    pub_key = cert.get_pubkey()
    pub_key.reset_context(md='sha1')
    pub_key.verify_init()

    # create string to sign
    str_to_sign = get_string_to_sign(keys, message)
    pub_key.verify_update(str_to_sign)
    result = pub_key.verify_final(b64decode(message['Signature']))
    return result == 1
Exemple #41
0
    def write_policy(ca_pem, target_file):
        """ Writes a signing policy for CA described by ca_pem
            into the file with filename target_file.

            The policy file will allow any issued certs to be in
            /OU=Users or /OU=Hosts.

            Returns None.
        """
        if isinstance(ca_pem, unicode):
            ca_pem = ca_pem.encode('ascii', 'ignore')
        cert = X509.load_cert_string(ca_pem, X509.FORMAT_PEM)
        ca_raw_dn = X509Utils.x509name_to_str(cert.get_subject())
        ca_dn = X509Utils.rfc_to_openssl(ca_raw_dn)
        policy_text = "access_id_CA   X509    '%s'\n" % ca_dn
        policy_text += "pos_rights     globus  CA:sign\n"
        policy_text += "cond_subjects  globus  '\"/O=*\"'\n"
        with open(target_file, "w") as pol_fd:
            pol_fd.write(policy_text)
Exemple #42
0
    def sign_m2(keyfile, content):
        """
        Sign content with a keyfile using M2Crypto
        """

        # XXX kill once we can load the key directly from a buffer
        if not hasattr(keyfile, "name"):
            warnings.warn("Rewrapping keyfile into a temporary file. "
                          "This may case the file to be written to insecure "
                          "storage!")
            with NamedTemporaryFile() as kp:
                with StreamPositionRestore(kp):
                    with StreamPositionRestore(keyfile):
                        kp.write(keyfile.read())
                return sign_m2(kp, content)

        try:
            # load intermediate certs if any
            stack = M2X509.X509_Stack()
            _, _, certificates = parse_keyfile(keyfile)
            for c in certificates:
                cert = M2X509.load_cert_string(c)
                # skip the main CA cert, as this must be built-in anyway
                if (cert.check_ca()
                        and str(cert.get_issuer()) == str(cert.get_subject())):
                    continue
                stack.push(cert)

            # actual signing
            smime = M2S.SMIME()
            smime.load_key(keyfile.name)
            smime.set_x509_stack(stack)

            pkcs7 = M2Buffer()
            smime.sign(M2Buffer(content),
                       M2S.PKCS7_DETACHED | M2S.PKCS7_BINARY).write_der(pkcs7)
            return pkcs7.read()

        except (M2EVPError, ex):
            if re.search("ANY PRIVATE KEY", ex.message):
                raise ValueError("Key file does not contain a private key")
            raise ValueError("Signing failed. Wrong password?")
def M2Crypto_verify(data):
    # https://www.artur-rodrigues.com/tech/2013/08/19/verifying-x509-signatures-in-python.html
    # https://penguindreams.org/blog/signature-verification-between-java-and-python/
    message = '&'.join([
        "{}={}".format(k, data[k]) for k in sorted(data.keys())
        if k != 'signature'
    ])

    cert_path = get_abs_path(CERTIFICATE_PATH, acquirer_cert)
    privatekey_path = get_abs_path(CERTIFICATE_PATH, acquirer_cert_key)

    from M2Crypto import X509
    str_cert = str(open(cert_path, 'r').read())
    cert = X509.load_cert_string(str_cert)
    pubkey = cert.get_pubkey()
    pubkey.reset_context(md='sha1')
    pubkey.verify_init()
    pubkey.verify_update(message.encode('utf-8'))
    result = pubkey.verify_final(base64.b64decode(data['signature']))
    print(result)
def M2Crypto_try_sign(data):
    message = '&'.join([
        "{}={}".format(k, data[k]) for k in sorted(data.keys())
        if k != 'signature'
    ])

    cert_path = get_abs_path(CERTIFICATE_PATH, acquirer_cert)
    privatekey_path = get_abs_path(CERTIFICATE_PATH, acquirer_cert_key)

    from M2Crypto import X509
    str_cert = str(open(cert_path, 'r').read())
    cert = X509.load_cert_string(str_cert)
    pubkey = cert.get_pubkey()
    pubkey.reset_context(md='sha1')

    pubkey.sign_init()
    pubkey.sign_update(message.encode())
    # raise SIGSEGV - error memory access
    sign = pubkey.sign_final()
    print(base64.b64encode(sign))
Exemple #45
0
 def getCert(cls, swiFile):
     with zipfile.ZipFile(swiFile, 'r') as swi:
         try:
             sigInfo = swi.getinfo(cls.getSigFileName(swiFile))
         except KeyError:
             # Occurs if SIG_FILE_NAME is not in the swi (the SWI is not signed properly)
             return None
         with swi.open(sigInfo, 'r') as sigFile:
             for line in sigFile:
                 data = line.split(':')
                 if len(data) == 2:
                     if data[0] == ISSUERCERT:
                         try:
                             base64_cert = cls.base64Decode(data[1].strip())
                             return X509.load_cert_string(base64_cert)
                         except TypeError:
                             return None
                 else:
                     sys.stderr.write('Unexpected format for line in swi[x]-signature file: %s\n' % line)
         return None
Exemple #46
0
    def _update(self, content):
        if content:
            x509 = X509.load_cert_string(content)
        else:
            x509 = X509.X509()
        self.__ext = Extensions(x509)
        self.x509 = x509

        self._parse_subject()
        self.serial = self.x509.get_serial_number()

        self.altName = None
        try:
            nameExt = self.x509.get_ext('subjectAltName')
            if nameExt:
                self.altName = nameExt.get_value()
        except LookupError:
            # This may not be defined, seems to only be used for identity
            # certificates:
            pass
Exemple #47
0
  def __createCertM2Crypto(self):
    """ Create new certificate for user

        :return: S_OK(tuple)/S_ERROR() -- tuple contain certificate and pulic key as strings
    """
    # Create public key
    userPubKey = EVP.PKey()
    userPubKey.assign_rsa(RSA.gen_key(self.bits, 65537, util.quiet_genparam_callback))
    # Create certificate
    userCert = X509.X509()
    userCert.set_pubkey(userPubKey)
    userCert.set_version(2)
    userCert.set_subject(self.__X509Name)
    userCert.set_serial_number(int(random.random() * 10 ** 10))
    # Add extentionals
    userCert.add_ext(X509.new_extension('basicConstraints', 'CA:' + str(False).upper()))
    userCert.add_ext(X509.new_extension('extendedKeyUsage', 'clientAuth', critical=1))
    # Set livetime
    validityTime = datetime.timedelta(days=400)
    notBefore = ASN1.ASN1_UTCTIME()
    notBefore.set_time(int(time.time()))
    notAfter = ASN1.ASN1_UTCTIME()
    notAfter.set_time(int(time.time()) + int(validityTime.total_seconds()))
    userCert.set_not_before(notBefore)
    userCert.set_not_after(notAfter)
    # Add subject from CA
    with open(self.parameters['CertFile']) as cf:
      caCertStr = cf.read()
    caCert = X509.load_cert_string(caCertStr)
    userCert.set_issuer(caCert.get_subject())
    # Use CA key
    with open(self.parameters['KeyFile']) as cf:
      caKeyStr = cf.read()
    pkey = EVP.PKey()
    pkey.assign_rsa(RSA.load_key_string(caKeyStr, callback=util.no_passphrase_callback))
    # Sign
    userCert.sign(pkey, self.algoritm)

    userCertStr = userCert.as_pem()
    userPubKeyStr = userPubKey.as_pem(cipher=None, callback=util.no_passphrase_callback)
    return S_OK((userCertStr, userPubKeyStr))
    def get_contracts_xml_signature(self, documento):
        self.get_contracts()
        #, datetime.now().replace(microsecond=0).isoformat('T')
        fiel_pass = "******"
        if str(documento).upper() == 'C':
            document = open('Contracts/contract.txt')
        elif documento.upper() == 'P':
            document = open('Contracts/privacy.txt')
        aviso_tmpl = '''<?xml version="1.0" encoding="UTF-8"?>
        <documento><contrato rfc="%s" fecha="2019-09-24T16:00:00">%s</contrato><ds:Signature 
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#">''' 
        aviso = aviso_tmpl % (self.taxpayer_id, document.read())

        digest_value = base64.encodestring(hashlib.sha1(aviso).digest())
        
        signed_info_digest_tmpl = '''<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>%s</ds:DigestValue></ds:Reference></ds:SignedInfo>'''
        signed_info_digest = signed_info_digest_tmpl % (digest_value)

        signed_info_digest_value = hashlib.sha1(signed_info_digest).digest().strip()
        
        try:
            pri_key = RSA.load_key_string(self.key)
        except Exception as e:
            print "Error en key get_contracts_xml_signature =>" + str(e)
        
        try:
            pri_cer = X509.load_cert_string(self.cer, X509.FORMAT_PEM)
        except Exception as e:
            print "Error en cer get_contracts_xml_signature =>" + str(e)

        signature_value = pri_key.sign(signed_info_digest_value)
       
        cert = self.cer.replace('-----BEGIN CERTIFICATE-----', '')
        cert = cert.replace('-----END CERTIFICATE-----', '').strip()

        signature_template_tmpl = '''%s<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>+%s</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>%s</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>%s</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature></documento>'''
        signature_template = signature_template_tmpl % (aviso, digest_value, base64.encodestring(signature_value).strip(), cert)

        with open('Contracts/sign_template_{}.xml'.format(documento.upper()), 'w') as sign_template:
            sign_template.write(signature_template)
            sign_template.close()
def main():

    continua = True

    certificate.create_self_signed_cert()

    f = open("selfsigned.crt")
    cert_buffer = f.read()
    f.close()

    cert = X509.load_cert_string(cert_buffer, X509.FORMAT_PEM)
    pub_key = cert.get_pubkey()
    rsa_key = pub_key.get_rsa()

    ReadRSA = RSA.load_key('private.key')

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], 10009))

    while (continua == True):

        order = raw_input("Next Order:")
        orders = order.split(" ")
        send_data(sock, orders[0])

        if (orders[0] == "DIRSEARCH"):
            send_data(sock, orders[1])
            print recv_data(sock)

        if (orders[0] == "DOWNLOAD"):
            send_data(sock, orders[1])
            receive_file_contents(orders[1], sock, ReadRSA)

        if (orders[0] == "UPLOAD"):
            send_data(sock, orders[1])
            send_file_contents(orders[1], sock, rsa_key)

        if (orders[0] == "CLOSE"):
            continua = False

    return
Exemple #50
0
    def to_template(self):
        """ Dictionary used to create configuration file related to the node
        :return     Dictionnary of configuration parameters
        """
        cert = X509.load_cert_string(str(self.cert))
        conf = {
            'id': str(self.id),
            'name': self.name,
            'subject': cert.get_subject().as_text(),
            'issuer': cert.get_issuer().as_text(),
            'status': self.status,
            'validfrom': str(cert.get_not_before()),
            'validtill': str(cert.get_not_after()),
            'is_vulture_ca': self.is_vulture_ca,
            'is_ca': self.is_ca,
            'is_external': self.is_external,
            'crl': self.crl,
            'crl_uri': self.crl_uri
        }

        return conf
Exemple #51
0
    def scan(self, data, file, options, expire_at):
        type = options.get('type', '')

        if type == 'der':
            cert = X509.load_cert_der_string(data)
        else:
            cert = X509.load_cert_string(data)

        self.event['issuer'] = cert.get_issuer().as_text()
        self.event['subject'] = cert.get_subject().as_text()
        self.event['serial_number'] = str(cert.get_serial_number())
        self.event['fingerprint'] = cert.get_fingerprint()
        self.event['version'] = cert.get_version()
        self.event['not_after'] = int(
            cert.get_not_after().get_datetime().strftime('%s'))
        self.event['not_before'] = int(
            cert.get_not_before().get_datetime().strftime('%s'))
        if self.event['not_after'] < time.time():
            self.event['expired'] = True
        else:
            self.event['expired'] = False
Exemple #52
0
    def _generate(self, password):
        required_generators = set()

        for cred, generator in Credentials.GENERATORS.iteritems():
            if cred not in self._credentials:
                required_generators.add(generator)
                logger.warning(
                    'Credential "%s" is missing and will be generated', cred)
            elif 'BEGIN CERTIFICATE' in self._credentials[cred]:
                cert = X509.load_cert_string(self._credentials[cred])
                expiration = cert.get_not_after().get_datetime()
                now = datetime.now(expiration.tzinfo)
                diff = (expiration - now).days

                if expiration <= now:
                    logger.error(
                        'Credential "%s" is expired! All related credentials will be regenerated',
                        cred)

                    required_generators.add(generator)
                elif diff < 7:
                    logger.error('%s will expire in %d days', cred, diff)
                elif diff < 90:
                    logger.warning('%s will expire in %d days', cred, diff)
                else:
                    logger.debug('Credential "%s" will expire in %d days',
                                 cred, diff)
            else:
                logger.debug('Credential "%s" exists', cred)

        for generator in required_generators:
            new_creds = generator()
            self._credentials.update(new_creds)

        updated = bool(required_generators)

        if updated:
            self.save(password)

        return updated
Exemple #53
0
def validate_client_cert(sock, fp):
    """
    validating ssl fingerprint of client

    input:
        sock    socket holding connection to client
        fp      expected cert fingerprint

    output:
        true if cert fingerprint == fp

    """
    cert_der = sock.getpeercert(binary_form=True)
    print("cert_der=%s" % str(cert_der))

    if not cert_der:
        return False

    x509 = X509.load_cert_string(cert_der, X509.FORMAT_DER)
    cert_fingerprint = x509.get_fingerprint("sha1")

    return fp == cert_fingerprint
Exemple #54
0
def pem_cert_to_ssh_line(cert):
    """
    Converts a PEM formatted X509 certificate to a SSH2 public key line 
    usable in authorized_keys file.
    """
    def _encode_ssh(buffer):
        n = len(buffer)
        tmp = "" + chr((n >>24) & 0xff)
        tmp += chr((n >>16) & 0xff)
        tmp += chr((n >>8) & 0xff)
        tmp += chr((n) & 0xff)
        tmp += "\000" # remove length
        tmp += buffer[1:]
        return tmp

    crt = X509.load_cert_string(str(cert))
    rsa = crt.get_pubkey().get_rsa()
    key = "\000\000\000\007ssh-rsa"
    key += _encode_ssh(rsa.e[3:])
    key += _encode_ssh(rsa.n[3:])
 
    return "ssh-rsa %s %s" %(base64.b64encode(key), crt.get_ext('subjectAltName').get_value().split(":")[1] + " " + crt.get_subject().O)
Exemple #55
0
    def testImportSiteCertificate(self):
        trust = constants.TRUST_AUTHENTICITY
        cert = self._importAndFind(self.pemSite, trust)

        x509 = cert.asX509()

        x509Issuer = X509.load_cert_string(self.pemRoot)
        issuerPublicKey = x509Issuer.get_pubkey()
        self.assert_(x509.verify(issuerPublicKey))

        self.assert_(x509.as_pem()[:-1] == self.pemSite)
        self.assert_(x509.get_subject().CN == 'bugzilla.osafoundation.org')

        self.assert_(
            cert.fingerprint == '0xff8013055aae612ad79c347f06d1b83f93deb664L',
            cert.fingerprint)
        self.assert_(cert.trust == trust)
        self.assert_(cert.purpose == constants.PURPOSE_SERVER)
        self.assert_(cert.displayName == u'bugzilla.osafoundation.org')

        self.assertTrue(
            certificate.certificatePurpose(x509) == constants.PURPOSE_SERVER)
Exemple #56
0
    def _certificate_expiration_date(self, full_cert_path):
        """
        Attempts to read and return the expiration date of the certificate at the given
        path. If anything goes wrong, None is returned. This method should not be considered
        as any sort of validation on the certificate.

        :rtype: str or None
        """

        # This except block is pretty broad, but the intention of this method is really just to
        # help pretty up the UI by showing the expiration date if it can find it.
        try:
            f = open(full_cert_path, 'r')
            certificate = f.read()
            f.close()

            certificate_section = str(certificate[certificate.index('-----BEGIN CERTIFICATE'):])
            x509_cert = X509.load_cert_string(certificate_section)
            expiration_date = x509_cert.get_not_after()
            return str(expiration_date)
        except Exception:
            return None
Exemple #57
0
 def verify(self, servernames, certdata):
     '''Verify the cookie against the specified server ID list and
     certificate data.'''
     now = datetime.now(tzutc())
     # Check cookie expiration
     if self.expires < now:
         raise ScopeCookieExpired('Cookie expired on %s' % self.expires)
     # Check that one of our server names matches a name in the cookie
     if len(set(servernames) & set(self.servers)) == 0:
         raise ScopeError('Cookie does not contain matching server name')
     # Split certdata into individual certificates
     begin = '-----BEGIN CERTIFICATE-----\n'
     end = '-----END CERTIFICATE-----'  # no trailing newline
     certdata = re.findall(begin + BASE64_RE + end, certdata)
     # Load certificates
     certs = [X509.load_cert_string(cd) for cd in certdata]
     # Find a certificate that verifies the signature
     failure = "Couldn't validate scope cookie signature"
     for cert in certs:
         # Check the signature
         key = cert.get_pubkey()
         key.verify_init()
         key.verify_update(self.data)
         if key.verify_final(self.signature) != 1:
             # Signature does not match certificate
             continue
         # Signature valid; now check the certificate
         if cert.verify() != 1:
             failure = 'Scope cookie signed by invalid certificate'
             continue
         if cert.get_not_before().get_datetime() > now:
             failure = 'Scope cookie signed by postdated certificate'
             continue
         if cert.get_not_after().get_datetime() < now:
             failure = 'Scope cookie signed by expired certificate'
             continue
         # We have a match
         return
     raise ScopeError(failure)
Exemple #58
0
	def test_unmap_user_certificate(self, udm, ucr):
		certificate_binary = subprocess.check_output(['openssl', 'x509', '-inform', 'pem', '-in', '/etc/univention/ssl/%(hostname)s/cert.pem' % ucr, '-outform', 'der', '-out', '-'])
		x509 = X509.load_cert_string(certificate_binary, X509.FORMAT_DER)
		certificateSerial = x509.get_serial_number()
		certificate = base64.b64encode(certificate_binary).encode('ASCII')
		certificate_ldap = {
			'userCertificate': certificate,
			'certificateIssuerCommonName': ucr['ssl/common'],
			'certificateIssuerCountry': ucr['ssl/country'],
			'certificateIssuerLocation': ucr['ssl/locality'],
			'certificateIssuerMail': ucr['ssl/email'],
			'certificateIssuerOrganisation': ucr['ssl/organization'],
			'certificateIssuerOrganisationalUnit': ucr['ssl/organizationalunit'],
			'certificateIssuerState': ucr['ssl/state'],
			'certificateSerial': str(certificateSerial),
			'certificateSubjectCommonName': '%(hostname)s.%(domainname)s' % ucr,
			'certificateSubjectCountry': ucr['ssl/country'],
			'certificateSubjectLocation': ucr['ssl/locality'],
			'certificateSubjectMail': ucr['ssl/email'],
			'certificateSubjectOrganisation': ucr['ssl/organization'],
			'certificateSubjectOrganisationalUnit': ucr['ssl/organizationalunit'],
			'certificateSubjectState': ucr['ssl/state'],
			'certificateVersion': '2',
		}
		try:
			from dateutil import parser
		except ImportError:
			pass
		else:
			dates = subprocess.check_output('openssl x509 -startdate -enddate -noout < /etc/univention/ssl/%(hostname)s/cert.pem' % ucr, shell=True)
			dates = dict(x.split('=', 1) for x in dates.decode('UTF-8').splitlines())
			certificate_ldap.update({
				'certificateDateNotAfter': parser.parse(dates['notAfter']).strftime('%Y-%m-%d'),
				'certificateDateNotBefore': parser.parse(dates['notBefore']).strftime('%Y-%m-%d'),
			})
		user = udm.create_user()[0]
		udm.modify_object('users/user', dn=user, append_option=['pki'], userCertificate=certificate)
		udm.verify_udm_object('users/user', user, certificate_ldap)
def _get_socket(client, addr, secure=True, timeout=10):
    """
    return a socket. in case of ssl, verifies ccd server cert fingerprint
    matches the fingerprint given in config file

    input:
        addr        address tuple to connect to
        secure      use ssl. if True, the ccd server cert's fingerprint is
                    checked against fp in config
    output:
        socket_fd   socket that holds connection

    """
    cert_fingerprint = _get_socket.cert_fingerprint

    socket_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket_fd.settimeout(timeout)
    socket_fd.connect(addr)

    if secure and cert_fingerprint:
        logger.debug("connecting to %s via ssl.", str(addr))
        socket_fd = ssl.wrap_socket(socket_fd,
                                    certfile=client._cert,
                                    keyfile=client._cert_key,
                                    ssl_version=client._ssl_version)

        cert_der = socket_fd.getpeercert(binary_form=True)
        x509 = X509.load_cert_string(cert_der, X509.FORMAT_DER)
        fp = x509.get_fingerprint("sha1")

        if not fp == cert_fingerprint:
            raise Exception("Invalid certificate %s" % fp)

        logger.debug("server cert has valid fingerprint (%s)", fp)
    else:
        logger.debug('ssl disabled')

    return socket_fd
Exemple #60
0
    def check_signature(self):
        if self.signature and self.data:
            certs = os.listdir(constants.CANDLEPIN_CA_CERT_DIR)
            # At least one certificate has to match
            for cert_name in certs:
                cert_file = None
                try:
                    cert_file = open(
                        constants.CANDLEPIN_CA_CERT_DIR + '/' + cert_name, 'r')
                    cert = X509.load_cert_string(cert_file.read())
                except (IOError, X509.X509Error):
                    continue
                finally:
                    if cert_file is not None:
                        cert_file.close()
                pubkey = cert.get_pubkey()
                pubkey.reset_context(md='sha256')
                pubkey.verify_init()

                pubkey.verify_update(self.data)
                if pubkey.verify_final(self.signature):
                    return True
        return False