Python ssl.PEM_cert_to_DER_cert() Examples

The following are 8 code examples of ssl.PEM_cert_to_DER_cert(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ssl , or try the search function .
Example #1
Source File: suppliers.py    From endpoints-management-python with Apache License 2.0 6 votes vote down vote up
def _extract_x509_certificates(x509_certificates):
    keys = []
    for kid, certificate in x509_certificates.iteritems():
        try:
            if certificate.startswith(jwk.PREFIX):
                # The certificate is PEM-encoded
                der = ssl.PEM_cert_to_DER_cert(certificate)
                key = jwk.der2rsa(der)
            else:
                key = jwk.import_rsa_key(certificate)
        except Exception as exception:
            raise UnauthenticatedException(u"Cannot load X.509 certificate",
                                           exception)
        rsa_key = jwk.RSAKey().load_key(key)
        rsa_key.kid = kid
        keys.append(rsa_key)
    return keys 
Example #2
Source File: xmppclient.py    From openduty with MIT License 6 votes vote down vote up
def verify_gtalk_cert(self, raw_cert):
        hosts = resolver.get_SRV(self.boundjid.server, 5222,
                                 self.dns_service,
                                 resolver=resolver.default_resolver())
        it_is_google = False
        for host, _ in hosts:
            if host.lower().find('google.com') > -1:
                it_is_google = True

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

        logging.error("invalid cert received for %s",
                      self.boundjid.server) 
Example #3
Source File: x509.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
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 #4
Source File: api_requestor.py    From shippo-python-client with MIT License 5 votes vote down vote up
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 Shippo, 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 shippo.config import verify_ssl_certs

        if verify_ssl_certs and not self._CERTIFICATE_VERIFIED:
            uri = urllib.parse.urlparse(shippo.config.api_base)
            try:
                certificate = ssl.get_server_certificate(
                    (uri.hostname, uri.port or 443))
                der_cert = ssl.PEM_cert_to_DER_cert(certificate)
            except socket.error as 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 ('APPENGINE_RUNTIME' in os.environ and
                        'Dev' in os.environ.get('SERVER_SOFTWARE', '')):
                    self._CERTIFICATE_VERIFIED = True
                    warnings.warn(
                        'We were unable to verify Shippo\'s SSL certificate '
                        'due to a bug in the Google App Engine development '
                        'server. Please alert us immediately at '
                        'suppgoshippo.compo.com if this message appears in your '
                        'production logs.')
                    return
                else:
                    raise

            self._CERTIFICATE_VERIFIED = certificate_blacklist.verify(
                uri.hostname, der_cert) 
Example #5
Source File: authentication.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def pair(clientsocket):
    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
    
    fpdiag = subprocess.Popen([PROGRAMDIR+"/fingerprints.py", myfp, devicefp], stdout=subprocess.PIPE)
    (vout, verr) = fpdiag.communicate()

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

    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))
        print "Successfully paired the Device!"

    else:
        print "Failed to pair Device." 
Example #6
Source File: iosCertTrustManager.py    From iOSSecAudit with GNU General Public License v3.0 5 votes vote down vote up
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 #7
Source File: pair.py    From deskcon-desktop with GNU General Public License v3.0 4 votes vote down vote up
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 #8
Source File: util.py    From pypowervm with Apache License 2.0 4 votes vote down vote up
def validate_certificate(host, port, certpath, certext):
    hostname = re.sub('[:.]', '_', host)
    cert_file = '%s%s%s' % (certpath, hostname, certext)
    try:
        with open(cert_file, 'r') as f:
            # Retrieve previously trusted certificate
            trusted_cert = ssl.PEM_cert_to_DER_cert(f.read())
    except Exception:
        # found no trusted certificate
        return False
    # Read current certificate from host
    conn = None
    try:
        # workaround for http://bugs.python.org/issue11811
        # should go back to using get_server_certificate when fixed
        # (Issue is resolved as of python 3.3.  Workaround still needed for
        # python 2.7 support.)
        #   rawcert = ssl.get_server_certificate((host, port))
        #   current_cert = ssl.PEM_cert_to_DER_cert(rawcert)
        conn = socket.create_connection((host, port))
        sock = ssl.wrap_socket(conn)
        current_cert = sock.getpeercert(True)
    except Exception:
        # couldn't get certificate from host
        return False
    finally:
        if conn is not None:
            conn.shutdown(socket.SHUT_RDWR)
            conn.close()
    # Verify certificate finger prints are the same
    if not (hashlib.sha1(trusted_cert).digest() ==
            hashlib.sha1(current_cert).digest()):
        return False
    # check certificate expiration
    try:
        cert = der_decoder.decode(current_cert,
                                  asn1Spec=rfc2459.Certificate())[0]
        tbs = cert.getComponentByName('tbsCertificate')
        validity = tbs.getComponentByName('validity')
        not_after = validity.getComponentByName('notAfter').getComponent()
        not_after = dt.datetime.strptime(str(not_after), '%y%m%d%H%M%SZ')
        if dt.datetime.utcnow() >= not_after:
            LOG.warning(_('Certificate has expired.'))
            return False
    except Exception:
        LOG.exception('error parsing cert for expiration check')
        return False
    return True