Python ssl.DER_cert_to_PEM_cert() Examples

The following are 15 code examples of ssl.DER_cert_to_PEM_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: ca_certs_locater.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _read_ssl_default_ca_certs():
    # it's not guaranteed to return PEM formatted certs when `binary_form` is False
    der_certs = ssl.create_default_context().get_ca_certs(binary_form=True)
    pem_certs = [ssl.DER_cert_to_PEM_cert(der_cert_bytes) for der_cert_bytes in der_certs]
    return '\n'.join(pem_certs) 
Example #2
Source File: ca_certs_locater.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _read_ssl_default_ca_certs():
    # it's not guaranteed to return PEM formatted certs when `binary_form` is False
    der_certs = ssl.create_default_context().get_ca_certs(binary_form=True)
    pem_certs = [ssl.DER_cert_to_PEM_cert(der_cert_bytes) for der_cert_bytes in der_certs]
    return '\n'.join(pem_certs) 
Example #3
Source File: interface.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def get_socket(self):
        if self.use_ssl:
            cert_path = os.path.join( self.config.path, 'certs', self.host)
            if not os.path.exists(cert_path):
                is_new = True
                s = self.get_simple_socket()
                if s is None:
                    return
                # try with CA first
                try:
                    s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True)
                except ssl.SSLError, e:
                    s = None
                if s and self.check_host_name(s.getpeercert(), self.host):
                    print_error("SSL certificate signed by CA:", self.host)
                    return s

                # get server certificate.
                # Do not use ssl.get_server_certificate because it does not work with proxy
                s = self.get_simple_socket()
                try:
                    s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_NONE, ca_certs=None)
                except ssl.SSLError, e:
                    print_error("SSL error retrieving SSL certificate:", self.host, e)
                    return

                dercert = s.getpeercert(True)
                s.close()
                cert = ssl.DER_cert_to_PEM_cert(dercert)
                # workaround android bug
                cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert)
                temporary_path = cert_path + '.temp'
                with open(temporary_path,"w") as f:
                    f.write(cert) 
Example #4
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 #5
Source File: sni-scanner.py    From Brainfuck-Tunnel with MIT License 5 votes vote down vote up
def main():
    log('Type hostname to scan that hostname (example: goo.gl fb.me etc)')
    log('Type exit to exit\n')

    host = str('74.125.24.100')
    port = int('443')

    while True:
        server_name_indications = app.str_input(':: ', newline=True)
        server_name_indications = app.filter_array(re.sub(r'\s+', ' ', server_name_indications).split(' '))

        if len(server_name_indications) and server_name_indications[0] == 'exit':
            break

        for server_name_indication in server_name_indications:
            try:
                if server_name_indication == 'exit': print(':: exit'); return
                socket_tunnel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                socket_tunnel.settimeout(3)
                log('Connecting to {host} port {port}'.format(host=host, port=port))
                socket_tunnel.connect((host, port))
                log('Server name indication: {server_hostname}'.format(server_hostname=server_name_indication))
                socket_tunnel = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2).wrap_socket(socket_tunnel, server_hostname=server_name_indication, do_handshake_on_connect=True)
                certificate = ssl.DER_cert_to_PEM_cert(socket_tunnel.getpeercert(True)).splitlines()
                certificate = '\n'.join(certificate[:13] + certificate[-13:])
                log('Certificate: \n\n{}\n'.format(certificate))
                log('Connection established')
                log('[Y1]Connected', status_color='[Y1]')
            except socket.timeout:
                log('[R1]Connection timeout', status_color='[R1]')
            except socket.error:
                log('[R1]Connection closed', status_color='[R1]')
            finally:
                socket_tunnel.close(); print() 
Example #6
Source File: server_tunnel.py    From Brainfuck-Tunnel with MIT License 5 votes vote down vote up
def certificate(self):
        self.log('Certificate:\n\n{certificate}'.format(certificate=ssl.DER_cert_to_PEM_cert(self.socket_tunnel.getpeercert(True)))) 
Example #7
Source File: iosCertTrustManager.py    From iOSSecAudit with GNU General Public License v3.0 5 votes vote down vote up
def save_PEMfile(self, certificate_path):
        """Save a certificate to a file in PEM format
        """
        self._filepath = certificate_path
        # convert to text (PEM format)
        PEMdata = ssl.DER_cert_to_PEM_cert(self._data)
        with open(self._filepath, "w") as output_file:
            output_file.write(PEMdata) 
Example #8
Source File: ca_certs_locater.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _read_ssl_default_ca_certs():
    # it's not guaranteed to return PEM formatted certs when `binary_form` is False
    der_certs = ssl.create_default_context().get_ca_certs(binary_form=True)
    pem_certs = [ssl.DER_cert_to_PEM_cert(der_cert_bytes) for der_cert_bytes in der_certs]
    return '\n'.join(pem_certs) 
Example #9
Source File: xmlstream.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def _cert_expiration(self, event):
        """Schedule an event for when the TLS certificate expires."""

        if not self.use_tls and not self.use_ssl:
            return

        if not self._der_cert:
            log.warn("TLS or SSL was enabled, but no certificate was found.")
            return

        def restart():
            if not self.event_handled('ssl_expired_cert'):
                log.warn("The server certificate has expired. Restarting.")
                self.reconnect()
            else:
                pem_cert = ssl.DER_cert_to_PEM_cert(self._der_cert)
                self.event('ssl_expired_cert', pem_cert)

        cert_ttl = cert.get_ttl(self._der_cert)
        if cert_ttl is None:
            return

        if cert_ttl.days < 0:
            log.warn('CERT: Certificate has expired.')
            restart()

        try:
            total_seconds = cert_ttl.total_seconds()
        except AttributeError:
            # for Python < 2.7
            total_seconds = (cert_ttl.microseconds + (cert_ttl.seconds + cert_ttl.days * 24 * 3600) * 10**6) / 10**6

        log.info('CERT: Time until certificate expiration: %s' % cert_ttl)
        self.schedule('Certificate Expiration',
                      total_seconds,
                      restart) 
Example #10
Source File: openssl_wrap.py    From XX-Net-mini with GNU General Public License v3.0 5 votes vote down vote up
def from_der(klass, der):
        pem = ssl.DER_cert_to_PEM_cert(der)
        return klass.from_pem(pem) 
Example #11
Source File: utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download_cert(filepath, host, raw=False):
    host = urlparse(host).hostname or host
    context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE

    for _ in range(20):
        try:
            with closing(socket.create_connection((host, 443))) as sock:
                with closing(context.wrap_socket(sock, server_hostname=host)) as secure_sock:
                    cert = secure_sock.getpeercert(binary_form=True)
        except Exception:  # no cov
            time.sleep(3)
        else:
            break
    else:  # no cov
        raise Exception('Unable to connect to {}'.format(host))

    if raw:
        with open(filepath, 'wb') as f:
            f.write(cert)
    else:
        cert = ssl.DER_cert_to_PEM_cert(cert)
        with open(filepath, 'w') as f:
            f.write(cert) 
Example #12
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 #13
Source File: builtin.py    From cheroot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_environ(self, sock):
        """Create WSGI environ entries to be merged into each request."""
        cipher = sock.cipher()
        ssl_environ = {
            'wsgi.url_scheme': 'https',
            'HTTPS': 'on',
            'SSL_PROTOCOL': cipher[1],
            'SSL_CIPHER': cipher[0],
            'SSL_CIPHER_EXPORT': '',
            'SSL_CIPHER_USEKEYSIZE': cipher[2],
            'SSL_VERSION_INTERFACE': '%s Python/%s' % (
                HTTPServer.version, sys.version,
            ),
            'SSL_VERSION_LIBRARY': ssl.OPENSSL_VERSION,
            'SSL_CLIENT_VERIFY': 'NONE',
            # 'NONE' - client did not provide a cert (overriden below)
        }

        # Python 3.3+
        with suppress(AttributeError):
            compression = sock.compression()
            if compression is not None:
                ssl_environ['SSL_COMPRESS_METHOD'] = compression

        # Python 3.6+
        with suppress(AttributeError):
            ssl_environ['SSL_SESSION_ID'] = sock.session.id.hex()
        with suppress(AttributeError):
            target_cipher = cipher[:2]
            for cip in sock.context.get_ciphers():
                if target_cipher == (cip['name'], cip['protocol']):
                    ssl_environ['SSL_CIPHER_ALGKEYSIZE'] = cip['alg_bits']
                    break

        # Python 3.7+ sni_callback
        with suppress(AttributeError):
            ssl_environ['SSL_TLS_SNI'] = sock.sni

        if self.context and self.context.verify_mode != ssl.CERT_NONE:
            client_cert = sock.getpeercert()
            if client_cert:
                # builtin ssl **ALWAYS** validates client certificates
                # and terminates the connection on failure
                ssl_environ['SSL_CLIENT_VERIFY'] = 'SUCCESS'
                ssl_environ.update(
                    self._make_env_cert_dict('SSL_CLIENT', client_cert),
                )
                ssl_environ['SSL_CLIENT_CERT'] = ssl.DER_cert_to_PEM_cert(
                    sock.getpeercert(binary_form=True),
                ).strip()

        ssl_environ.update(self._server_env)

        # not supplied by the Python standard library (as of 3.8)
        # - SSL_SESSION_RESUMED
        # - SSL_SECURE_RENEG
        # - SSL_CLIENT_CERT_CHAIN_n
        # - SRP_USER
        # - SRP_USERINFO

        return ssl_environ 
Example #14
Source File: ssl_tools.py    From DeepPavlov with Apache License 2.0 4 votes vote down vote up
def verify_certs_chain(certs_chain: List[crypto.X509], amazon_cert: crypto.X509) -> bool:
    """Verifies if Amazon and additional certificates creates chain of trust to a root CA.

    Args:
        certs_chain: List of pycrypto X509 intermediate certificates from signature chain URL.
        amazon_cert: Pycrypto X509 Amazon certificate.

    Returns:
        result: True if verification was successful, False if not.
    """
    store = crypto.X509Store()

    # add certificates from Amazon provided certs chain
    for cert in certs_chain:
        store.add_cert(cert)

    # add CA certificates
    default_verify_paths = ssl.get_default_verify_paths()

    default_verify_file = default_verify_paths.cafile
    default_verify_file = Path(default_verify_file).resolve() if default_verify_file else None

    default_verify_path = default_verify_paths.capath
    default_verify_path = Path(default_verify_path).resolve() if default_verify_path else None

    ca_files = [ca_file for ca_file in default_verify_path.iterdir()] if default_verify_path else []
    if default_verify_file:
        ca_files.append(default_verify_file)

    for ca_file in ca_files:
        ca_file: Path
        if ca_file.is_file():
            with ca_file.open('r', encoding='ascii') as crt_f:
                ca_certs_txt = crt_f.read()
                ca_certs = extract_certs(ca_certs_txt)
                for cert in ca_certs:
                    store.add_cert(cert)

    # add CA certificates (Windows)
    ssl_context = ssl.create_default_context()
    der_certs = ssl_context.get_ca_certs(binary_form=True)
    pem_certs = '\n'.join([ssl.DER_cert_to_PEM_cert(der_cert) for der_cert in der_certs])
    ca_certs = extract_certs(pem_certs)
    for ca_cert in ca_certs:
        store.add_cert(ca_cert)

    store_context = crypto.X509StoreContext(store, amazon_cert)

    try:
        store_context.verify_certificate()
        result = True
    except crypto.X509StoreContextError:
        result = False

    return result 
Example #15
Source File: rocket.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def build_environ(self, sock_file, conn):
        """ Build the execution environment. """
        # Grab the request line
        request = self.read_request_line(sock_file)

        # Copy the Base Environment
        environ = self.base_environ.copy()

        # Grab the headers
        for k, v in self.read_headers(sock_file).iteritems():
            environ[str('HTTP_' + k)] = v

        # Add CGI Variables
        environ['REQUEST_METHOD'] = request['method']
        environ['PATH_INFO'] = request['path']
        environ['SERVER_PROTOCOL'] = request['protocol']
        environ['SERVER_PORT'] = str(conn.server_port)
        environ['REMOTE_PORT'] = str(conn.client_port)
        environ['REMOTE_ADDR'] = str(conn.client_addr)
        environ['QUERY_STRING'] = request['query_string']
        if 'HTTP_CONTENT_LENGTH' in environ:
            environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH']
        if 'HTTP_CONTENT_TYPE' in environ:
            environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE']

        # Save the request method for later
        self.request_method = environ['REQUEST_METHOD']

        # Add Dynamic WSGI Variables
        if conn.ssl:
            environ['wsgi.url_scheme'] = 'https'
            environ['HTTPS'] = 'on'
            try:
                peercert = conn.socket.getpeercert(binary_form=True)
                environ['SSL_CLIENT_RAW_CERT'] = \
                    peercert and ssl.DER_cert_to_PEM_cert(peercert)
            except Exception:
                print sys.exc_info()[1]
        else:
            environ['wsgi.url_scheme'] = 'http'

        if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked':
            environ['wsgi.input'] = ChunkedReader(sock_file)
        else:
            environ['wsgi.input'] = sock_file

        return environ