Python OpenSSL.SSL 模块,Connection() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用OpenSSL.SSL.Connection()

项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def writeSomeData(self, data):
        try:
            return Connection.writeSomeData(self, data)
        except SSL.WantWriteError:
            return 0
        except SSL.WantReadError:
            self.writeBlockedOnRead = 1
            Connection.stopWriting(self)
            Connection.startReading(self)
            return 0
        except SSL.ZeroReturnError:
            return main.CONNECTION_LOST
        except SSL.SysCallError, e:
            if e[0] == -1 and data == "":
                # errors when writing empty strings are expected
                # and can be ignored
                return 0
            else:
                return main.CONNECTION_LOST
        except SSL.Error, e:
            return e
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, server_address, HandlerClass, logRequests=True):
        """Secure XML-RPC server.

        It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        self.logRequests = logRequests

        SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
        SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file (KEYFILE)
        ctx.use_certificate_file(CERTFILE)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
                                                        self.socket_type))
        self.server_bind()
        self.server_activate()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __init__(self, ctx, sock=None):
        """Create SSL socket object

        @param ctx: SSL context
        @type ctx: OpenSSL.SSL.Context
        @param sock: underlying socket object
        @type sock: socket.socket
        """
        if sock is not None:
            self.socket = sock
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.__ssl_conn = SSL.Connection(ctx, self.socket)
        self.buf_size = self.__class__.default_buf_size
        self._makefile_refs = 0
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def doRead(self):
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST
        except SSL.Error, e:
            return e
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def writeSomeData(self, data):
        """Connection.writeSomeData(data) -> #of bytes written | CONNECTION_LOST
        This writes as much data as possible to the socket and returns either
        the number of bytes read (which is positive) or a connection error code
        (which is negative)
        """
        try:
            # Limit length of buffer to try to send, because some OSes are too
            # stupid to do so themselves (ahem windows)
            return self.socket.send(buffer(data, 0, self.SEND_LIMIT))
        except socket.error, se:
            if se.args[0] == EINTR:
                return self.writeSomeData(data)
            elif se.args[0] in (EWOULDBLOCK, ENOBUFS):
                return 0
            else:
                return main.CONNECTION_LOST
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, sock, protocol, client, server, sessionno):
        """Server(sock, protocol, client, server, sessionno)

        Initialize me with a socket, a protocol, a descriptor for my peer (a
        tuple of host, port describing the other end of the connection), an
        instance of Port, and a session number.
        """
        Connection.__init__(self, sock, protocol)
        self.server = server
        self.client = client
        self.sessionno = sessionno
        self.hostname = client[0]
        self.logstr = "%s,%s,%s" % (self.protocol.__class__.__name__, sessionno, self.hostname)
        self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__, self.sessionno, self.server.port)
        self.startReading()
        self.connected = 1
项目:midip-sslyze    作者:soukupa5    | 项目源码 | 文件源码
def _test_dtls_ciphersuite(self, server_connectivity_info, dtls_version, cipher, port):
        """This function is used by threads to it investigates with support the cipher suite on server, when DTLS protocol(s) is/are tested. Returns instance of class AcceptCipher or RejectCipher.

            Args:
            server_connectivity_info (ServerConnectivityInfo): contains information for connection on server
            dtls_version (str): contains SSL/TLS protocol version, which is used to connect
            cipher (str): contains OpenSSL shortcut for identification cipher suite
            port (int): contains port number for connecting comunication.
        """
        cnx = SSL.Context(dtls_version)
        cnx.set_cipher_list(cipher)
        conn = SSL.Connection(cnx, socket.socket(socket.AF_INET, socket.SOCK_DGRAM))
        try:
            conn.connect((server_connectivity_info.ip_address, port))
            conn.do_handshake()
        except SSL.Error as e:
            error_msg = ((e[0])[0])[2]
            cipher_result = RejectCipher(TLS_OPENSSL_TO_RFC_NAMES_MAPPING[cipher], error_msg)
        else:
            cipher_result = AcceptCipher(TLS_OPENSSL_TO_RFC_NAMES_MAPPING[cipher])
        finally:
            conn.shutdown()
            conn.close()
        return cipher_result
项目:midip-sslyze    作者:soukupa5    | 项目源码 | 文件源码
def test_dtls_protocol_support(self, server_connectivity_info, dtls_version, port):
        """Tests if DTLS protocols are supported by server. Returns true if server supports protocol otherwise returns false.

            Args:
            server_connectivity_info (ServerConnectivityInfo): contains information for connection on server
            dtls_protocol (str): contains version of DTLS protocol, which is supposed to be tested
            port (int): contains port number for connecting comunication.
        """
        cnx = SSL.Context(dtls_version)
        cnx.set_cipher_list('ALL:COMPLEMENTOFALL')
        conn = SSL.Connection(cnx,socket.socket(socket.AF_INET, socket.SOCK_DGRAM))
        try:
            conn.connect((server_connectivity_info.ip_address, port))
            conn.do_handshake()
        except SSL.SysCallError as ex:
            if ex[0] == 111:
                raise ValueError('LuckyThirteenVulnerabilityTesterPlugin: It is entered wrong port for DTLS connection.')
            else:
                support = False
        else:
            support = True
        finally:
            conn.shutdown()
            conn.close()
        return support
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def ssl(sock, keyfile=None, certfile=None):
    context = SSL.Context(SSL.SSLv23_METHOD)
    if certfile is not None:
        context.use_certificate_file(certfile)
    if keyfile is not None:
        context.use_privatekey_file(keyfile)
    context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
    timeout = sock.gettimeout()
    try:
        sock = sock._sock
    except AttributeError:
        pass
    connection = SSL.Connection(context, sock)
    ssl_sock = SSLObject(connection)
    ssl_sock.settimeout(timeout)

    try:
        sock.getpeername()
    except Exception:
        # no, no connection yet
        pass
    else:
        # yes, do the handshake
        ssl_sock.do_handshake()
    return ssl_sock
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def ssl(sock, keyfile=None, certfile=None):
    context = SSL.Context(SSL.SSLv23_METHOD)
    if certfile is not None:
        context.use_certificate_file(certfile)
    if keyfile is not None:
        context.use_privatekey_file(keyfile)
    context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
    timeout = sock.gettimeout()
    try:
        sock = sock._sock
    except AttributeError:
        pass
    connection = SSL.Connection(context, sock)
    ssl_sock = SSLObject(connection)
    ssl_sock.settimeout(timeout)

    try:
        sock.getpeername()
    except Exception:
        # no, no connection yet
        pass
    else:
        # yes, do the handshake
        ssl_sock.do_handshake()
    return ssl_sock
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def main():
    """
    Connect to an SNI-enabled server and request a specific hostname, specified
    by argv[1], of it.
    """
    if len(argv) < 2:
        print 'Usage: %s <hostname>' % (argv[0],)
        return 1

    client = socket()

    print 'Connecting...',
    stdout.flush()
    client.connect(('127.0.0.1', 8443))
    print 'connected', client.getpeername()

    client_ssl = Connection(Context(TLSv1_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(argv[1])
    client_ssl.do_handshake()
    print 'Server subject is', client_ssl.get_peer_certificate().get_subject()
    client_ssl.close()
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def main():
    """
    Run an SNI-enabled server which selects between a few certificates in a
    C{dict} based on the handshake request it receives from a client.
    """
    port = socket()
    port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    port.bind(('', 8443))
    port.listen(3)

    print 'Accepting...',
    stdout.flush()
    server, addr = port.accept()
    print 'accepted', addr

    server_context = Context(TLSv1_METHOD)
    server_context.set_tlsext_servername_callback(pick_certificate)

    server_ssl = Connection(server_context, server)
    server_ssl.set_accept_state()
    server_ssl.do_handshake()
    server.close()
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def __init__(self, server_address, RequestHandlerClass):
        SocketServer.BaseServer.__init__(
            self, server_address, RequestHandlerClass
        )

        # Same as normal, but make it secure:
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.set_options(SSL.OP_NO_SSLv2)

        dir = os.curdir
        ctx.use_privatekey_file(os.path.join(dir, 'server.pkey'))
        ctx.use_certificate_file(os.path.join(dir, 'server.cert'))

        self.socket = SSLWrapper(
            SSL.Connection(
                ctx, socket.socket(self.address_family, self.socket_type)
            )
        )
        self.server_bind()
        self.server_activate()
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def simple_response(self, status, msg=""):
        """Write a simple response back to the client."""
        status = str(status)
        buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
               "Content-Length: %s\r\n" % len(msg),
               "Content-Type: text/plain\r\n"]

        if status[:3] == "413" and self.response_protocol == 'HTTP/1.1':
            # Request Entity Too Large
            self.close_connection = True
            buf.append("Connection: close\r\n")

        buf.append("\r\n")
        if msg:
            buf.append(msg)

        try:
            self.wfile.sendall("".join(buf))
        except socket.error, x:
            if x.args[0] not in socket_errors_to_ignore:
                raise
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def doRead(self):
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST
        except SSL.Error, e:
            return e
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def writeSomeData(self, data):
        try:
            return Connection.writeSomeData(self, data)
        except SSL.WantWriteError:
            return 0
        except SSL.WantReadError:
            self.writeBlockedOnRead = 1
            Connection.stopWriting(self)
            Connection.startReading(self)
            return 0
        except SSL.ZeroReturnError:
            return main.CONNECTION_LOST
        except SSL.SysCallError, e:
            if e[0] == -1 and data == "":
                # errors when writing empty strings are expected
                # and can be ignored
                return 0
            else:
                return main.CONNECTION_LOST
        except SSL.Error, e:
            return e
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def writeSomeData(self, data):
        """Connection.writeSomeData(data) -> #of bytes written | CONNECTION_LOST
        This writes as much data as possible to the socket and returns either
        the number of bytes read (which is positive) or a connection error code
        (which is negative)
        """
        try:
            # Limit length of buffer to try to send, because some OSes are too
            # stupid to do so themselves (ahem windows)
            return self.socket.send(buffer(data, 0, self.SEND_LIMIT))
        except socket.error, se:
            if se.args[0] == EINTR:
                return self.writeSomeData(data)
            elif se.args[0] in (EWOULDBLOCK, ENOBUFS):
                return 0
            else:
                return main.CONNECTION_LOST
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, sock, protocol, client, server, sessionno):
        """Server(sock, protocol, client, server, sessionno)

        Initialize me with a socket, a protocol, a descriptor for my peer (a
        tuple of host, port describing the other end of the connection), an
        instance of Port, and a session number.
        """
        Connection.__init__(self, sock, protocol)
        self.server = server
        self.client = client
        self.sessionno = sessionno
        self.hostname = client[0]
        self.logstr = "%s,%s,%s" % (self.protocol.__class__.__name__, sessionno, self.hostname)
        self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__, self.sessionno, self.server.port)
        self.startReading()
        self.connected = 1
项目:mu    作者:excamera    | 项目源码 | 文件源码
def close(self):
        if self.sock is None:
            return

        if Defs.debug:
            print "CLOSING SOCKET %s" % traceback.format_exc()

        try:
            if isinstance(self.sock, SSL.Connection):
                self.sock.shutdown()
            else:
                self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
        except:
            pass

        self.sock = None
项目:mu    作者:excamera    | 项目源码 | 文件源码
def do_handshake(self):
        self.update_flags()
        if not isinstance(self.sock, SSL.Connection):
            return

        self.handshaking = True
        self.ssl_write = None
        try:
            self.sock.do_handshake()
        except SSL.WantWriteError:
            self.ssl_write = True
        except SSL.WantReadError:
            pass
        except SSL.Error:
            self.close()
        else:
            self.handshaking = False
项目:mu    作者:excamera    | 项目源码 | 文件源码
def connect_socket(addr, port, cacert, srvcrt, srvkey):
    # connect to the master for orders
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    s.connect((addr, port))

    # if we have a cacert, this means we should use SSL for this connection
    if cacert is not None:
        s = sslize(s, cacert, srvcrt, srvkey, True)
        if not isinstance(s, SSL.Connection):
            return "ERROR could not initialize SSL connection: %s\n" % str(s)

    # wrap in non-blocking socket reader/writer class
    s.setblocking(False)
    s = libmu.socket_nb.SocketNB(s)
    s.do_handshake()

    return s
项目:mu    作者:excamera    | 项目源码 | 文件源码
def sslize(sock, cacert, srvcrt, srvkey, is_connect):
    sslconn = None
    try:
        sslctx = ssl_context(cacert, srvcrt, srvkey)
        sslconn = SSL.Connection(sslctx, sock)
        if is_connect:
            sslconn.set_connect_state()
        else:
            sslconn.set_accept_state()
    except:
        return traceback.format_exc()
    else:
        return sslconn

###
#  listen on a socket, maybe SSLizing
###
项目:mu    作者:excamera    | 项目源码 | 文件源码
def listen_socket(addr, port, cacert, srvcrt, srvkey, nlisten=1):
    ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    ls.bind((addr, port))
    ls.listen(nlisten)

    if cacert is not None and srvcrt is not None and srvkey is not None:
        ls = sslize(ls, cacert, srvcrt, srvkey, False)
        if not isinstance(ls, SSL.Connection):
            return "ERROR could not initialize SSL connection: %s\n" % str(ls)

    ls.setblocking(False)

    return ls

###
#  accept from a listening socket and hand back a SocketNB
###
项目:mu    作者:excamera    | 项目源码 | 文件源码
def get_arwsocks(vals):
    # asocks is all extant sockets
    socknames = ['cmdsock', 'stsock']
    asocks = [ s for s in [ vals.get(n) for n in socknames ] if s is not None ] + \
             [ info[1] for info in vals.setdefault('runinfo', []) ]

    # rsocks is all objects that we could select upon
    rsocks = [ s for s in asocks
                 if isinstance(s, socket.SocketType)
                 or isinstance(s, SSL.Connection)
                 or (isinstance(s, SocketNB) and s.sock is not None) ]

    # wsocks is all rsocks that indicate they want to be written
    wsocks = [ s for s in asocks if isinstance(s, SocketNB) and (s.ssl_write or s.want_write) ]

    return (asocks, rsocks, wsocks)

###
#  make command string
###
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def _send_loop(self, send_method, data, *args):
        if self.act_non_blocking:
            return send_method(data, *args)

        while 1:
            try:
                return send_method(data, *args)
            except socket.error as e:
                eno = get_errno(e)
                if eno == errno.ENOTCONN or eno not in SOCKET_BLOCKING:
                    raise

            try:
                self._trampoline(self.fd, write=True, timeout=self.gettimeout(),
                                 timeout_exc=socket.timeout("timed out"))
            except IOClosed:
                raise socket.error(errno.ECONNRESET, 'Connection closed by another thread')
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def shutdown_safe(sock):
    """ Shuts down the socket. This is a convenience method for
    code that wants to gracefully handle regular sockets, SSL.Connection
    sockets from PyOpenSSL and ssl.SSLSocket objects from Python 2.6
    interchangeably.  Both types of ssl socket require a shutdown() before
    close, but they have different arity on their shutdown method.

    Regular sockets don't need a shutdown before close, but it doesn't hurt.
    """
    try:
        try:
            # socket, ssl.SSLSocket
            return sock.shutdown(socket.SHUT_RDWR)
        except TypeError:
            # SSL.Connection
            return sock.shutdown()
    except socket.error as e:
        # we don't care if the socket is already closed;
        # this will often be the case in an http server context
        if get_errno(e) not in (errno.ENOTCONN, errno.EBADF):
            raise
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def ssl(sock, keyfile=None, certfile=None):
    context = SSL.Context(SSL.SSLv23_METHOD)
    if certfile is not None:
        context.use_certificate_file(certfile)
    if keyfile is not None:
        context.use_privatekey_file(keyfile)
    context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
    timeout = sock.gettimeout()
    try:
        sock = sock._sock
    except AttributeError:
        pass
    connection = SSL.Connection(context, sock)
    ssl_sock = SSLObject(connection)
    ssl_sock.settimeout(timeout)

    try:
        sock.getpeername()
    except Exception:
        # no, no connection yet
        pass
    else:
        # yes, do the handshake
        ssl_sock.do_handshake()
    return ssl_sock
项目:package-33c3    作者:info-beamer    | 项目源码 | 文件源码
def __init__(self, ctx, sock=None):
        """Create SSL socket object

        @param ctx: SSL context
        @type ctx: OpenSSL.SSL.Context
        @param sock: underlying socket object
        @type sock: socket.socket
        """
        if sock is not None:
            self.socket = sock
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.__ssl_conn = SSL.Connection(ctx, self.socket)
        self.buf_size = self.__class__.default_buf_size
        self._makefile_refs = 0
项目:package-33c3    作者:info-beamer    | 项目源码 | 文件源码
def __init__(self, ctx, sock=None):
        """Create SSL socket object

        @param ctx: SSL context
        @type ctx: OpenSSL.SSL.Context
        @param sock: underlying socket object
        @type sock: socket.socket
        """
        if sock is not None:
            self.socket = sock
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.__ssl_conn = SSL.Connection(ctx, self.socket)
        self.buf_size = self.__class__.default_buf_size
        self._makefile_refs = 0
项目:slack_scholar    作者:xLeitix    | 项目源码 | 文件源码
def __init__(self, ctx, sock=None):
        """Create SSL socket object

        @param ctx: SSL context
        @type ctx: OpenSSL.SSL.Context
        @param sock: underlying socket object
        @type sock: socket.socket
        """
        if sock is not None:
            self.socket = sock
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.__ssl_conn = SSL.Connection(ctx, self.socket)
        self.buf_size = self.__class__.default_buf_size
        self._makefile_refs = 0
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def simpleVerifyHostname(connection, hostname):
    """
    Check only the common name in the certificate presented by the peer and
    only for an exact match.

    This is to provide I{something} in the way of hostname verification to
    users who haven't installed C{service_identity}. This check is overly
    strict, relies on a deprecated TLS feature (you're supposed to ignore the
    commonName if the subjectAlternativeName extensions are present, I
    believe), and lots of valid certificates will fail.

    @param connection: the OpenSSL connection to verify.
    @type connection: L{OpenSSL.SSL.Connection}

    @param hostname: The hostname expected by the user.
    @type hostname: L{unicode}

    @raise twisted.internet.ssl.VerificationError: if the common name and
        hostname don't match.
    """
    commonName = connection.get_peer_certificate().get_subject().commonName
    if commonName != hostname:
        raise SimpleVerificationError(repr(commonName) + "!=" +
                                      repr(hostname))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def clientConnectionForTLS(self, tlsProtocol):
        """
        Create a TLS connection for a client.

        @note: This will call C{set_app_data} on its connection.  If you're
            delegating to this implementation of this method, don't ever call
            C{set_app_data} or C{set_info_callback} on the returned connection,
            or you'll break the implementation of various features of this
            class.

        @param tlsProtocol: the TLS protocol initiating the connection.
        @type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}

        @return: the configured client connection.
        @rtype: L{OpenSSL.SSL.Connection}
        """
        context = self._ctx
        connection = SSL.Connection(context, None)
        connection.set_app_data(tlsProtocol)
        return connection
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _identityVerifyingInfoCallback(self, connection, where, ret):
        """
        U{info_callback
        <http://pythonhosted.org/pyOpenSSL/api/ssl.html#OpenSSL.SSL.Context.set_info_callback>
        } for pyOpenSSL that verifies the hostname in the presented certificate
        matches the one passed to this L{ClientTLSOptions}.

        @param connection: the connection which is handshaking.
        @type connection: L{OpenSSL.SSL.Connection}

        @param where: flags indicating progress through a TLS handshake.
        @type where: L{int}

        @param ret: ignored
        @type ret: ignored
        """
        if where & SSL.SSL_CB_HANDSHAKE_START:
            connection.set_tlsext_host_name(self._hostnameBytes)
        elif where & SSL.SSL_CB_HANDSHAKE_DONE:
            try:
                verifyHostname(connection, self._hostnameASCII)
            except VerificationError:
                f = Failure()
                transport = connection.get_app_data()
                transport.failVerification(f)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        self._checkHandshakeStatus()
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _checkHandshakeStatus(self):
        """
        Ask OpenSSL to proceed with a handshake in progress.

        Initially, this just sends the ClientHello; after some bytes have been
        stuffed in to the C{Connection} object by C{dataReceived}, it will then
        respond to any C{Certificate} or C{KeyExchange} messages.
        """
        # The connection might already be aborted (eg. by a callback during
        # connection setup), so don't even bother trying to handshake in that
        # case.
        if self._aborted:
            return
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            self._flushSendBIO()
        except Error:
            self._tlsShutdownFinished(Failure())
        else:
            self._handshakeDone = True
            if IHandshakeListener.providedBy(self.wrappedProtocol):
                self.wrappedProtocol.handshakeCompleted()
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _unbufferPendingWrites(self):
        """
        Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}.
        """
        pendingWrites, self._appSendBuffer = self._appSendBuffer, []
        for eachWrite in pendingWrites:
            self._write(eachWrite)

        if self._appSendBuffer:
            # If OpenSSL ran out of buffer space in the Connection on our way
            # through the loop earlier and re-buffered any of our outgoing
            # writes, then we're done; don't consider any future work.
            return

        if self._producer is not None:
            # If we have a registered producer, let it know that we have some
            # more buffer space.
            self._producer.resumeProducing()
            return

        if self.disconnecting:
            # Finally, if we have no further buffered data, no producer wants
            # to send us more data in the future, and the application told us
            # to end the stream, initiate a TLS shutdown.
            self._shutdownTLS()
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def clientConnectionForTLS(self, protocol):
        """
        Construct an OpenSSL server connection from the wrapped old-style
        context factory.

        @note: Since old-style context factories don't distinguish between
            clients and servers, this is exactly the same as
            L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}.

        @param protocol: The protocol initiating a TLS connection.
        @type protocol: L{TLSMemoryBIOProtocol}

        @return: a connection
        @rtype: L{OpenSSL.SSL.Connection}
        """
        return self._connectionForTLS(protocol)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _applyProtocolNegotiation(self, connection):
        """
        Applies ALPN/NPN protocol neogitation to the connection, if the factory
        supports it.

        @param connection: The OpenSSL connection object to have ALPN/NPN added
            to it.
        @type connection: L{OpenSSL.SSL.Connection}

        @return: Nothing
        @rtype: L{None}
        """
        if IProtocolNegotiationFactory.providedBy(self.wrappedFactory):
            protocols = self.wrappedFactory.acceptableProtocols()
            context = connection.get_context()
            _setAcceptableProtocols(context, protocols)

        return
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _createConnection(self, tlsProtocol):
        """
        Create an OpenSSL connection and set it up good.

        @param tlsProtocol: The protocol which is establishing the connection.
        @type tlsProtocol: L{TLSMemoryBIOProtocol}

        @return: an OpenSSL connection object for C{tlsProtocol} to use
        @rtype: L{OpenSSL.SSL.Connection}
        """
        connectionCreator = self._connectionCreator
        if self._creatorInterface is IOpenSSLClientConnectionCreator:
            connection = connectionCreator.clientConnectionForTLS(tlsProtocol)
            self._applyProtocolNegotiation(connection)
            connection.set_connect_state()
        else:
            connection = connectionCreator.serverConnectionForTLS(tlsProtocol)
            self._applyProtocolNegotiation(connection)
            connection.set_accept_state()
        return connection
项目:birdnet    作者:cyysu    | 项目源码 | 文件源码
def simple_response(self, status, msg=""):
        """Write a simple response back to the client."""
        status = str(status)
        buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
               "Content-Length: %s\r\n" % len(msg),
               "Content-Type: text/plain\r\n"]

        if status[:3] == "413" and self.response_protocol == 'HTTP/1.1':
            # Request Entity Too Large
            self.close_connection = True
            buf.append("Connection: close\r\n")

        buf.append("\r\n")
        if msg:
            buf.append(msg)

        try:
            self.wfile.sendall("".join(buf))
        except socket.error, x:
            if x.args[0] not in socket_errors_to_ignore:
                raise
项目:deb-python-eventlet    作者:openstack    | 项目源码 | 文件源码
def _send_loop(self, send_method, data, *args):
        if self.act_non_blocking:
            return send_method(data, *args)

        _timeout_exc = socket_timeout('timed out')
        while True:
            try:
                return send_method(data, *args)
            except socket.error as e:
                eno = get_errno(e)
                if eno == errno.ENOTCONN or eno not in SOCKET_BLOCKING:
                    raise

            try:
                self._trampoline(self.fd, write=True, timeout=self.gettimeout(),
                                 timeout_exc=_timeout_exc)
            except IOClosed:
                raise socket.error(errno.ECONNRESET, 'Connection closed by another thread')
项目:deb-python-eventlet    作者:openstack    | 项目源码 | 文件源码
def shutdown_safe(sock):
    """ Shuts down the socket. This is a convenience method for
    code that wants to gracefully handle regular sockets, SSL.Connection
    sockets from PyOpenSSL and ssl.SSLSocket objects from Python 2.6
    interchangeably.  Both types of ssl socket require a shutdown() before
    close, but they have different arity on their shutdown method.

    Regular sockets don't need a shutdown before close, but it doesn't hurt.
    """
    try:
        try:
            # socket, ssl.SSLSocket
            return sock.shutdown(socket.SHUT_RDWR)
        except TypeError:
            # SSL.Connection
            return sock.shutdown()
    except socket.error as e:
        # we don't care if the socket is already closed;
        # this will often be the case in an http server context
        if get_errno(e) not in (errno.ENOTCONN, errno.EBADF, errno.ENOTSOCK):
            raise
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def ssl(sock, keyfile=None, certfile=None):
    context = SSL.Context(SSL.SSLv23_METHOD)
    if certfile is not None:
        context.use_certificate_file(certfile)
    if keyfile is not None:
        context.use_privatekey_file(keyfile)
    context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
    timeout = sock.gettimeout()
    try:
        sock = sock._sock
    except AttributeError:
        pass
    connection = SSL.Connection(context, sock)
    ssl_sock = SSLObject(connection)
    ssl_sock.settimeout(timeout)

    try:
        sock.getpeername()
    except Exception:
        # no, no connection yet
        pass
    else:
        # yes, do the handshake
        ssl_sock.do_handshake()
    return ssl_sock
项目:ooniprobe-debian    作者:TheTorProject    | 项目源码 | 文件源码
def getPeerCert(connection, get_chain=False):
        """Get the PEM-encoded certificate or cert chain of the remote host.

        :param connection: A :class:`OpenSSL.SSL.Connection <Connection>`.
        :param bool get_chain: If True, get the all certificates in the
            chain. Otherwise, only get the remote host's certificate.
        :returns: A PEM-encoded x509 certificate. If
            :param:`getPeerCert.get_chain <get_chain>` is True, returns a list
            of PEM-encoded x509 certificates.
        """
        if not get_chain:
            x509_cert = connection.get_peer_certificate()
            pem_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, x509_cert)
            return pem_cert
        else:
            cert_chain = []
            x509_cert_chain = connection.get_peer_cert_chain()
            for x509_cert in x509_cert_chain:
                pem_cert = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                   x509_cert)
                cert_chain.append(pem_cert)
            return cert_chain
项目:estreamer    作者:spohara79    | 项目源码 | 文件源码
def __enter__(self):
        self.ctx = SSL.Context(SSL.TLSv1_METHOD)
        if self.verify:
            self.ctx.set_verify(SSL.VERIFY_PEER, self.validate_cert)
            self.ctx.load_verify_locations(self.verify)
            self.trusted_cert = crypto.load_certificate(crypto.FILETYPE_PEM, file(self.verify).read())
        self.ctx.use_privatekey(self.pkey)
        self.ctx.use_certificate(self.cert)
        self.sock = SSL.Connection(self.ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
        self.sock.connect((self.host, self.port))
        return self
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, registerInstance, server_address, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True):
        """Secure Documenting XML-RPC server.
        It it very similar to DocXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        DocXMLRPCServer.__init__(self, server_address, SecureDocXMLRpcRequestHandler, logRequests)
        self.logRequests = logRequests

        # stuff for doc server
        try: self.set_server_title(registerInstance.title)
        except AttributeError: self.set_server_title('default title')
        try: self.set_server_name(registerInstance.name)
        except AttributeError: self.set_server_name('default name')
        if registerInstance.__doc__: self.set_server_documentation(registerInstance.__doc__)
        else: self.set_server_documentation('default documentation')
        self.register_introspection_functions()

        # init stuff, handle different versions:
        try:
            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
        except TypeError:
            # An exception is raised in Python 2.5 as the prototype of the __init__
            # method has changed and now has 3 arguments (self, allow_none, encoding)
            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, False, None)
        SocketServer.BaseServer.__init__(self, server_address, SecureDocXMLRpcRequestHandler)
        self.register_instance(registerInstance) # for some reason, have to register instance down here!

        # SSL socket stuff
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyFile)
        ctx.use_certificate_file(certFile)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()
项目:electrum-martexcoin-server    作者:martexcoin    | 项目源码 | 文件源码
def __init__(self, server_address, certfile, keyfile, RequestHandlerClass, bind_and_activate=True):
        from OpenSSL import SSL
        SocketServer.BaseServer.__init__(self, server_address, RequestHandlerClass)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyfile)
        ctx.use_certificate_file(certfile)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        if bind_and_activate:
            self.server_bind()
            self.server_activate()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __init__(self, *args):
        self._ssl_conn = _ssl.Connection(*args)
        self._lock = _RLock()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def set_shutdown(self, mode):
        """Set the shutdown state of the Connection.
        @param mode: bit vector of either or both of SENT_SHUTDOWN and
        RECEIVED_SHUTDOWN
        """
        self.__ssl_conn.set_shutdown(mode)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def get_shutdown(self):
        """Get the shutdown state of the Connection.
        @return: bit vector of either or both of SENT_SHUTDOWN and
        RECEIVED_SHUTDOWN
        """
        return self.__ssl_conn.get_shutdown()