Pberndt V4

Direkt zum Inhalt springen


Quellcode OpenSSL_Python.py

Sourcecode

import os, sys, re, socket, fnmatch
from OpenSSL import SSL

def sslSocket(sock, keyFile=None, certFile=None):
    class capsule(object):
        def write(self, data):
            return self.conn.write(data)
        def read(self, howmuch=1024):
            return self.conn.recv(howmuch)

    ctx = SSL.Context(SSL.SSLv23_METHOD)
    def testCert(conn, cert, errnum, depth, ok):
        if depth == 0:
            peer = socket.gethostbyaddr(conn.getpeername()[0])[0]
            cn = re.search("CN=(.+?)(?:/|$|')", str(cert.get_subject()))
            if cn and not fnmatch.fnmatch(peer, cn.group(1)):
                print "%s vs %s: " % (peer, cn.group(1)),
                return False
        return ok
    ctx.set_verify(SSL.VERIFY_PEER, testCert)
    ctx.set_options(SSL.OP_PKCS1_CHECK_1 | SSL.OP_PKCS1_CHECK_2)
    for cert in os.listdir("/etc/ssl/certs/"):
        if cert[-3:] == "pem" and os.access("/etc/ssl/certs/%s" % cert, os.F_OK):
            ctx.load_verify_locations("/etc/ssl/certs/%s" % cert)

    peer = sock.getpeername()

    connection = capsule()
    connection.conn = SSL.Connection(ctx, sock)
    connection.conn.set_connect_state()
    try:
        connection.conn.do_handshake()
    except:
        print "ERROR: SSL handshake failed!"
        sys.exit(0)

    return connection

poplib.socket.ssl = sslSocket
smtplib.socket.ssl = sslSocket

Download

Dateiname
OpenSSL_Python.py
Größe
1.18kb