Example #1
0
    def testDERtoPEM(self):

        pem = open(SVN_PYTHON_ORG_ROOT_CERT, 'r').read()
        d1 = ssl.PEM_cert_to_DER_cert(pem)
        p2 = ssl.DER_cert_to_PEM_cert(d1)
        d2 = ssl.PEM_cert_to_DER_cert(p2)
        if (d1 != d2):
            raise support.TestFailed("PEM-to-DER or DER-to-PEM translation failed")
Example #2
0
    def create(self, snf_uuid, snf_token, mail, cn, vo, user_dn, cert=None):
        """Add a user in LDAP directory
        :param snf_uuid: (str) the Synnefo user UUID, part of LDAP user uid
        :param snf_token: (str) the Synnefo user token
        :param mail: (str) e-mail
        :param cn: (str) Human-readable name of the human
        :param vo: (str) Virtual organization this user is affiliated to
        :param user_dn: (str) the user DN, e.g. "/C=ORG/C=EXAMPLE/CN=Real name"
        :param cert: (str) user PEM certificate
        """
        add_record = [
            ('objectclass', [
                'person', 'organizationalperson', 'inetorgperson', 'pkiuser']),
            ('uid', [str(snf_uuid), ]),
            ('cn', [str(cn), ]),
            ('sn', [str(vo), ]),
            ('userpassword', [str(snf_token), ]),
            ('mail', [str(mail), ]),
            ('givenname', str(user_dn)),
            ('ou', ['users', ])
        ]
        dn = 'uid=%s,%s' % (str(snf_uuid), str(self.base_dn))
        self.con.add_s(dn, add_record)

        if cert:
            cert_der = ssl.PEM_cert_to_DER_cert(cert)
            mod_attrs = [(ldap.MOD_ADD, 'userCertificate;binary', cert_der)]
            self.con.modify_s(dn, mod_attrs)
Example #3
0
    def _check_ssl_cert(self):
        """Preflight the SSL certificate presented by the backend.

        This isn't 100% bulletproof, in that we're not actually validating the
        transport used to communicate with Ping++, merely that the first
        attempt to does not use a revoked certificate.

        Unfortunately the interface to OpenSSL doesn't make it easy to check
        the certificate before sending potentially sensitive data on the wire.
        This approach raises the bar for an attacker significantly."""

        from pingpp import verify_ssl_certs

        if verify_ssl_certs and not self._CERTIFICATE_VERIFIED:
            uri = urlparse.urlparse(pingpp.api_base)
            try:
                certificate = ssl.get_server_certificate(
                    (uri.hostname, uri.port or 443), ssl_version=3)
                der_cert = ssl.PEM_cert_to_DER_cert(certificate)
            except socket.error, e:
                raise error.APIConnectionError(e)
            except TypeError:
                # The Google App Engine development server blocks the C socket
                # module which causes a type error when using the SSL library
                if util.is_appengine_dev():
                    self._CERTIFICATE_VERIFIED = True
                    warnings.warn(
                        'We were unable to verify Ping++\'s SSL certificate '
                        'due to a bug in the Google App Engine development '
                        'server. Please alert us immediately at '
                        '[email protected] if this message appears in your '
                        'production logs.')
                    return
                else:
                    raise
    def get_cert_info(self, hostname, port=443, cert_file_name='cert.der'):

        f = open(str(cert_file_name), 'wb')
        certificate = ssl.get_server_certificate((hostname, port))
        f.write(ssl.PEM_cert_to_DER_cert(certificate))

        with open(str(cert_file_name), "rb") as f:
            certificate = Certificate.load(f.read())

        modulus = certificate.public_key.native["public_key"]["modulus"]
        pub_exp = certificate.public_key.native["public_key"][
            "public_exponent"]
        sig_algorithm = certificate.signature_algo
        try:
            cert_issuer_country = certificate.issuer.native["country_name"]
        except:
            cert_issuer_country = "Empty"
        try:
            cert_issuer_name = certificate.issuer.native["organization_name"]
        except:
            cert_issuer_name = "Empty"
        try:
            cert_issuer_common_name = certificate.issuer.native["common_name"]
        except:
            cert_issuer_common_name = "Empty"
        self_signed = certificate.self_signed
        hash_algo = certificate.hash_algo
        domains = certificate.valid_domains

        return ('{0:02x}'.format(modulus), pub_exp, sig_algorithm,
                cert_issuer_country, cert_issuer_name, cert_issuer_common_name,
                self_signed, hash_algo, domains)
Example #5
0
def getCertNames(ip, port, verbose=False):
    setdefaulttimeout(5)
    try:
        certstring = ssl.get_server_certificate((ip, port))
    except (error, timeout) as err:
        if verbose:
            print("No connection: {0}".format(err))
        return None
    der_cert = ssl.PEM_cert_to_DER_cert(certstring)
    cert = x509.load_der_x509_certificate(der_cert, default_backend())

    names = []

    cn = cert.subject.get_attributes_for_oid(x509.OID_COMMON_NAME)[0].value
    names.append(cn)

    try:
        sans = cert.extensions.get_extension_for_oid(
            x509.OID_SUBJECT_ALTERNATIVE_NAME).value.get_values_for_type(
                x509.DNSName)
    except:
        sans = None

    if sans and len(sans):
        for san in sans:
            names.append(san)
            #print ip, san

    return names
Example #6
0
 def get_public_key_from_pem(self, pem_cert):
     der = ssl.PEM_cert_to_DER_cert(pem_cert)
     cert = DerSequence()
     cert.decode(der)
     tbsCertificate = DerSequence()
     tbsCertificate.decode(cert[0])
     return tbsCertificate[6]
 def test_revoked_cert_is_revoked(self):
     hostname = "revoked.stripe.com"
     cert = ssl.get_server_certificate((hostname, 444))
     der_cert = ssl.PEM_cert_to_DER_cert(cert)
     self.assertRaises(APIError,
                       lambda: certificate_blacklist.verify(
                           hostname, der_cert))
Example #8
0
def init():
    if os.environ.get('XDG_CONFIG_HOME') is None or os.environ.get('XDG_CONFIG_HOME') == '':
        XDG_CONFIG_HOME = os.path.join(os.path.expanduser('~'), '.config')
    else:
        XDG_CONFIG_HOME = os.environ.get('XDG_CONFIG_HOME')

    CONF_DIR_PATH = os.path.join(XDG_CONFIG_HOME, 'an2linux')
    CONF_FILE_PATH = os.path.join(CONF_DIR_PATH, 'config')

    CERTIFICATE_PATH = os.path.join(CONF_DIR_PATH, 'certificate.pem')
    RSA_PRIVATE_KEY_PATH = os.path.join(CONF_DIR_PATH, 'rsakey.pem')
    AUTHORIZED_CERTS_PATH = os.path.join(CONF_DIR_PATH, 'authorized_certs')
    DHPARAM_PATH = os.path.join(CONF_DIR_PATH, 'dhparam.pem')

    if not os.path.exists(CONF_DIR_PATH):
        os.makedirs(CONF_DIR_PATH)

    if not os.path.isfile(CERTIFICATE_PATH) or not os.path.isfile(RSA_PRIVATE_KEY_PATH):
        generate_server_private_key_and_certificate(CERTIFICATE_PATH, RSA_PRIVATE_KEY_PATH)
    else:
        # test if valid private key / certificate
        try:
            ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2).load_cert_chain(CERTIFICATE_PATH,
                                                                          RSA_PRIVATE_KEY_PATH)
            ssl.PEM_cert_to_DER_cert(open(CERTIFICATE_PATH, 'r').read())
        except (ssl.SSLError, ValueError) as e:
            logging.error('Something went wrong trying to load your private key and certificate: {}'.format(e))
            logging.error('Will generate new key overwriting old key and certificate')
            generate_server_private_key_and_certificate(CERTIFICATE_PATH, RSA_PRIVATE_KEY_PATH)

    return CONF_FILE_PATH, CERTIFICATE_PATH, RSA_PRIVATE_KEY_PATH, AUTHORIZED_CERTS_PATH, DHPARAM_PATH
    def ssl_invalid_cert(self, raw_cert):
        """Handle an invalid certificate from the Jabber server
           This may happen if the domain is using Google Apps
           for their XMPP server and the XMPP server."""
        hosts = resolver.get_SRV(self.boundjid.server,
                                 5222,
                                 'xmpp-client',
                                 resolver=resolver.default_resolver())

        domain_uses_google = False
        for host, _ in hosts:
            if host.lower()[-10:] == 'google.com':
                domain_uses_google = True

        if domain_uses_google:
            try:
                if cert.verify('talk.google.com',
                               ssl.PEM_cert_to_DER_cert(raw_cert)):
                    logging.debug('Google certificate found for %s',
                                  self.boundjid.server)
                    return
            except cert.CertificateError:
                pass

        logging.error("Invalid certificate received for %s",
                      self.boundjid.server)
        self.disconnect()
Example #10
0
def cert_PEM_to_hash(cert):
    """Given a certificate in PEM format, return it's hash as string"""
    cert_der = ssl.PEM_cert_to_DER_cert(cert)
    hash = hashlib.sha1()
    hash.update(cert_der)
    digest = hash.digest()
    digest_string = "".join([binascii.b2a_hex(b) for b in bytes(digest)])
    return digest_string
def pemFileHash(fname):
    """ Return SHA256 hash of PEM cert in hex """
    with file(fname) as certFile:
        pemData = certFile.read()
        derData = ssl.PEM_cert_to_DER_cert(pemData)
        certDigest = sha256(derData).hexdigest()

        return certDigest
Example #12
0
 def invalid_cert(self, pem_cert):
     der_cert = ssl.PEM_cert_to_DER_cert(pem_cert)
     try:
         cert.verify('talk.google.com', der_cert)
         print "CERT: Found GTalk certificate"
     except cert.CertificateError as err:
         print err.message, " : ", traceback.format_exc()
         self.disconnect(send_close=False)
Example #13
0
 def invalid_cert(self, pem_cert):
     der_cert = ssl.PEM_cert_to_DER_cert(pem_cert)
     try:
         cert.verify('talk.google.com', der_cert)
         logging.debug("CERT: Found GTalk certificate")
     except cert.CertificateError as err:
         logging.error(err.message)
         self.disconnect()
 def load_PEMfile(self, certificate_path):
     """Load a certificate from a file in PEM format
     """
     self._init_data()
     self._filepath = certificate_path
     with open(self._filepath, "r") as inputFile:
         PEMdata = inputFile.read()
     # convert to binary (DER format)
     self._data = ssl.PEM_cert_to_DER_cert(PEMdata)
Example #15
0
def cert_to_public_rsa_key(pem):
    DER = ssl.PEM_cert_to_DER_cert(pem)
    cert = DerSequence()
    cert.decode(DER)
    tbsCertificate = DerSequence()
    tbsCertificate.decode(cert[0])
    subjectPublicKeyInfo = tbsCertificate[6]
    rsa_key = RSA.importKey(subjectPublicKeyInfo)
    return rsa_key
 def verify_cert(self, pem_cert):
     """Verify that certificate originates from Google."""
     der_cert = ssl.PEM_cert_to_DER_cert(pem_cert)
     try:
         cert.verify('talk.google.com', der_cert)
         logging.debug('Found Hangouts certificate.')
     except cert.CertificateError as err:
         logging.error(err)
         self.disconnect(send_close=False)
Example #17
0
    def convertPEMcertificateToDER(self, certificate):
        ''' Converting PEM certificate to DER '''

        if certificate is None:
            return None
        if not self.isPEM(certificate):
            return certificate
        der = ssl.PEM_cert_to_DER_cert(certificate)
        return der
    def grab_file(self, mconfig, filepath, filename):

        file_mod_time = os.stat(
            os.path.join(filepath, filename) +
            GlobalLabelParameters.P12_PREFIX).st_mtime

        if filename not in self.filecache:

            p12 = crypto.load_pkcs12(
                open(
                    os.path.join(filepath, filename) +
                    GlobalLabelParameters.P12_PREFIX, 'rb').read(),
                mconfig.key_password)
            cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                               p12.get_certificate())
            der_cert_string = base64.b64encode(
                ssl.PEM_cert_to_DER_cert(cert_str.decode("utf-8")))
            private_key = crypto.dump_privatekey(
                crypto.FILETYPE_PEM, p12.get_privatekey()).decode("utf-8")

            self.filecache.setdefault(str(filename),
                                      []).append(der_cert_string)
            self.filecache.setdefault(str(filename), []).append(private_key)
            self.filecache.setdefault(str(filename), []).append(file_mod_time)

        if file_mod_time != self.filecache[filename][2]:
            p12 = crypto.load_pkcs12(
                open(
                    os.path.join(filepath, filename) +
                    GlobalLabelParameters.P12_PREFIX, 'rb').read(),
                mconfig.key_password)
            cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                               p12.get_certificate())
            der_cert_string = base64.b64encode(
                ssl.PEM_cert_to_DER_cert(cert_str.decode("utf-8")))
            private_key = crypto.dump_privatekey(
                crypto.FILETYPE_PEM, p12.get_privatekey()).decode("utf-8")

            self.filecache.setdefault(str(filename),
                                      []).append(der_cert_string)
            self.filecache.setdefault(str(filename), []).append(private_key)
            self.filecache.setdefault(str(filename), []).append(file_mod_time)

        return self.filecache[filename]
Example #19
0
	def __init__(self,addr,cert=None):
		self.addr=addr
		self.username=None
		self.password=None
		if cert is None:
			self.cert=None
		elif type(cert)==bytes:
			self.cert=cert
		elif type(cert)==str:
			if cert.startswith('-----BEGIN CERTIFICATE-----'):
				self.cert=ssl.PEM_cert_to_DER_cert(cert)
			else:
				with open(cert,'rb') as f:
					cert=f.read()
				if cert.startswith(b'-----BEGIN CERTIFICATE-----'):
					cert=ssl.PEM_cert_to_DER_cert(cert.decode('ascii'))
				self.cert=cert
		else:
			raise ValueError('Unknown Certificate type')
Example #20
0
    def ssl_invalid_cert(self, pem_cert):
        # Source: https://github.com/poezio/slixmpp/blob/master/examples/gtalk_custom_domain.py

        der_cert = ssl.PEM_cert_to_DER_cert(pem_cert)
        try:
            cert.verify('talk.google.com', der_cert)
            self.logger.info("found GTalk certificate")
        except cert.CertificateError as err:
            self.logger.error(err.message)
            self.disconnect(send_close=False)
Example #21
0
def compute_chain_hashes(chainp):
    result = []
    for p in permutations(chainp):
        servercert = ssl.PEM_cert_to_DER_cert(p[0])
        
        serverhash = SHA256.new(servercert).hexdigest()
        chainhashes = map(lambda x: MD5.new(x).hexdigest(), p[1:])
        concatenated = ''.join(chainhashes).lower()
        result.append(SHA256.new(unhexlify(serverhash + concatenated)).digest())
    return result 
Example #22
0
 def __init__(self, path):
     self.path = path
     if os.path.isfile(path):
         self.key = xmlsec.Key.from_file(path, xmlsec.KeyFormat.CERT_PEM)
         pem_content = open(path, 'rb').read()
     else:
         self.key = xmlsec.Key.from_memory(path, xmlsec.KeyFormat.CERT_PEM)
         pem_content = path
     h = hashlib.sha1()
     h.update(ssl.PEM_cert_to_DER_cert(pem_content))
     self.fingerprint = h.hexdigest().zfill(40)
Example #23
0
def get_pubkey(pem):
    """ Extracts public key from x08 pem. """
    der = ssl.PEM_cert_to_DER_cert(pem)

    # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
    cert = DerSequence()
    cert.decode(der)
    tbsCertificate = DerSequence()
    tbsCertificate.decode(cert[0])
    subjectPublicKeyInfo = tbsCertificate[6]

    return subjectPublicKeyInfo
Example #24
0
def get_certificate_from_file(certfile):
    cert = open(certfile, 'r').read()
    inpemcert = False
    prunedcert = ''
    for line in cert.split('\n'):
        if '-----BEGIN CERTIFICATE-----' in line:
            inpemcert = True
        if inpemcert:
            prunedcert += line
        if '-----END CERTIFICATE-----' in line:
            break
    return ssl.PEM_cert_to_DER_cert(prunedcert)
Example #25
0
 def proxyConnect(self, host, port, path, cadata=None):
     if not cadata:
         cadata = self.server_cert
     dercert = ssl.PEM_cert_to_DER_cert(cadata)
     c = httplib.HTTPSConnection(
         self.squid.ip_address,
         3128,
         context=ssl.create_default_context(cadata=dercert))
     c.set_tunnel(host, port)
     #c.putheader('Host',"squid-webtest")
     c.request("GET", path)
     return c.getresponse()
Example #26
0
def pair_client(clientsocket, q):
    print "wants to pair"
    mycert = open(os.path.join(configmanager.keydir, "server.crt"), "r").read()
    secure_port = str(configmanager.secure_port)

    myder_cert = ssl.PEM_cert_to_DER_cert(mycert)
    m = hashlib.sha256(myder_cert)
    myfp = m.hexdigest().upper()
    myfp = " ".join(myfp[i:i + 4] for i in range(0, len(myfp), 4))
    print "\nMy SHA256: " + myfp
    #send my certiuficate
    clientsocket.sendall(myder_cert.encode('base64'))

    #receive client Certificate
    clientcert = clientsocket.recv(2048)

    m = hashlib.sha256(clientcert)
    devicefp = m.hexdigest().upper()
    devicefp = " ".join(devicefp[i:i + 4] for i in range(0, len(devicefp), 4))
    print "\nClient SHA256: " + devicefp

    if (q):  #GUI
        q.put([myfp, devicefp])
        vout = q.get(True)
    else:  #CMDLine only
        vout = raw_input("Do they match?(yes/no)\n")

    if (vout.strip().lower() == "yes"):
        clientsocket.sendall(secure_port + "\n")
    else:
        clientsocket.sendall("0\n")
        pass

    print "wait for Device..."
    ack = clientsocket.recv(2)

    if (ack == "OK"):
        #save pub key
        with open(os.path.join(configmanager.keydir, "cas.pem"),
                  'a') as the_file:
            the_file.write(ssl.DER_cert_to_PEM_cert(clientcert))

        if (q):
            q.put(1)

        restart_server()
        print "Successfully paired the Device!"

    else:
        if (q):
            q.put(0)
        print "Failed to pair Device."
Example #27
0
def extract_public_key_from_certificate(x509_certificate):
    """Extracts the PEM public key from an x509 certificate."""
    der_certificate_string = ssl.PEM_cert_to_DER_cert(x509_certificate)

    # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
    der_certificate = asn1.DerSequence()
    der_certificate.decode(der_certificate_string)
    tbs_certification = asn1.DerSequence()  # To Be Signed certificate
    tbs_certification.decode(der_certificate[0])

    subject_public_key_info = tbs_certification[6]

    return subject_public_key_info
Example #28
0
def PEM_to_header(pems, cert_var, cert_length_var, output, full_chain,
                  keep_dupes):
    """Combine a collection of PEM format certificates into a single C header with the
    combined cert data in binary DER format.  Pems should be a list of strings with
    each cert PEM or chain of PEM certs, cert_var controls the name of the cert data
    variable in the output header, cert_length_var controls the name of the cert
    data length variable/define, output is the output file (which must be open for
    writing), and full_chain is a boolean that indicates if each cert chain should include
    the full chain or just the root/last cert.  Keep_dupes is a boolean to
    indicate if duplicate certificates should be left intact (true) or removed (false).
    """
    cert_der = bytearray()
    cert_description = ''
    processed_certs = set()
    for p in pems:
        certs = PEM_split(p)
        if full_chain:
            # Go through each cert in the chain and convert to DER format.
            for cert_pem in certs:
                # Skip duplicate certs where required.
                if not keep_dupes and cert_pem in processed_certs:
                    continue
                processed_certs.add(cert_pem)
                cert_description += '    {0}\n'.format(
                    PEM_description(cert_pem))
                cert_der.extend(bytearray(ssl.PEM_cert_to_DER_cert(cert_pem)))
        else:
            # Otherwise just grab the last cert in the chain (the root) and convert.
            cert_pem = certs[-1]
            # Skip duplicate certs where required.
            if not keep_dupes and cert_pem in processed_certs:
                continue
            processed_certs.add(cert_pem)
            cert_description += '    {0}\n'.format(PEM_description(cert_pem))
            cert_der.extend(bytearray(ssl.PEM_cert_to_DER_cert(cert_pem)))
    # Save DER cert data as a C style header.
    cert_to_header(cert_der, output, cert_var, cert_length_var,
                   cert_description)
    click.echo('Wrote {0}'.format(output.name))
Example #29
0
    def fetch_certificate_info(self):
        filecache = {}
        filename = 'testrest'

        p12 = crypto.load_pkcs12(open(os.path.join(os.getcwd(), "samples/authentication/Resources", filename) + ".p12", 'rb').read(), self.merchant_id)

        cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())
        der_cert_string = base64.b64encode(ssl.PEM_cert_to_DER_cert(cert_str.decode("utf-8")))
        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey()).decode("utf-8")

        filecache.setdefault(str(filename), []).append(der_cert_string)
        filecache.setdefault(str(filename), []).append(private_key)

        return filecache[filename]
Example #30
0
    def _ValidateCertificateHostname(self, cert, bincert, hostname):
        hosts = self._GetValidHostsForCert(cert)
        for host in hosts:
            host_re = host.replace('.', '\.').replace('*', '[^.]*')
            if re.search('^%s$' % (host_re,), hostname, re.I):
                return True

        # If we cannot validate against the hostname, try against the
        # KES certificate.
        binary_kes_cert = ssl.PEM_cert_to_DER_cert(_KES_CERT)
        if binary_kes_cert == bincert:
            return True

        return False