Example #1
0
    def _open(suffix, dscp):
        error, sock = TCPStream._open(suffix, dscp)
        if error:
            return error, None

        # Create an SSL context
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.set_verify(SSL.VERIFY_PEER, SSLStream.verify_cb)
        ctx.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
        # If the client has not set the SSL configuration files
        # exception would be raised.
        ctx.use_privatekey_file(Stream._SSL_private_key_file)
        ctx.use_certificate_file(Stream._SSL_certificate_file)
        ctx.load_verify_locations(Stream._SSL_ca_cert_file)

        ssl_sock = SSL.Connection(ctx, sock)
        ssl_sock.set_connect_state()
        return error, ssl_sock
 def __init__(self, server_address, HandlerClass):
     BaseServer.__init__(self, server_address, HandlerClass)
     # SSLv2 and SSLv3 supported
     ctx = SSL.Context(SSL.SSLv23_METHOD)
     # pem files defined before
     fpem_priv = 'newreq.pem'
     fpem_cli = 'newcert.pem'
     # establish private key
     ctx.use_privatekey_file(fpem_priv)
     # establish public/client certificate
     ctx.use_certificate_file(fpem_cli)
     # setup the ssl socket
     self.socket = SSL.Connection(
         ctx, socket.socket(self.address_family, self.socket_type))
     # bind to interface
     self.server_bind()
     # activate the interface
     self.server_activate()
Example #3
0
def send_init_packets(host):
    tpkt = TPKT()
    tpdu = TPDU()
    rdp_neg = RDP_NEG_REQ()
    rdp_neg['Type'] = 1
    rdp_neg['requestedProtocols'] = 1
    tpdu['VariablePart'] = rdp_neg.getData()
    tpdu['Code'] = 0xe0
    tpkt['TPDU'] = tpdu.getData()
    s = socket.socket()
    s.connect((host, 3389))
    s.sendall(tpkt.getData())
    s.recv(8192)
    ctx = SSL.Context(SSL.TLSv1_METHOD)
    tls = SSL.Connection(ctx, s)
    tls.set_connect_state()
    tls.do_handshake()
    return tls
    def _init_socket(self):
        if self.__unix:
            self.__realsocket = socket.socket(socket.AF_UNIX,
                                              socket.SOCK_STREAM)
        else:
            self.__realsocket = socket.socket(socket.AF_INET,
                                              socket.SOCK_STREAM)
        self.__realsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        fcntl.fcntl(self.__realsocket.fileno(), fcntl.F_SETFD, 1)

        if self.__ssl and not self.__unix:
            self.__socket = SSL.Connection(self.__crypto_context,
                                           self.__realsocket)
        else:
            if self.__socket:
                notifier.socket_remove(self.__socket)
                self.__socket.close()
            self.__socket = None
Example #5
0
 def handle_secure_connection(self, client_socket, request, dialog_id):
     """ performs all TLS stuff with client
         returns (wrapped secure_socket socket, client request after CONNECT)
     """
     client_socket.sendall(self.dialog_service.make_established_response(dialog_id))
     context = self.tls_service.create_ssl_context(request.host)
     secure_socket = SSL.Connection(context, client_socket)
     secure_socket.set_accept_state()
     try:
         secure_socket.do_handshake()
     except SSL.Error as err:
         secure_socket.close()
         raise SSL.Error(err)
         # return secure_socket, None
     # read application data request after handshake
     post_handshake_raw = read(secure_socket)
     final_request = self.dialog_service.make_request_from_raw(post_handshake_raw, dialog_id)
     return secure_socket, final_request
Example #6
0
    def __init__(self, server_address, RequestHandlerClass):
        from OpenSSL import SSL

        BaseServer.__init__(self, server_address, RequestHandlerClass)
        ctx = SSL.Context(SSL.SSLv3_METHOD)

        cert = os.path.join(settings.Config.ResponderPATH,
                            settings.Config.SSLCert)
        key = os.path.join(settings.Config.ResponderPATH,
                           settings.Config.SSLKey)

        ctx.use_privatekey_file(key)
        ctx.use_certificate_file(cert)

        self.socket = SSL.Connection(
            ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()
Example #7
0
    def __init__(self, sleeper=None):
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        # TLS 1.3 removes renegotiation support. Which is great for them, but
        # we still have to support versions before that, and that means we
        # need to test renegotation support, which means we need to force this
        # to use a lower version where this test server can trigger
        # renegotiations. Of course TLS 1.3 support isn't released yet, but
        # I'm told that this will work once it is. (And once it is we can
        # remove the pragma: no cover too.) Alternatively, once we drop
        # support for CPython 3.5 on MacOS, then we could switch to using
        # TLSv1_2_METHOD.
        #
        # Discussion: https://github.com/pyca/pyopenssl/issues/624
        if hasattr(SSL, "OP_NO_TLSv1_3"):  # pragma: no cover
            ctx.set_options(SSL.OP_NO_TLSv1_3)
        # Unfortunately there's currently no way to say "use 1.3 or worse", we
        # can only disable specific versions. And if the two sides start
        # negotiating 1.4 at some point in the future, it *might* mean that
        # our tests silently stop working properly. So the next line is a
        # tripwire to remind us we need to revisit this stuff in 5 years or
        # whatever when the next TLS version is released:
        assert not hasattr(SSL, "OP_NO_TLSv1_4")
        ctx.use_certificate_file(CERT1)
        ctx.use_privatekey_file(CERT1)
        self._conn = SSL.Connection(ctx, None)
        self._conn.set_accept_state()
        self._lot = _core.ParkingLot()
        self._pending_cleartext = bytearray()

        self._send_all_mutex = UnLock(
            _core.ResourceBusyError,
            "simultaneous calls to PyOpenSSLEchoStream.send_all")
        self._receive_some_mutex = UnLock(
            _core.ResourceBusyError,
            "simultaneous calls to PyOpenSSLEchoStream.receive_some")

        if sleeper is None:

            async def no_op_sleeper(_):
                return

            self.sleeper = no_op_sleeper
        else:
            self.sleeper = sleeper
Example #8
0
def do_tlsalpn_challenges(client, authzs):
    port = 5001
    example_key, example_cert = load_example_cert()
    server_certs = {'localhost': (example_key, example_cert)}
    challs = {
        a.body.identifier.value: get_chall(a, challenges.TLSALPN01)
        for a in authzs
    }
    chall_certs = {
        domain: tls_alpn_01_cert(client, c, domain)
        for domain, c in challs.items()
    }
    # TODO: this won't be needed once acme standalone tls-alpn server serves
    # certs correctly, not only challenge certs.
    chall_certs['localhost'] = (example_key, example_cert)
    server = standalone.TLSALPN01Server(("", port), server_certs, chall_certs)
    thread = threading.Thread(target=server.serve_forever)
    thread.start()

    # Loop until the TLSALPN01Server is ready.
    while True:
        try:
            s = socket.socket()
            s.connect(("localhost", port))
            client_ssl = SSL.Connection(SSL.Context(SSL.TLSv1_METHOD), s)
            client_ssl.set_connect_state()
            client_ssl.set_tlsext_host_name("localhost")
            client_ssl.set_alpn_protos([b'acme-tls/1'])
            client_ssl.do_handshake()
            break
        except (socket.error, SSL.Error):
            time.sleep(0.1)
        finally:
            s.close()

    for chall_body in challs.values():
        client.answer_challenge(chall_body, chall_body.response(client.key))

    def cleanup():
        server.shutdown()
        server.server_close()
        thread.join()

    return cleanup
Example #9
0
def get_requests_verify(hostname, port):
    """
    Get verification method for sending HTTP requests to Hopsworks.
    Credit to https://gist.github.com/gdamjan/55a8b9eec6cf7b771f92021d93b87b2c
    Returns:
        if env var HOPS_UTIL_VERIFY is not false
            then if hopsworks certificate is self-signed, return the path to the truststore (PEM)
            else if hopsworks is not self-signed, return true
        return false
    """
    if constants.ENV_VARIABLES.REQUESTS_VERIFY_ENV_VAR in os.environ and os.environ[
            constants.ENV_VARIABLES.REQUESTS_VERIFY_ENV_VAR] == 'true':

        hostname_idna = idna.encode(hostname)
        sock = socket()

        sock.connect((hostname, int(port)))
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.check_hostname = False
        ctx.verify_mode = SSL.VERIFY_NONE

        sock_ssl = SSL.Connection(ctx, sock)
        sock_ssl.set_connect_state()
        sock_ssl.set_tlsext_host_name(hostname_idna)
        sock_ssl.do_handshake()
        cert = sock_ssl.get_peer_certificate()
        crypto_cert = cert.to_cryptography()
        sock_ssl.close()
        sock.close()

        try:
            commonname = crypto_cert.subject.get_attributes_for_oid(
                NameOID.COMMON_NAME)[0].value
            issuer = crypto_cert.issuer.get_attributes_for_oid(
                NameOID.COMMON_NAME)[0].value
            if commonname == issuer and constants.ENV_VARIABLES.DOMAIN_CA_TRUSTSTORE_PEM_ENV_VAR in os.environ:
                return os.environ[
                    constants.ENV_VARIABLES.DOMAIN_CA_TRUSTSTORE_PEM_ENV_VAR]
            else:
                return True
        except x509.ExtensionNotFound:
            return True

    return False
Example #10
0
    def run(self):
        kb = self._scanner.get_knowledge_base()

        protocol_versions = self._scanner.get_enabled_versions()

        methods = convert_versions2methods(protocol_versions)
        methods.reverse()

        for method in methods:
            try:
                ctx = SSL.Context(method)
            except:
                # ToDo:
                continue

            ctx.set_cipher_list("ALL:COMPLEMENT")
            ctx.set_options(_util.lib.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
            conn = self._scanner.handler.connect()
            conn_ssl = SSL.Connection(ctx, conn._socket)
            conn_ssl.set_tlsext_host_name(
                self._scanner.handler.hostname.encode("utf-8"))
            conn_ssl.set_connect_state()
            try:
                conn_ssl.do_handshake()
            except Exception as e:
                # ToDo:
                # print(e)
                conn_ssl.close()
                continue

            kb.set("server.renegotiation.support", False)
            if _util.lib.SSL_get_secure_renegotiation_support(
                    conn_ssl._ssl) == 1:
                kb.set("server.renegotiation.secure", True)
                kb.set("server.renegotiation.support", True)
            else:
                kb.set("server.renegotiation.secure", False)
                kb.set("server.renegotiation.support", False)
                cipher_status = _util.lib.SSL_do_handshake(conn_ssl._ssl)
                if cipher_status == 1:
                    if _util.lib.SSL_get_state(conn_ssl._ssl) == SSL.SSL_ST_OK:
                        kb.set("server.renegotiation.support", True)

            conn_ssl.close()
Example #11
0
def get_host_certificate(host, port=443):
    """Get a host's certificate.

  :param str host: The hostname from which to fetch the certificate.
  :param int port: The port from which to fetch the certificate, if different
    than ``443``.
  :return: The host's X.509 certificate.
  :rtype: :class:`OpenSSL.crypto.X509`

  """
    ip_addr = socket.gethostbyname(host)
    sock = socket.socket()
    context = SSL.Context(SSL.TLSv1_METHOD)
    context.set_options(SSL.OP_NO_SSLv2)
    context.load_verify_locations(certifi.where(), None)
    ssl_sock = SSL.Connection(context, sock)
    ssl_sock.connect((ip_addr, port))
    ssl_sock.do_handshake()
    return ssl_sock.get_peer_certificate()
Example #12
0
    def __init__(self, args, kwargs):

        irc_server.IRCServer.__init__(self, args, kwargs)

        # Setup SSL.
        # TODO: Load certificate path from config and handle missing certificate.
        ssl_ctx = SSL.Context(SSL.SSLv23_METHOD)
        ssl_key_path = '../server.pem'
        ssl_ctx.use_privatekey_file(ssl_key_path)
        ssl_ctx.use_certificate_file(ssl_key_path)
        self.socket = SSL.Connection(
            ssl_ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()

        # Create a default channel and set a default map.
        channel = self.channels.setdefault('#lobby',
                                           irc_server.IRCChannel('#lobby'))
        channel.topic = 'Map:Farm'
Example #13
0
    def accept(self):  # pylint: disable=missing-docstring
        sock, addr = self.sock.accept()
        context = SSL.Context(self.method)
        context.set_options(SSL.OP_NO_SSLv2)
        context.set_options(SSL.OP_NO_SSLv3)
        context.set_tlsext_servername_callback(self._pick_certificate_cb)
        if self.alpn_selection is not None:
            context.set_alpn_select_callback(self.alpn_selection)
        ssl_sock = self.FakeConnection(SSL.Connection(context, sock))
        ssl_sock.set_accept_state()
        self.log_callback("SSL Socket: Performing handshake with {0}".format(addr))
        try:
            ssl_sock.do_handshake()
        except SSL.Error as error:
            # _pick_certificate_cb might have returned without
            # creating SSL context (wrong server name)
            raise socket.error(error)

        return ssl_sock, addr
Example #14
0
    def wrapClientConnection(self, cert='/tmp/impacket.crt'):
        # Create a context, we don't really care about the SSL/TLS
        # versions used since it is only intended for local use and thus
        # doesn't have to be super-secure
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        try:
            ctx.use_privatekey_file(cert)
            ctx.use_certificate_file(cert)
        except SSL.Error:
            LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt')
            generateImpacketCert(cert)
            ctx.use_privatekey_file(cert)
            ctx.use_certificate_file(cert)

        sslSocket = SSL.Connection(ctx, self.socksSocket)
        sslSocket.set_accept_state()

        # Now set this property back to the SSL socket instead of the regular one
        self.socksSocket = sslSocket
Example #15
0
    def run(self):
        if self._scanner.handler.name != "imap":
            return

        kb = self._scanner.get_knowledge_base()

        methods = self._scanner.get_enabled_methods()
        methods.reverse()
        for method in methods:
            try:
                ctx = SSL.Context(method)
            except:
                # ToDo:
                continue

            server_info = self._scanner.handler.get_server_info()
            if server_info is None:
                ctx.set_cipher_list("ALL:COMPLEMENT")
                conn = self._scanner.handler.connect()
                conn_ssl = SSL.Connection(ctx, conn)
                conn_ssl.set_tlsext_host_name(
                    self._scanner.handler.hostname.encode("utf-8"))
                conn_ssl.set_connect_state()
                try:
                    conn_ssl.do_handshake()
                except Exception as e:
                    print(e)
                    conn_ssl.close()
                    continue

                server_info = self._scanner.handler.get_server_info(conn_ssl)
                conn_ssl.close()

            if server_info is None:
                return

            kb.set("server.custom.protocol.imap",
                   ResultGroup(label="IMAP Information"))

            kb.set(
                "server.custom.protocol.imap.banner",
                ResultValue(label="Server banner",
                            value=server_info.get("banner")))
Example #16
0
def get_certificate(hostname: str, port: int) -> HostInfo:
    hostname_idna = idna.encode(hostname)
    sock = socket.socket()

    sock.connect((hostname, port))
    peername = sock.getpeername()
    ctx = SSL.Context(SSL.SSLv23_METHOD)  # most compatible
    ctx.check_hostname = False
    ctx.verify_mode = SSL.VERIFY_NONE

    sock_ssl = SSL.Connection(ctx, sock)
    sock_ssl.set_connect_state()
    sock_ssl.set_tlsext_host_name(hostname_idna)
    sock_ssl.do_handshake()
    cert = sock_ssl.get_peer_certificate()
    sock_ssl.close()
    sock.close()

    return HostInfo(cert=cert, peername=peername, hostname=hostname)
Example #17
0
def certificate_age(config, host, port=443):
    """
    Check a TLS certificate of a host to determine if it's going to expire soon

    :param config: dictionary containing settings
        config['vars']['cert_expiration_days_threshold']: If the certificate
        is set to expire in a number of days less than this threshold then
        alert
    :param host: The host to fetch the certificate from
    :return: 3-tuple of (success, name, message)
        success: Boolean value indicating if there is a problem or not
        name: DNS name
        message: String describing the status
    """
    name = host
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
    except Exception as e:
        return False, name, "Exception %s %s" % (e.__class__, e)
    try:
        ctx = SSL.Context(SSL.TLSv1_METHOD)
        ctx.load_verify_locations(CA_CERTS)
    except Exception as e:
        return False, name, "Exception %s %s" % (e.__class__, e)

    try:
        ssl_sock = SSL.Connection(ctx, sock)
        ssl_sock.set_connect_state()
        ssl_sock.set_tlsext_host_name(host)
        ssl_sock.do_handshake()

        x509 = ssl_sock.get_peer_certificate()
        asn1 = x509.get_notAfter()
        result = check_expiration_date(
            asn1, name, config['vars']['cert_expiration_days_threshold'])
    except Exception as e:
        return False, name, "Exception %s %s" % (e.__class__, e)
    finally:
        ssl_sock.shutdown()

    sock.close()
    return result
Example #18
0
def get_cert(host, port, user_args):
    """Connection to the host."""
    if user_args.socks:
        import socks
        socks_host, socks_port = filter_hostname(user_args.socks)
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, socks_host, int(socks_port), True)
        socket.socket = socks.socksocket

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    osobj = SSL.Context(PROTOCOL_TLSv1)
    sock.connect((host, int(port)))
    oscon = SSL.Connection(osobj, sock)
    oscon.set_tlsext_host_name(host.encode())
    oscon.set_connect_state()
    oscon.do_handshake()
    cert = oscon.get_peer_certificate()
    sock.close()

    return cert
Example #19
0
        def tls_start(tls_start: tls.TlsStartData):
            # INSECURE
            ssl_context = SSL.Context(SSL.SSLv23_METHOD)
            if tls_start.conn == tls_start.context.client:
                ssl_context.use_privatekey_file(
                    pkg_data.path("../test/mitmproxy/data/verificationcerts/trusted-leaf.key")
                )
                ssl_context.use_certificate_chain_file(
                    pkg_data.path("../test/mitmproxy/data/verificationcerts/trusted-leaf.crt")
                )

            tls_start.ssl_conn = SSL.Connection(ssl_context)

            if tls_start.conn == tls_start.context.client:
                tls_start.ssl_conn.set_accept_state()
            else:
                tls_start.ssl_conn.set_connect_state()
                if tls_start.context.client.sni is not None:
                    tls_start.ssl_conn.set_tlsext_host_name(tls_start.context.client.sni.encode())
def verify_cert(hostname, port):
    hostname_idna = idna.encode(hostname)
    sock = socket()

    sock.connect((hostname, port))
    peername = sock.getpeername()
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.check_hostname = False
    ctx.verify_mode = SSL.VERIFY_NONE

    sock_ssl = SSL.Connection(ctx, sock)
    sock_ssl.set_connect_state()
    sock_ssl.set_tlsext_host_name(hostname_idna)
    sock_ssl.do_handshake()
    cert = sock_ssl.get_peer_certificate()
    crypto_cert = cert.to_cryptography()
    sock_ssl.close()
    sock.close()
    return HostInfo(cert=crypto_cert, peername=peername, hostname=hostname)
Example #21
0
    def __init__(self,server_address,HandlerClass,certFile='certs/cert.pem',keyFile='certs/key.pem',logRequests=False):
        """Secure XML-RPC server.
        It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        cpem.log_event('debug',"starting SecureXMLRPCServer")
        self.logRequests = logRequests #turn off the BaseHTTPServer logging... because we dun need it.
        SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self,True,None)
        ThreadedBaseServer(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()
        cpem.log_event('debug','server setup complete')

        def shutdown_request(self,request):
            request.shutdown()
Example #22
0
def test_alpn_select_callback():
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    conn = SSL.Connection(ctx)
    conn.set_app_data(tlsconfig.AppData(server_alpn=b"h2", http2=True))

    # Test that we try to mirror the server connection's ALPN
    assert tlsconfig.alpn_select_callback(
        conn, [b"http/1.1", b"qux", b"h2"]) == b"h2"

    # Test that we respect the client's preferred HTTP ALPN.
    conn.set_app_data(tlsconfig.AppData(server_alpn=None, http2=True))
    assert tlsconfig.alpn_select_callback(
        conn, [b"qux", b"http/1.1", b"h2"]) == b"http/1.1"
    assert tlsconfig.alpn_select_callback(
        conn, [b"qux", b"h2", b"http/1.1"]) == b"h2"

    # Test no overlap
    assert tlsconfig.alpn_select_callback(
        conn, [b"qux", b"quux"]) == SSL.NO_OVERLAPPING_PROTOCOLS
Example #23
0
    def convert_to_ssl(self, cert, key, **sslctx_kwargs):
        """
        Convert connection to SSL.
        For a list of parameters, see BaseHandler._create_ssl_context(...)
        """

        context = self.create_ssl_context(
            cert,
            key,
            **sslctx_kwargs)
        self.connection = SSL.Connection(context, self.connection)
        self.connection.set_accept_state()
        try:
            self.connection.do_handshake()
        except SSL.Error as v:
            raise TlsException("SSL handshake error: %s" % repr(v))
        self.ssl_established = True
        self.rfile.set_descriptor(self.connection)
        self.wfile.set_descriptor(self.connection)
Example #24
0
    def __connect(cls, hostname: str, port: int) -> SSL.Connection:
        """
        Method for opening a socket to the Conjur server
        """

        ctx = cls._get_ssl_context()
        # Taken from
        # https://gist.github.com/brandond/f3d28734a40c49833176207b17a44786#file-sslscan-py-L17
        conjur_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conjur_conn = SSL.Connection(context=ctx, socket=conjur_sock)
        conjur_conn.connect((hostname, port))
        # handle SNI
        conjur_conn.set_tlsext_host_name(hostname.encode())
        conjur_conn.do_handshake()

        logging.debug("TLS connection established. "
                      "Fetching certificate from Conjur server...")

        return conjur_conn
    def listen(self):
        # This should have been a SSLAcceptor ...
        if self._sok == None:

            def verify_cb(conn, cert, errnum, depth, ok):
                # This obviously has to be updated
                print 'Got certificate: %s' % cert.get_subject()
                return ok

            # Initialize context
            ctx = SSL.Context(SSL.SSLv23_METHOD)
            ctx.set_session_id('weightless:%s:%s' %
                               (time(), randint(1024, 4096)))
            ctx.set_options(SSL.OP_NO_SSLv2)
            ctx.set_verify(SSL.VERIFY_PEER, verify_cb)  # Demand a certificate
            ctx.use_privatekey_file(self._keyfile)
            ctx.use_certificate_file(self._certfile)

            # Set up server
            self._sok = SSL.Connection(ctx, socket())
            self._sok.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            self._sok.setsockopt(SOL_SOCKET, SO_LINGER, pack('ii', 0, 0))
            self._sok.bind(
                ('0.0.0.0' if self._bindAddress is None else self._bindAddress,
                 self._port))
            self._sok.listen(127)

        self._acceptor = Acceptor(reactor=self._reactor,
                                  port=self._port,
                                  sinkFactory=lambda sok: HttpsHandler(
                                      reactor=self._reactor,
                                      sok=sok,
                                      generatorFactory=self._generatorFactory,
                                      timeout=self._timeout,
                                      recvSize=self._recvSize,
                                      prio=self._prio,
                                      maxConnections=self._maxConnections,
                                      errorHandler=self._errorHandler,
                                      compressResponse=self._compressResponse),
                                  prio=self._prio,
                                  sok=self._sok,
                                  bindAddress=self._bindAddress)
Example #26
0
def get_server_root_cert(address, port, certDict, root=True):
    """Attempt to retrieve the the root certificate in the full SSL cert chain 
    from the provided server address & port. The certDict parameter should
    contain a dictionary of { certificate.get_subject().hash() md5 hash : certificate }, 
    which this function will use to match the certificate chain to a stored root 
    certificate. This function will return a single certificate as a PyOpenSSL X509 
    object, or None if the chain couldn't be retrieved for some reason, or the 
    certDict did not contain a matching certificate.
    """
    # Use PyOpenSSL to initiate an SSL connection and get the full cert chain.
    # Sadly Python's built in SSL library can't do this so we must use this
    # OpenSSL-based library.
    cert = None
    ctx = SSL.Context(SSL.TLSv1_2_METHOD)
    # do the connection, and fetch the cert chain
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ssl_soc = SSL.Connection(ctx, soc)
    ssl_soc.connect((address, port))
    ssl_soc.set_tlsext_host_name(bytes(address, "utf8"))
    try:
        ssl_soc.do_handshake()
        if root is True:
            cert = ssl_soc.get_peer_cert_chain()[-1]
        else:
            cert = ssl_soc.get_peer_cert_chain()[0]
    finally:
        ssl_soc.shutdown()
        soc.close()
    # match the certificate in the chain to the respective root certificate using the common name
    if cert is None:
        print("Failed to fetch certificate on domain: " + address)
        return None
    # if we don't want the root cert, return the regular cert
    if root is False:
        return cert
    cn_hash = cert.get_issuer().hash()
    # if there is a respective certificate, return it
    # else print an error and return None
    if cn_hash not in certDict:
        print("Could not find matching root certificate for domain: " + address)
        return None
    return certDict[cn_hash]
Example #27
0
def start_server():
    #	context = SSL.Context(SSL.TLSv1_2_METHOD)
    context = SSL.Context(SSL.TLSv1_METHOD)

    context.use_privatekey_file('startssl.key')
    context.use_certificate_file('startssl.cert')
    context.use_certificate_chain_file('startssl.cert')

    s_n = socket.socket()
    s_n.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s_n.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
    s = SSL.Connection(context, s_n)

    s.bind(('', PORT))
    s.listen(MAX_CLIENTS)  # max clients

    p.rint(
        "[S_wss " + time.strftime("%H:%M:%S") +
        "] Waiting on wss_clients on Port " + str(PORT), "l")
    while 1:
        conn, addr = s.accept()
        try:
            #connstream = ssl.wrap_socket(conn, server_side=True, certfile="cert", keyfile="key", ssl_version=ssl.PROTOCOL_TLSv1)
            # generate new client
            new_client = ws_clients(conn.getpeername()[1],
                                    conn.getpeername()[0])  # port, ip
            new_client.ws = WebSocket(conn)
            # append it
            clients.append(new_client)
            p.rint(
                "[S_wss " + time.strftime("%H:%M:%S") +
                "] -> Connection from: " + str(addr[0]) + ". Serving " +
                str(len(clients)) + " ws_clients now", "l")
            threading.Thread(target=handle, args=(new_client, addr)).start()
            # send every subscr
            for callb in callback_con:
                callb("connect", new_client)
        except Exception as n:
            p.rint(
                "[S_wss " + time.strftime("%H:%M:%S") +
                "] exception before starting connect thread", "d")
            print(n)
Example #28
0
def scan(address, version):
    """
    Not finished yet, just analyzing if the web server supports
    any CBC ciphers
    :param address: tuple of an url and port
    :param version: tls version in bytes
    :return: if the server is vulnerable
    """
    client_hello = construct_client_hello(version)
    logging.info("Scanning Poodle vulnerability...")
    server_hello, sock = send_client_hello(address, client_hello, 2)
    # If no server hello is sent the server doesn't support
    # CBC ciphers
    if not is_server_hello(server_hello):
        return False
    sock.close()
    unsafe_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ssl_socket = SSL.Connection(SSL.Context(SSL.SSLv23_METHOD), unsafe_sock)
    ssl_socket.connect(address)
    ssl_socket.do_handshake()
    for i in range(256):
        try:
            unsafe_sock.send(build_data(i))
            ssl_socket.read(2048)
        # Server didn't send an alert
        except (SSL.ZeroReturnError, SSL.SysCallError):
            continue
        # Server broke connection
        except BrokenPipeError:
            return False
        # Server sent an alert
        except SSL.Error as e:
            if e.args[0][0][2] == 'sslv3 alert bad record mac':
                continue
            # If there is an alert and its not bad record mac
            else:
                return True
        # Unknown exception
        except Exception as e:
            raise e
    logging.info("Poodle vulnerability scan done.")
    return False
	def run(self):
		Logger.info("[WebApps] new process started")
		
		signal.signal(signal.SIGINT, signal.SIG_IGN)
		signal.signal(signal.SIGTERM, signal.SIG_IGN)
		
		# close inherited father pipes
		self.father_pipes[0].close()
		self.father_pipes[1].close()
		
		self.socks = Queue.Queue()
		
		self.clean_timer = threading.Timer(Config.process_timeout, self.clean)
		self.clean_timer.start()
		
		self.f_control = ControlFatherProcess(self)
		self.f_control.start()
		
		while self.f_control.is_alive() or not self.socks.empty():
			try:
				sock = self.socks.get(timeout=0.01)
				if Config.connection_secure:
					ssl_conn = SSL.Connection(self.ssl_ctx, sock)
					Logger.debug("[WebApps] new connection => %s" % str(ssl_conn.getpeername()))
					ssl_conn.set_accept_state()
					ProtocolDetectDispatcher(ssl_conn, self.f_control, self.ssl_ctx)
				else:
					HttpProtocolDetectDispatcher(sock, self.f_control)
			except (IOError, Queue.Empty):
				continue
			
			# reload asyncore if stopped
			if self.is_sleeping():
				# timeout needed for more SSL layer reactivity
				self.t_asyncore = threading.Thread(target=lambda:asyncore.loop(timeout=0.01))
				self.t_asyncore.start()
		
		if not self.is_sleeping():
			asyncore.close_all()
			self.t_asyncore.join()
		
		Logger.info("[WebApps] child process stopped")
Example #30
0
def scan_server(ip, port):
    global vulnerable

    print('Checking to {}:{}'.format(ip, port))

    ctx = SSL.Context(DTLSv1_METHOD)
    ctx.set_verify_depth(2)
    ctx.set_verify(SSL.VERIFY_PEER, certificate_callback)

    sock = SSL.Connection(ctx, socket.socket(socket.AF_INET,
                                             socket.SOCK_DGRAM))

    sock.connect((ip, int(port)))
    sock.send(build_connect_packet(0, 65, b"A"))

    data = sock.recv(1024)
    if len(data) == 16:
        error_code = struct.unpack('<L', data[12:])[0]
        if error_code == 0x8000ffff:
            vulnerable = True