示例#1
2
文件: util.py 项目: ryfx/modrana
    def ssl_wrap_socket(
        sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None
    ):
        """
        All arguments except `server_hostname` have the same meaning as for
        :func:`ssl.wrap_socket`

        :param server_hostname:
            Hostname of the expected certificate
        """
        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs
        if ca_certs:
            try:
                context.load_verify_locations(ca_certs)
            # Py32 raises IOError
            # Py33 raises FileNotFoundError
            except Exception:  # Reraise as SSLError
                e = sys.exc_info()[1]
                raise SSLError(e)
        if certfile:
            # FIXME: This block needs a test.
            context.load_cert_chain(certfile, keyfile)
        if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
            return context.wrap_socket(sock, server_hostname=server_hostname)
        return context.wrap_socket(sock)
示例#2
1
    def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
                        ca_certs=None, server_hostname=None,
                        ssl_version=None):
        """
        All arguments except `server_hostname` have the same meaning as for
        :func:`ssl.wrap_socket`

        :param server_hostname:
            Hostname of the expected certificate
        """
        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs

        # Disable TLS compression to migitate CRIME attack (issue #309)
        OP_NO_COMPRESSION = 0x20000
        context.options |= OP_NO_COMPRESSION

        if ca_certs:
            try:
                context.load_verify_locations(ca_certs)
            # Py32 raises IOError
            # Py33 raises FileNotFoundError
            except Exception as e:  # Reraise as SSLError
                raise SSLError(e)
        if certfile:
            # FIXME: This block needs a test.
            context.load_cert_chain(certfile, keyfile)
        if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
            return context.wrap_socket(sock, server_hostname=server_hostname)
        return context.wrap_socket(sock)
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     ctx = SSLContext(ssl.PROTOCOL_SSLv23)
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2 and SSLv3. Note that up to
         # date versions of MongoDB 2.4 and above already do this,
         # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4
         # and SSLv3 in >= 3.4.3. There is no way for us to do this
         # explicitly for python 2.6 or 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
     if certfile is not None:
         if passphrase is not None:
             vi = sys.version_info
             # Since python just added a new parameter to an existing method
             # this seems to be about the best we can do.
             if (vi[0] == 2 and vi < (2, 7, 9) or
                     vi[0] == 3 and vi < (3, 3)):
                 raise ConfigurationError(
                     "Support for ssl_pem_passphrase requires "
                     "python 2.7.9+ (pypy 2.5.1+) or 3.3+")
             ctx.load_cert_chain(certfile, keyfile, passphrase)
         else:
             ctx.load_cert_chain(certfile, keyfile)
     if crlfile is not None:
         if not hasattr(ctx, "verify_flags"):
             raise ConfigurationError(
                 "Support for ssl_crlfile requires "
                 "python 2.7.9+ (pypy 2.5.1+) or  3.4+")
         # Match the server's behavior.
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         ctx.load_verify_locations(crlfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32" and
               hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     return ctx
示例#4
0
def connect_cassandra(is_client_encryption_enable):
    connected = False
    attempt = 0
    session = None
    _ssl_context = None

    if is_client_encryption_enable:

        ssl_context = SSLContext(PROTOCOL_TLSv1)
        ssl_context.load_verify_locations(certfile)
        ssl_context.verify_mode = CERT_REQUIRED
        ssl_context.load_cert_chain(certfile=usercert, keyfile=userkey)
        _ssl_context = ssl_context

    while not connected and attempt < 10:
        try:
            cluster = Cluster(contact_points=["127.0.0.1"],
                              ssl_context=_ssl_context)
            session = cluster.connect()
            connected = True
        except cassandra.cluster.NoHostAvailable:
            attempt += 1
            time.sleep(10)

    return session
示例#5
0
文件: ssl_.py 项目: Ddoudou/test
def create_urllib3_context(ssl_version=None, cert_reqs=None,
                           options=None, ciphers=None):
    """All arguments have the same meaning as ``ssl_wrap_socket``.

    By default, this function does a lot of the same work that
    ``ssl.create_default_context`` does on Python 3.4+. It:

    - Disables SSLv2, SSLv3, and compression
    - Sets a restricted set of server ciphers

    If you wish to enable SSLv3, you can do::

        from urllib3.util import ssl_
        context = ssl_.create_urllib3_context()
        context.options &= ~ssl_.OP_NO_SSLv3

    You can do the same to enable compression (substituting ``COMPRESSION``
    for ``SSLv3`` in the last line above).

    :param ssl_version:
        The desired protocol version to use. This will default to
        PROTOCOL_SSLv23 which will negotiate the highest protocol that both
        the server and your installation of OpenSSL support.
    :param cert_reqs:
        Whether to require the certificate verification. This defaults to
        ``ssl.CERT_REQUIRED``.
    :param options:
        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
    :param ciphers:
        Which cipher suites to allow the server to select.
    :returns:
        Constructed SSLContext object with specified options
    :rtype: SSLContext
    """
    context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)

    context.set_ciphers(ciphers or DEFAULT_CIPHERS)

    # Setting the default here, as we may have no ssl module on import
    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs

    if options is None:
        options = 0
        # SSLv2 is easily broken and is considered harmful and dangerous
        options |= OP_NO_SSLv2
        # SSLv3 has several problems and is now dangerous
        options |= OP_NO_SSLv3
        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
        # (issue #309)
        options |= OP_NO_COMPRESSION

    context.options |= options

    context.verify_mode = cert_reqs
    if getattr(context, 'check_hostname', None) is not None:  # Platform-specific: Python 3.2
        # We do our own verification, including fingerprints and alternative
        # hostnames. So disable it here
        context.check_hostname = False
    return context
示例#6
0
def adminLogin():
    if flask.request.method == 'GET':
        # Just render the initial form, to get input
        return (flask.render_template('adminLogin.html'))

    if flask.request.method == 'POST':
        u_id = flask.request.form['uid']
        pwd = flask.request.form['pwd']
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.verify_mode = CERT_NONE
        auth_provider = PlainTextAuthProvider(username=cfg.config['username'],
                                              password=cfg.config['password'])
        cluster = Cluster([cfg.config['contactPoint']],
                          port=cfg.config['port'],
                          auth_provider=auth_provider,
                          ssl_context=ssl_context)
        session = cluster.connect()
        #</authenticateAndConnect>
        rows = session.execute(
            "SELECT * FROM miniproj.admins WHERE admin_id=" + u_id +
            " AND password='******' ALLOW FILTERING")
        cluster.shutdown()
        if len(rows.current_rows) == 0:
            result = 'Wrong Username or Password'
        else:
            result = 'Login Successful'
        return flask.render_template('adminLogin.html', result=result)
示例#7
0
def resetAdminPassword():
    if flask.request.method == 'GET':
        # Just render the initial form, to get input
        return (flask.render_template('resetAdminPassword.html'))

    if flask.request.method == 'POST':
        subid = flask.request.form['subid']
        pwd = flask.request.form['pwd']
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.verify_mode = CERT_NONE
        auth_provider = PlainTextAuthProvider(username=cfg.config['username'],
                                              password=cfg.config['password'])
        cluster = Cluster([cfg.config['contactPoint']],
                          port=cfg.config['port'],
                          auth_provider=auth_provider,
                          ssl_context=ssl_context)
        session = cluster.connect()
        rows = session.execute(
            "SELECT * FROM miniproj.admins WHERE admin_id=" + subid)
        if len(rows.current_rows) == 0:
            cluster.shutdown()
            return flask.render_template('resetAdminPassword.html',
                                         result='Invalid Admin ID')
        #</authenticateAndConnect>
        try:
            rows = session.execute("UPDATE miniproj.admins SET password='******' WHERE admin_id = " + subid)
            result = 'Updated Successfully'
        except Exception as e:
            result = 'Error updating record'
        cluster.shutdown()
        return flask.render_template('resetAdminPassword.html', result=result)
示例#8
0
def insertAdmin():
    if flask.request.method == 'GET':
        # Just render the initial form, to get input
        return (flask.render_template('insertAdmin.html'))

    if flask.request.method == 'POST':
        name = flask.request.form['name']
        pwd = flask.request.form['pwd']
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.verify_mode = CERT_NONE
        auth_provider = PlainTextAuthProvider(username=cfg.config['username'],
                                              password=cfg.config['password'])
        cluster = Cluster([cfg.config['contactPoint']],
                          port=cfg.config['port'],
                          auth_provider=auth_provider,
                          ssl_context=ssl_context)
        session = cluster.connect()
        rows = session.execute("SELECT * FROM miniproj.admins")
        next_id = 0
        for t in rows:
            if next_id < t.admin_id:
                next_id = t.admin_id
        next_id = int(next_id) + 1
        #</authenticateAndConnect>
        try:
            rows = session.execute(
                "INSERT INTO  miniproj.admins  (admin_id, admin_name , password) VALUES (%s,%s,%s)",
                [next_id, name, pwd])
            result = 'Inserted successfully. User ID of new record is ' + str(
                next_id)
        except:
            result = 'Failed to insert'
        cluster.shutdown()
        return flask.render_template('insertAdmin.html', result=result)
示例#9
0
    def get_connection(self):
        """ Returns Cassandra session """
        auth_provider = None

        if self.ssl:
            ssl_context = SSLContext(PROTOCOL_TLSv1)
            ssl_context.load_verify_locations(path_cert)
            ssl_context.verify_mode = CERT_REQUIRED
            #ssl_options = {
            #    'ca_certs' : self.ssl,
            #    'ssl_version' : PROTOCOL_TLSv1_2
            #}
        else:
            ssl_context = None

        if (self.username and self.password):
            auth_provider = PlainTextAuthProvider(self.username, self.password)

        node1_profile = ExecutionProfile(
            load_balancing_policy=WhiteListRoundRobinPolicy(
                [self.endpoint_name]))
        profiles = {'node1': node1_profile}
        cluster = Cluster([self.endpoint_name],
                          port=self.port,
                          auth_provider=auth_provider,
                          ssl_context=ssl_context,
                          control_connection_timeout=360,
                          execution_profiles=profiles)
        session = cluster.connect()
        return session
示例#10
0
def create_context(keyfile=None, certfile=None, cert_reqs=None,
                   ca_certs=None, server_hostname=None, ssl_version=None):
        """
        All arguments except `server_hostname` have the same meaning as for
        :func:`ssl.wrap_socket`

        :param server_hostname:
            Hostname of the expected certificate
        """
        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs

        # Disable TLS compression to migitate CRIME attack (issue #309)
        OP_NO_COMPRESSION = 0x20000
        context.options |= OP_NO_COMPRESSION

        if ca_certs:
            try:
                context.load_verify_locations(ca_certs)
            # Py32 raises IOError
            # Py33 raises FileNotFoundError
            except Exception as e:  # Reraise as SSLError
                raise SSLError(e)
        if certfile:
            # FIXME: This block needs a test.
            context.load_cert_chain(certfile, keyfile)

        return context
示例#11
0
def wrap(client, _socket):
    """ Wrap socket in SSL wrapper. """
    if client.init_kwargs.get('use_ssl', None):
        keyfile = client.init_kwargs.get('ssl_keyfile', None)
        certfile = client.init_kwargs.get('ssl_certfile', None)

        if keyfile and not certfile:
            raise ValueError("certfile must be specified")

        password = client.init_kwargs.get('ssl_keyfile_password', None)
        ssl_version = client.init_kwargs.get('ssl_version',
                                             SSL_DEFAULT_VERSION)
        ciphers = client.init_kwargs.get('ssl_ciphers', SSL_DEFAULT_CIPHERS)
        cert_reqs = client.init_kwargs.get('ssl_cert_reqs', ssl.CERT_NONE)
        ca_certs = client.init_kwargs.get('ssl_ca_certfile', None)

        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs

        if ca_certs:
            context.load_verify_locations(ca_certs)
        if certfile:
            context.load_cert_chain(certfile, keyfile, password)
        if ciphers:
            context.set_ciphers(ciphers)

        _socket = context.wrap_socket(sock=_socket)

    return _socket
    def __init__(self, ip_addresses, cassandra_config):
        self._ip_addresses = ip_addresses
        self._auth_provider = None
        self._ssl_context = None
        self._cassandra_config = cassandra_config

        if cassandra_config.cql_username is not None and cassandra_config.cql_password is not None:
            auth_provider = PlainTextAuthProvider(
                username=cassandra_config.cql_username,
                password=cassandra_config.cql_password)
            self._auth_provider = auth_provider

        if cassandra_config.certfile is not None and cassandra_config.usercert is not None and \
           cassandra_config.userkey is not None:
            ssl_context = SSLContext(PROTOCOL_TLSv1)
            ssl_context.load_verify_locations(cassandra_config.certfile)
            ssl_context.verify_mode = CERT_REQUIRED
            ssl_context.load_cert_chain(certfile=cassandra_config.usercert,
                                        keyfile=cassandra_config.userkey)
            self._ssl_context = ssl_context

        load_balancing_policy = WhiteListRoundRobinPolicy(ip_addresses)
        self._execution_profiles = {
            'local':
            ExecutionProfile(load_balancing_policy=load_balancing_policy)
        }
示例#13
0
def create_ssl_context(ssl_params):
    if not ssl_params.get('use_ssl'):
        return None

    keyfile = ssl_params.get('ssl_keyfile', None)
    certfile = ssl_params.get('ssl_certfile', None)

    if keyfile and not certfile:
        raise ValueError("certfile must be specified")

    password = ssl_params.get('ssl_keyfile_password', None)
    ssl_version = ssl_params.get('ssl_version', SSL_DEFAULT_VERSION)
    ciphers = ssl_params.get('ssl_ciphers', SSL_DEFAULT_CIPHERS)
    cert_reqs = ssl_params.get('ssl_cert_reqs', ssl.CERT_NONE)
    ca_certs = ssl_params.get('ssl_ca_certfile', None)

    context = SSLContext(ssl_version)
    context.verify_mode = cert_reqs

    if ca_certs:
        context.load_verify_locations(ca_certs)
    if certfile:
        context.load_cert_chain(certfile, keyfile, password)
    if ciphers:
        context.set_ciphers(ciphers)

    return context
示例#14
0
def _ssl_context_from_cert(ca_cert_location, cert_location, key_location):
    ssl_context = SSLContext(PROTOCOL_TLS)
    ssl_context.load_verify_locations(ca_cert_location)
    ssl_context.verify_mode = CERT_REQUIRED
    ssl_context.load_cert_chain(certfile=cert_location, keyfile=key_location)

    return ssl_context
示例#15
0
    def ssl_wrap_socket(sock,
                        keyfile=None,
                        certfile=None,
                        cert_reqs=None,
                        ca_certs=None,
                        server_hostname=None,
                        ssl_version=None):
        """
        All arguments except `server_hostname` have the same meaning as for
        :func:`ssl.wrap_socket`

        :param server_hostname:
            Hostname of the expected certificate
        """
        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs
        if ca_certs:
            try:
                context.load_verify_locations(ca_certs)
            # Py32 raises IOError
            # Py33 raises FileNotFoundError
            except Exception as e:  # Reraise as SSLError
                raise SSLError(e)
        if certfile:
            # FIXME: This block needs a test.
            context.load_cert_chain(certfile, keyfile)
        if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
            return context.wrap_socket(sock, server_hostname=server_hostname)
        return context.wrap_socket(sock)
示例#16
0
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     ctx = SSLContext(ssl.PROTOCOL_SSLv23)
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2 and SSLv3. Note that up to
         # date versions of MongoDB 2.4 and above already do this,
         # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4
         # and SSLv3 in >= 3.4.3. There is no way for us to do this
         # explicitly for python 2.6 or 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
     if certfile is not None:
         if passphrase is not None:
             vi = sys.version_info
             # Since python just added a new parameter to an existing method
             # this seems to be about the best we can do.
             if (vi[0] == 2 and vi < (2, 7, 9) or vi[0] == 3 and vi <
                 (3, 3)):
                 raise ConfigurationError(
                     "Support for ssl_pem_passphrase requires "
                     "python 2.7.9+ (pypy 2.5.1+) or 3.3+")
             ctx.load_cert_chain(certfile, keyfile, passphrase)
         else:
             ctx.load_cert_chain(certfile, keyfile)
     if crlfile is not None:
         if not hasattr(ctx, "verify_flags"):
             raise ConfigurationError(
                 "Support for ssl_crlfile requires "
                 "python 2.7.9+ (pypy 2.5.1+) or  3.4+")
         # Match the server's behavior.
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         ctx.load_verify_locations(crlfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32"
               and hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     return ctx
示例#17
0
def create_urllib3_context(ssl_version=None,
                           cert_reqs=ssl.CERT_REQUIRED,
                           options=None,
                           ciphers=None):
    """All arguments have the same meaning as ``ssl_wrap_socket``.

    By default, this function does a lot of the same work that
    ``ssl.create_default_context`` does on Python 3.4+. It:

    - Disables SSLv2, SSLv3, and compression
    - Sets a restricted set of server ciphers

    If you wish to enable SSLv3, you can do::

        from urllib3.util import ssl_
        context = ssl_.create_urllib3_context()
        context.options &= ~ssl_.OP_NO_SSLv3

    You can do the same to enable compression (substituting ``COMPRESSION``
    for ``SSLv3`` in the last line above).

    :param ssl_version:
        The desired protocol version to use. This will default to
        PROTOCOL_SSLv23 which will negotiate the highest protocol that both
        the server and your installation of OpenSSL support.
    :param cert_reqs:
        Whether to require the certificate verification. This defaults to
        ``ssl.CERT_REQUIRED``.
    :param options:
        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
    :param ciphers:
        Which cipher suites to allow the server to select.
    :returns:
        Constructed SSLContext jeeObject with specified options
    :rtype: SSLContext
    """
    context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)

    if options is None:
        options = 0
        # SSLv2 is easily broken and is considered harmful and dangerous
        options |= OP_NO_SSLv2
        # SSLv3 has several problems and is now dangerous
        options |= OP_NO_SSLv3
        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
        # (issue #309)
        options |= OP_NO_COMPRESSION

    context.options |= options

    if getattr(context, 'supports_set_ciphers',
               True):  # Platform-specific: Python 2.6
        context.set_ciphers(ciphers or _DEFAULT_CIPHERS)

    context.verify_mode = cert_reqs
    if getattr(context, 'check_hostname',
               None) is not None:  # Platform-specific: Python 3.2
        context.check_hostname = (context.verify_mode == ssl.CERT_REQUIRED)
    return context
示例#18
0
def sslContext(trustStore: str, keyStore: str) -> SSLContext:
    sslContext = SSLContext(PROTOCOL_TLSv1_2)
    sslContext.verify_mode = CERT_REQUIRED
    storePath = "../../certificates/"
    sslContext.load_verify_locations(storePath + trustStore)
    sslContext.load_cert_chain(storePath + keyStore, password="******")
    sslContext.set_ciphers("AES128-SHA")
    return sslContext
示例#19
0
def sslContext(trustStore: str, keyStore: str) -> SSLContext:
    sslContext = SSLContext(PROTOCOL_TLSv1_2)
    sslContext.verify_mode = CERT_REQUIRED
    storePath = "../../certificates/"
    sslContext.load_verify_locations(storePath + trustStore)
    sslContext.load_cert_chain(storePath + keyStore, password="******")
    sslContext.set_ciphers("AES128-SHA")
    return sslContext
示例#20
0
	def __init__(self, ssl_context: ssl.SSLContext, port: int):
		ssl_context.verify_mode = ssl.CERT_REQUIRED
		self.ssl_context = ssl_context
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
		self.port = port
		self.sock.bind(("", port))
		self.sock.listen(10)
		self.worker_thread = threading.Thread(target=self.worker_func)
示例#21
0
 def secure(self, verify=True, hostname=None):
     """ Apply a layer of security onto this connection.
     """
     from ssl import SSLContext, PROTOCOL_TLS, CERT_NONE, CERT_REQUIRED
     context = SSLContext(PROTOCOL_TLS)
     if verify:
         context.verify_mode = CERT_REQUIRED
         context.check_hostname = bool(hostname)
     else:
         context.verify_mode = CERT_NONE
     context.load_default_certs()
     try:
         self.__socket = context.wrap_socket(self.__socket,
                                             server_hostname=hostname)
     except (IOError, OSError):
         # TODO: add connection failure/diagnostic callback
         raise WireError(
             "Unable to establish secure connection with remote peer")
示例#22
0
def getSSLContext(capath, crtpath, keypath, keypass=None):
    ctx = SSLContext(PROTOCOL_TLSv1_2)
    ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
    # client certificate is required
    ctx.verify_mode = CERT_REQUIRED
    ctx.options |= OP_NO_COMPRESSION
    ctx.load_verify_locations(capath)
    ctx.load_cert_chain(crtpath, keypath, password=keypass)
    return ctx
示例#23
0
文件: irc.py 项目: Xeronel/CipherBot
    def __init__(self, host: str, port: int, nicks: list, pwd: str, chans: list, op_pass: str,
                 use_ssl: bool=False, ssl_options: ssl.SSLContext=None,
                 encoding: str='utf-8'):
        """
        Asynchronous IRC client
        :param host: Server address
        :param port: IRC Port
        :param nicks: List of nicknames to try
        :param pwd: NickServ password
        :param use_ssl: Enable/Disable SSL
        :param ssl_options: SSLContext object
        :param encoding: Character encoding to use
        """
        self.host = host
        self.port = port
        self.nicks = nicks
        self.pwd = pwd
        self.chans = chans
        self.oper_pass = op_pass
        self.ssl = use_ssl
        self.encoding = encoding
        self.__nickidx = 0
        self.__handlers = {
            b'PING': self.__ping,
            b'NOTICE': self.__notice,
            b'PRIVMSG': self.__privmsg,
            b'PART': self.__part,
            b'JOIN': self.__join,
            b'MODE': self.__mode,
            b'NICK': self.__nick,
            b'QUIT': self.__quit,
            b'KICK': self.__kick,
            b'001': self.__welcome,
            b'251': self.__user_count,
            b'252': self.__op_count,
            b'353': self.__namreply,
            b'372': self.__motd,
            b'376': self.__end_motd,
            b'433': self.__nick_in_use,
            b'900': self.__logged_in
        }

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)

        if use_ssl:
            if not ssl_options:
                ssl_options = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                # IRC often has unsigned certs, by default do not verify
                ssl_options.verify_mode = ssl.CERT_NONE
            sock = ssl.wrap_socket(sock, do_handshake_on_connect=False)
            self.stream = tornado.iostream.SSLIOStream(sock, ssl_options=ssl_options)
        else:
            self.stream = tornado.iostream.IOStream(sock)

        self.stream.connect((self.host, self.port),
                            self.__initial_auth,
                            server_hostname=self.host)
示例#24
0
    def __get_ssl_context(cls, sslca=None):
        """Make an SSLConext for this Python version using public or sslca
        """
        if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 9)) or
                (version_info[0] == 3 and version_info[1] >= 4)):
            logger.debug('SSL method for 2.7.9+ / 3.4+')
            # pylint: disable=no-name-in-module
            from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION
            ctx = SSLContext(PROTOCOL_TLSv1_2)
            ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
            # see CRIME security exploit
            ctx.options |= OP_NO_COMPRESSION
            # the following options are used to verify the identity of the broker
            if sslca:
                ctx.load_verify_locations(sslca)
                ctx.verify_mode = CERT_REQUIRED
                ctx.check_hostname = False
            else:
                # Verify public certifcates if sslca is None (default)
                from ssl import Purpose  # pylint: disable=no-name-in-module
                ctx.load_default_certs(purpose=Purpose.SERVER_AUTH)
                ctx.verify_mode = CERT_REQUIRED
                ctx.check_hostname = True

        elif version_info[0] == 3 and version_info[1] < 4:
            logger.debug('Using SSL method for 3.2+, < 3.4')
            # pylint: disable=no-name-in-module
            from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
            ctx = SSLContext(PROTOCOL_SSLv23)
            ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1)
            ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
            # the following options are used to verify the identity of the broker
            if sslca:
                ctx.load_verify_locations(sslca)
                ctx.verify_mode = CERT_REQUIRED
            else:
                # Verify public certifcates if sslca is None (default)
                ctx.set_default_verify_paths()
                ctx.verify_mode = CERT_REQUIRED

        else:
            raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3]))

        return ctx
示例#25
0
    def __get_ssl_context(cls, sslca=None):
        """Make an SSLConext for this Python version using public or sslca
        """
        if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or
                (version_info[0] == 3 and version_info[1] >= 4)):
            logger.debug('SSL method for 2.7.5+ / 3.4+')
            # pylint: disable=no-name-in-module,import-outside-toplevel
            from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION
            ctx = SSLContext(PROTOCOL_TLSv1_2)
            ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
            # see CRIME security exploit
            ctx.options |= OP_NO_COMPRESSION
            # the following options are used to verify the identity of the broker
            if sslca:
                ctx.load_verify_locations(sslca)
                ctx.verify_mode = CERT_REQUIRED
                ctx.check_hostname = False
            else:
                # Verify public certifcates if sslca is None (default)
                from ssl import Purpose  # pylint: disable=no-name-in-module,import-outside-toplevel
                ctx.load_default_certs(purpose=Purpose.SERVER_AUTH)
                ctx.verify_mode = CERT_REQUIRED
                ctx.check_hostname = True

        elif version_info[0] == 3 and version_info[1] < 4:
            logger.debug('Using SSL method for 3.2+, < 3.4')
            # pylint: disable=no-name-in-module,import-outside-toplevel
            from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
            ctx = SSLContext(PROTOCOL_SSLv23)
            ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1)
            ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH')
            # the following options are used to verify the identity of the broker
            if sslca:
                ctx.load_verify_locations(sslca)
                ctx.verify_mode = CERT_REQUIRED
            else:
                # Verify public certifcates if sslca is None (default)
                ctx.set_default_verify_paths()
                ctx.verify_mode = CERT_REQUIRED

        else:
            raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3]))

        return ctx
示例#26
0
 def to_ssl_context(self):
     # See https://docs.python.org/3.7/library/ssl.html#protocol-versions
     from ssl import SSLContext, PROTOCOL_TLS_CLIENT, OP_NO_TLSv1, OP_NO_TLSv1_1, CERT_REQUIRED
     ssl_context = SSLContext(PROTOCOL_TLS_CLIENT)
     ssl_context.options |= OP_NO_TLSv1
     ssl_context.options |= OP_NO_TLSv1_1
     if self.verify_cert:
         ssl_context.verify_mode = CERT_REQUIRED
     ssl_context.set_default_verify_paths()
     return ssl_context
示例#27
0
    def context(self) -> Optional[SSLContext]:
        if self.ssl:
            self.logger.info("Setting up SSL")
            context = SSLContext(PROTOCOL_TLS)
            if self.cert and self.key:
                self.logger.info("Using SSL Cert: %s", self.cert)
                try:
                    context.load_cert_chain(str(self.cert),
                                            str(self.key),
                                            password=self.key_password)
                except FileNotFoundError as e:
                    raise FileNotFoundError(
                        better_file_not_found_error(
                            self.cert, self.key, purpose='ssl cert loading'))
                if self.warn_if_expires_before_days:
                    self._warn_expiry_task = create_task(
                        self.check_cert_expiry())
                    set_task_name(self._warn_expiry_task,
                                  'CheckSSLCertValidity')
            context.verify_mode = CERT_REQUIRED if self.cert_required else CERT_NONE
            context.check_hostname = self.check_hostname
            self.logger.info('%s, Check Hostname: %s' %
                             (context.verify_mode, context.check_hostname))

            if context.verify_mode != CERT_NONE:
                if self.cafile or self.capath or self.cadata:
                    locations = {
                        'cafile': str(self.cafile) if self.cafile else None,
                        'capath': str(self.capath) if self.capath else None,
                        'cadata': self.cadata
                    }
                    try:
                        context.load_verify_locations(**locations)
                        self.logger.info("Verifying SSL certs with: %s",
                                         locations)
                    except FileNotFoundError:
                        raise FileNotFoundError(
                            better_file_not_found_error(
                                *locations.values(),
                                purpose='CA ssl cert validation'))
                else:
                    context.load_default_certs(self.purpose)
                    self.logger.info("Verifying SSL certs with: %s",
                                     get_default_verify_paths())
            self.logger.info("SSL Context loaded")
            # OpenSSL 1.1.1 keylog file
            if hasattr(context, 'keylog_filename'):
                keylogfile = os.environ.get('SSLKEYLOGFILE')
                if keylogfile and not sys.flags.ignore_environment:
                    self.logger.warning(
                        "TLS encryption secrets are being stored in %s",
                        keylogfile)
                    context.keylog_filename = keylogfile
            return context
        return None
示例#28
0
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     certfile, keyfile, ca_certs, cert_reqs = args
     ctx = SSLContext(ssl.PROTOCOL_SSLv23)
     if certfile is not None:
         ctx.load_cert_chain(certfile, keyfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     if cert_reqs is not None:
         ctx.verify_mode = cert_reqs
     return ctx
示例#29
0
 def load_TLS(self):
     context = SSLContext(PROTOCOL_TLS)
     context.minimum_version = TLSVersion.TLSv1_3
     context.verify_mode = CERT_REQUIRED
     context.check_hostname = True
     if self.CA != 'default' and self.CA != '':
         context.load_verify_locations(self.CA)
     else:
         context.load_default_certs()
     self.server = create_connection((self.SERVER_HOST, self.SERVER_PORT))
     self.server = context.wrap_socket(self.server, server_hostname=self.SERVER_HOST)
示例#30
0
 def __init__(self):
     ssl_context = SSLContext(PROTOCOL_TLSv1_2)
     ssl_context.load_verify_locations('.cassandra/AmazonRootCA1.pem')
     ssl_context.verify_mode = CERT_REQUIRED
     auth_provider = PlainTextAuthProvider(username='******',
                                           password='******')
     self.cluster = Cluster(['cassandra.us-east-1.amazonaws.com'],
                            ssl_context=ssl_context,
                            auth_provider=auth_provider,
                            port=9142)
     self.session = self.cluster.connect("test_keyspace")
示例#31
0
 def __init__(self):
     user = os.getenv("PG_USER", 'postgres')
     password = os.getenv("PG_PASSWORD", None)
     self._database = os.getenv("PG_DATABASE", 'postgres')
     host = os.getenv("PG_HOST", 'localhost')
     port = int(os.getenv("PG_PORT", '5432'))
     ssl_context = SSLContext()
     ssl_context.check_hostname = False
     ssl_context.verify_mode = ssl.CERT_NONE
     self._con = pg8000.connect(user, host, self._database, port, password)
     self._con.autocommit = True
     self._create_schema()
示例#32
0
文件: redis.py 项目: ttbud/ttbud
async def create_redis_pool(address: str,
                            ssl_validation: SSLValidation) -> Redis:
    ssl_context: Union[SSLContext, bool]
    if ssl_validation == SSLValidation.SELF_SIGNED:
        ssl_context = SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.VerifyMode.CERT_NONE
    elif ssl_validation == SSLValidation.NONE:
        ssl_context = False
    else:
        ssl_context = ssl.create_default_context()

    return await aioredis.create_redis_pool(address, ssl=ssl_context)
示例#33
0
def create_session(url: str, port: int, context: ssl.SSLContext = ssl.create_default_context()):
    """
    Create a secure connection to any server on any port with a defined context
    on a specific timeout.

    :param url: url of the website
    :param context: ssl context
    :param port: port
    :return: created secure socket
    """
    cert_verified = True
    context.check_hostname = True
    context.verify_mode = ssl.VerifyMode.CERT_REQUIRED
    sleep = 0
    # Loop until there is a valid response or after 15 seconds
    # because of rate limiting on some servers
    while True:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)  # in seconds
        # context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        ssl_socket = context.wrap_socket(sock, server_hostname=url)
        try:
            logging.debug(f'connecting... (main connection)')
            ssl_socket.connect((url, port))
            break
        except ssl.SSLCertVerificationError:
            cert_verified = False
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        except socket.timeout:
            raise ConnectionTimeoutError()
        except socket.gaierror:
            raise DNSError()
        except ConnectionResetError as e:
            raise UnknownConnectionError(e)
        except socket.error as e:
            ssl_socket.close()
            sleep = incremental_sleep(sleep, e, 1)
    return ssl_socket, cert_verified
示例#34
0
    def instance(cls, keyspace_name: str = None):
        if cls._instance is None:
            print('Creating new instance of Cosmos Factory')
            cls._instance = cls.__new__(cls)

            # Put any initialization here.
            ssl_opts = {
                'ca_certs': DEFAULT_CA_BUNDLE_PATH,
                'ssl_version': PROTOCOL_TLSv1_2,
            }

            if 'certpath' in cfg.config:
                ssl_opts['ca_certs'] = cfg.config['certpath']

            ssl_context = SSLContext(PROTOCOL_TLSv1_2)
            ssl_context.verify_mode = CERT_NONE

            auth_provider = PlainTextAuthProvider(
                username=cfg.config['username'],
                password=cfg.config['password'])
            # cluster = Cluster([cfg.config['contactPoint']], port=int(cfg.config['port']), auth_provider=auth_provider,
            #                  ssl_options=ssl_opts, connect_timeout=600)

            cluster = Cluster([cfg.config['contactPoint']],
                              port=int(cfg.config['port']),
                              auth_provider=auth_provider,
                              ssl_context=ssl_context,
                              connect_timeout=600)
            cls._instance.session = cluster.connect()

            # self.create_keyspace(name='bitemporaldb', strategy_type='NetworkTopologyStrategy',  dc_name='datacenter',repl_factor=1)

            if keyspace_name == None and 'keyspace' in cfg.config and not cfg.config[
                    'keyspace']:

                cls._instance.name = "_" + timestamp_helper.get_timestamp()

                cls._instance.create_keyspace(
                    name=cls._instance.name,
                    strategy_type='NetworkTopologyStrategy',
                    dc_name='datacenter',
                    repl_factor=1)
            else:
                if keyspace_name == None and 'keyspace' in cfg.config and cfg.config[
                        'keyspace']:
                    cls._instance.name = cfg.config['keyspace']
                else:
                    cls._instance.name = keyspace_name

        return cls._instance
示例#35
0
 def __init__(self):
     ssl_context = SSLContext(PROTOCOL_TLSv1_2)
     ssl_context.verify_mode = CERT_NONE
     auth_provider = PlainTextAuthProvider(
                                             username=cfg.config['username'], 
                                             password=cfg.config['password'])
     
     self.cluster = Cluster([cfg.config['contactPoint']], 
                            port=cfg.config['port'],
                            auth_provider=auth_provider, 
                            ssl_context=ssl_context)
     self.session = None
     self.keyspace = None
     self.log = None
示例#36
0
文件: ssl_.py 项目: connoryang/1v1dec
def create_urllib3_context(ssl_version = None, cert_reqs = None, options = None, ciphers = None):
    context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
    if options is None:
        options = 0
        options |= OP_NO_SSLv2
        options |= OP_NO_SSLv3
        options |= OP_NO_COMPRESSION
    context.options |= options
    if getattr(context, 'supports_set_ciphers', True):
        context.set_ciphers(ciphers or DEFAULT_CIPHERS)
    context.verify_mode = cert_reqs
    if getattr(context, 'check_hostname', None) is not None:
        context.check_hostname = False
    return context
示例#37
0
def create_thriftpy_context(server_side=False, ciphers=None):
    """Backport create_default_context for older python versions.

    The SSLContext has some default security options, you can disable them
    manually, for example::

        from thriftpy.transport import _ssl
        context = _ssl.create_thriftpy_context()
        context.options &= ~_ssl.OP_NO_SSLv3

    You can do the same to enable compression.
    """
    if MODERN_SSL:
        if server_side:
            context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        else:
            context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)

        if ciphers:
            context.set_ciphers(ciphers)

    else:
        context = SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= OP_NO_SSLv2
        context.options |= OP_NO_SSLv3
        context.options |= OP_NO_COMPRESSION

        # server/client default options
        if server_side:
            context.options |= OP_CIPHER_SERVER_PREFERENCE
            context.options |= OP_SINGLE_DH_USE
            context.options |= OP_SINGLE_ECDH_USE
        else:
            context.verify_mode = ssl.CERT_REQUIRED
            # context.check_hostname = True
            warnings.warn(
                "ssl check hostname support disabled, upgrade your python",
                InsecurePlatformWarning)

        # Platform-specific: Python 2.6
        if getattr(context, 'supports_set_ciphers', True):
            if ciphers:
                context.set_ciphers(ciphers)
        else:
            warnings.warn("ssl ciphers support disabled, upgrade your python",
                          InsecurePlatformWarning)

    return context
def updateSubject():
    if flask.request.method == 'GET':
        # Just render the initial form, to get input
        return (flask.render_template('updateSubject.html')), 200

    if flask.request.method == 'POST':
        subid = flask.request.form['subid']
        name = flask.request.form['name']
        year = flask.request.form['year']
        time = flask.request.form['time']
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.verify_mode = CERT_NONE
        auth_provider = PlainTextAuthProvider(username=cfg.config['username'],
                                              password=cfg.config['password'])
        cluster = Cluster([cfg.config['contactPoint']],
                          port=cfg.config['port'],
                          auth_provider=auth_provider,
                          ssl_context=ssl_context)
        session = cluster.connect()
        # Retreive data with existing subjects from the DB
        rows = session.execute(
            "SELECT * FROM miniproj.subjects WHERE subject_id=" + subid)
        if len(rows.current_rows) == 0:
            cluster.shutdown()
            return flask.render_template('updateSubject.html',
                                         result='Invalid Subject ID'), 400
        # Retreive data with existing subjects and schedule from the DB
        rows = session.execute("SELECT * FROM miniproj.subjects WHERE year='" +
                               year + "' AND time='" + time +
                               "' ALLOW FILTERING")
        # Check for clashes between subjects
        if len(rows.current_rows) > 0:
            cluster.shutdown()
            return flask.render_template(
                'insertSubject.html',
                result='Clash detected. Please enter a new time.'), 400
        #</authenticateAndConnect>
        try:
            # Edit selected subject information (name, year, time, subject id)
            rows = session.execute(
                "UPDATE miniproj.subjects SET subject_name='" + name +
                "', year='" + year + "', time='" + time +
                "' WHERE subject_id = " + subid)
            result = 'Updated Successfully'
        except Exception as e:
            result = 'Error updating record'
        cluster.shutdown()
        return flask.render_template('updateStudent.html', result=result), 200
示例#39
0
文件: _ssl.py 项目: 10sr/hue
def create_thriftpy_context(server_side=False, ciphers=None):
    """Backport create_default_context for older python versions.

    The SSLContext has some default security options, you can disable them
    manually, for example::

        from thriftpy.transport import _ssl
        context = _ssl.create_thriftpy_context()
        context.options &= ~_ssl.OP_NO_SSLv3

    You can do the same to enable compression.
    """
    if MODERN_SSL:
        if server_side:
            context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        else:
            context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)

        if ciphers:
            context.set_ciphers(ciphers)

    else:
        context = SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= OP_NO_SSLv2
        context.options |= OP_NO_SSLv3
        context.options |= OP_NO_COMPRESSION

        # server/client default options
        if server_side:
            context.options |= OP_CIPHER_SERVER_PREFERENCE
            context.options |= OP_SINGLE_DH_USE
            context.options |= OP_SINGLE_ECDH_USE
        else:
            context.verify_mode = ssl.CERT_REQUIRED
            # context.check_hostname = True
            warnings.warn(
                "ssl check hostname support disabled, upgrade your python",
                InsecurePlatformWarning)

        # Platform-specific: Python 2.6
        if getattr(context, 'supports_set_ciphers', True):
            if ciphers:
                context.set_ciphers(ciphers)
        else:
            warnings.warn("ssl ciphers support disabled, upgrade your python",
                          InsecurePlatformWarning)

    return context
示例#40
0
    def ssl_wrap_socket(sock, keyfile = None, certfile = None, cert_reqs = None, ca_certs = None, server_hostname = None, ssl_version = None):
        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs
        OP_NO_COMPRESSION = 131072
        context.options |= OP_NO_COMPRESSION
        if ca_certs:
            try:
                context.load_verify_locations(ca_certs)
            except Exception as e:
                raise SSLError(e)

        if certfile:
            context.load_cert_chain(certfile, keyfile)
        if HAS_SNI:
            return context.wrap_socket(sock, server_hostname=server_hostname)
        return context.wrap_socket(sock)
示例#41
0
文件: ssl_support.py 项目: Alpus/Eth
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     certfile, keyfile, ca_certs, cert_reqs = args
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     ctx = SSLContext(ssl.PROTOCOL_SSLv23)
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2 and SSLv3. Note that up to
         # date versions of MongoDB 2.4 and above already do this,
         # python disables SSLv2 by default in >= 2.7.7 and >= 3.3.4
         # and SSLv3 in >= 3.4.3. There is no way for us to do this
         # explicitly for python 2.6 or 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
     if certfile is not None:
         ctx.load_cert_chain(certfile, keyfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32" and
               hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     return ctx
示例#42
0
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
                    ca_certs=None, server_hostname=None,
                    ssl_version=None):
    context = SSLContext(ssl_version)
    context.verify_mode = cert_reqs

    if ca_certs:
        try:
            context.load_verify_locations(ca_certs)
        # Py32 raises IOError   
        # Py33 raises FileNotFoundError
        except Exception as e:  # Reraise as SSLError
            raise SSLError(e)

    if certfile:
        # FIXME: This block needs a test.
        context.load_cert_chain(certfile, keyfile)

    if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
        return (context, context.wrap_socket(sock, server_hostname=server_hostname))

    return (context, context.wrap_socket(sock))
示例#43
0
    def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=CERT_NONE,
                        ca_certs=None, server_hostname=None,
                        ssl_version=PROTOCOL_SSLv23):
        """
        All arguments except `server_hostname` have the same meaning as for
        :func:`ssl.wrap_socket`

        :param server_hostname:
            Hostname of the expected certificate
        """
        context = SSLContext(ssl_version)
        context.verify_mode = cert_reqs
        if ca_certs:
            try:
                context.load_verify_locations(ca_certs)
            except TypeError as e:  # Reraise as SSLError
                # FIXME: This block needs a test.
                raise SSLError(e)
        if certfile:
            # FIXME: This block needs a test.
            context.load_cert_chain(certfile, keyfile)
        if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
            return context.wrap_socket(sock, server_hostname=server_hostname)
        return context.wrap_socket(sock)
示例#44
0
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     certfile, keyfile, passphrase, ca_certs, cert_reqs, crlfile = args
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating
     # PROTOCOL_SSLv23.
     ctx = SSLContext(
         getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23))
     # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4.
     # PROTOCOL_TLS_CLIENT enables it by default. Using it
     # requires passing server_hostname to wrap_socket, which we already
     # do for SNI support. To support older versions of Python we have to
     # call match_hostname directly, so we disable check_hostname explicitly
     # to avoid calling match_hostname twice.
     if hasattr(ctx, "check_hostname"):
         ctx.check_hostname = False
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that
         # up to date versions of MongoDB 2.4 and above already disable
         # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7
         # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do
         # any of this explicitly for python 2.6 or 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
         # OpenSSL >= 1.0.0
         ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0)
     if certfile is not None:
         try:
             if passphrase is not None:
                 vi = sys.version_info
                 # Since python just added a new parameter to an existing method
                 # this seems to be about the best we can do.
                 if (vi[0] == 2 and vi < (2, 7, 9) or
                         vi[0] == 3 and vi < (3, 3)):
                     raise ConfigurationError(
                         "Support for ssl_pem_passphrase requires "
                         "python 2.7.9+ (pypy 2.5.1+) or 3.3+")
                 ctx.load_cert_chain(certfile, keyfile, passphrase)
             else:
                 ctx.load_cert_chain(certfile, keyfile)
         except ssl.SSLError as exc:
             raise ConfigurationError(
                 "Private key doesn't match certificate: %s" % (exc,))
     if crlfile is not None:
         if not hasattr(ctx, "verify_flags"):
             raise ConfigurationError(
                 "Support for ssl_crlfile requires "
                 "python 2.7.9+ (pypy 2.5.1+) or  3.4+")
         # Match the server's behavior.
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         ctx.load_verify_locations(crlfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32" and
               hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     return ctx
 def get_ssl_context(*args):
     """Create and return an SSLContext object."""
     (certfile,
      keyfile,
      passphrase,
      ca_certs,
      cert_reqs,
      crlfile,
      match_hostname) = args
     verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
     # Note PROTOCOL_SSLv23 is about the most misleading name imaginable.
     # This configures the server and client to negotiate the
     # highest protocol version they both support. A very good thing.
     # PROTOCOL_TLS_CLIENT was added in CPython 3.6, deprecating
     # PROTOCOL_SSLv23.
     ctx = SSLContext(
         getattr(ssl, "PROTOCOL_TLS_CLIENT", ssl.PROTOCOL_SSLv23))
     # SSLContext.check_hostname was added in CPython 2.7.9 and 3.4.
     # PROTOCOL_TLS_CLIENT (added in Python 3.6) enables it by default.
     if hasattr(ctx, "check_hostname"):
         if _PY37PLUS and verify_mode != ssl.CERT_NONE:
             # Python 3.7 uses OpenSSL's hostname matching implementation
             # making it the obvious version to start using this with.
             # Python 3.6 might have been a good version, but it suffers
             # from https://bugs.python.org/issue32185.
             # We'll use our bundled match_hostname for older Python
             # versions, which also supports IP address matching
             # with Python < 3.5.
             ctx.check_hostname = match_hostname
         else:
             ctx.check_hostname = False
     if hasattr(ctx, "options"):
         # Explicitly disable SSLv2, SSLv3 and TLS compression. Note that
         # up to date versions of MongoDB 2.4 and above already disable
         # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7
         # and >= 3.3.4 and SSLv3 in >= 3.4.3. There is no way for us to do
         # any of this explicitly for python 2.7 before 2.7.9.
         ctx.options |= getattr(ssl, "OP_NO_SSLv2", 0)
         ctx.options |= getattr(ssl, "OP_NO_SSLv3", 0)
         # OpenSSL >= 1.0.0
         ctx.options |= getattr(ssl, "OP_NO_COMPRESSION", 0)
         # Python 3.7+ with OpenSSL >= 1.1.0h
         ctx.options |= getattr(ssl, "OP_NO_RENEGOTIATION", 0)
     if certfile is not None:
         try:
             if passphrase is not None:
                 vi = sys.version_info
                 # Since python just added a new parameter to an existing method
                 # this seems to be about the best we can do.
                 if (vi[0] == 2 and vi < (2, 7, 9) or
                         vi[0] == 3 and vi < (3, 3)):
                     raise ConfigurationError(
                         "Support for ssl_pem_passphrase requires "
                         "python 2.7.9+ (pypy 2.5.1+) or 3.3+")
                 ctx.load_cert_chain(certfile, keyfile, passphrase)
             else:
                 ctx.load_cert_chain(certfile, keyfile)
         except ssl.SSLError as exc:
             raise ConfigurationError(
                 "Private key doesn't match certificate: %s" % (exc,))
     if crlfile is not None:
         if not hasattr(ctx, "verify_flags"):
             raise ConfigurationError(
                 "Support for ssl_crlfile requires "
                 "python 2.7.9+ (pypy 2.5.1+) or  3.4+")
         # Match the server's behavior.
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         ctx.load_verify_locations(crlfile)
     if ca_certs is not None:
         ctx.load_verify_locations(ca_certs)
     elif cert_reqs != ssl.CERT_NONE:
         # CPython >= 2.7.9 or >= 3.4.0, pypy >= 2.5.1
         if hasattr(ctx, "load_default_certs"):
             ctx.load_default_certs()
         # Python >= 3.2.0, useless on Windows.
         elif (sys.platform != "win32" and
               hasattr(ctx, "set_default_verify_paths")):
             ctx.set_default_verify_paths()
         elif sys.platform == "win32" and HAVE_WINCERTSTORE:
             with _WINCERTSLOCK:
                 if _WINCERTS is None:
                     _load_wincerts()
             ctx.load_verify_locations(_WINCERTS.name)
         elif HAVE_CERTIFI:
             ctx.load_verify_locations(certifi.where())
         else:
             raise ConfigurationError(
                 "`ssl_cert_reqs` is not ssl.CERT_NONE and no system "
                 "CA certificates could be loaded. `ssl_ca_certs` is "
                 "required.")
     ctx.verify_mode = verify_mode
     return ctx
示例#46
0
def open_url(url, data=None, headers=None, method=None, use_proxy=True,
        force=False, last_mod_time=None, timeout=10, validate_certs=True,
        url_username=None, url_password=None, http_agent=None, force_basic_auth=False):
    '''
    Fetches a file from an HTTP/FTP server using urllib2
    '''
    handlers = []
    # FIXME: change the following to use the generic_urlparse function
    #        to remove the indexed references for 'parsed'
    parsed = urlparse.urlparse(url)
    if parsed[0] == 'https' and validate_certs:
        if not HAS_SSL:
            raise NoSSLError('SSL validation is not available in your version of python. You can use validate_certs=False, however this is unsafe and not recommended')

        # do the cert validation
        netloc = parsed[1]
        if '@' in netloc:
            netloc = netloc.split('@', 1)[1]
        if ':' in netloc:
            hostname, port = netloc.split(':', 1)
            port = int(port)
        else:
            hostname = netloc
            port = 443
        # create the SSL validation handler and
        # add it to the list of handlers
        ssl_handler = SSLValidationHandler(hostname, port)
        handlers.append(ssl_handler)

    if parsed[0] != 'ftp':
        username = url_username

        if username:
            password = url_password
            netloc = parsed[1]
        elif '@' in parsed[1]:
            credentials, netloc = parsed[1].split('@', 1)
            if ':' in credentials:
                username, password = credentials.split(':', 1)
            else:
                username = credentials
                password = ''

            parsed = list(parsed)
            parsed[1] = netloc

            # reconstruct url without credentials
            url = urlparse.urlunparse(parsed)

        if username and not force_basic_auth:
            passman = urllib2.HTTPPasswordMgrWithDefaultRealm()

            # this creates a password manager
            passman.add_password(None, netloc, username, password)

            # because we have put None at the start it will always
            # use this username/password combination for  urls
            # for which `theurl` is a super-url
            authhandler = urllib2.HTTPBasicAuthHandler(passman)

            # create the AuthHandler
            handlers.append(authhandler)

        elif username and force_basic_auth:
            if headers is None:
                headers = {}

            headers["Authorization"] = "Basic %s" % base64.b64encode("%s:%s" % (username, password))

    if not use_proxy:
        proxyhandler = urllib2.ProxyHandler({})
        handlers.append(proxyhandler)

    # pre-2.6 versions of python cannot use the custom https
    # handler, since the socket class is lacking create_connection.
    # Some python builds lack HTTPS support.
    if hasattr(socket, 'create_connection') and CustomHTTPSHandler:
        handlers.append(CustomHTTPSHandler)

    opener = urllib2.build_opener(*handlers)
    urllib2.install_opener(opener)

    if method:
        if method.upper() not in ('OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT','PATCH'):
            raise ConnectionError('invalid HTTP request method; %s' % method.upper())
        request = RequestWithMethod(url, method.upper(), data)
    else:
        request = urllib2.Request(url, data)

    # add the custom agent header, to help prevent issues
    # with sites that block the default urllib agent string
    request.add_header('User-agent', http_agent)

    # if we're ok with getting a 304, set the timestamp in the
    # header, otherwise make sure we don't get a cached copy
    if last_mod_time and not force:
        tstamp = last_mod_time.strftime('%a, %d %b %Y %H:%M:%S +0000')
        request.add_header('If-Modified-Since', tstamp)
    else:
        request.add_header('cache-control', 'no-cache')

    # user defined headers now, which may override things we've set above
    if headers:
        if not isinstance(headers, dict):
            raise ValueError("headers provided to fetch_url() must be a dict")
        for header in headers:
            request.add_header(header, headers[header])

    urlopen_args = [request, None]
    if sys.version_info >= (2,6,0):
        # urlopen in python prior to 2.6.0 did not
        # have a timeout parameter
        urlopen_args.append(timeout)

    if HAS_SSLCONTEXT and not validate_certs:
        # In 2.7.9, the default context validates certificates
        context = SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= ssl.OP_NO_SSLv2
        context.options |= ssl.OP_NO_SSLv3
        context.verify_mode = ssl.CERT_NONE
        context.check_hostname = False
        urlopen_args += (None, None, None, context)

    r = urllib2.urlopen(*urlopen_args)
    return r
示例#47
0
from __future__ import absolute_import, division, print_function

from ssl import CERT_NONE, PROTOCOL_SSLv23, SSLContext

from psphere.client import Client

if __name__ == '__main__':
    context = SSLContext(PROTOCOL_SSLv23)
    context.verify_mode = CERT_NONE
    test_client = Client('localhost:8989', 'user', 'pass', sslcontext=context)
    print(test_client.si.CurrentTime())
    test_client.logout()
示例#48
0
def open_url(url, data=None, headers=None, method=None, use_proxy=True,
             force=False, last_mod_time=None, timeout=10, validate_certs=True,
             url_username=None, url_password=None, http_agent=None,
             force_basic_auth=False, follow_redirects='urllib2'):
    '''
    Sends a request via HTTP(S) or FTP using urllib2 (Python2) or urllib (Python3)

    Does not require the module environment
    '''
    handlers = []
    ssl_handler = maybe_add_ssl_handler(url, validate_certs)
    if ssl_handler:
        handlers.append(ssl_handler)

    # FIXME: change the following to use the generic_urlparse function
    #        to remove the indexed references for 'parsed'
    parsed = urlparse(url)
    if parsed[0] != 'ftp':
        username = url_username

        if headers is None:
            headers = {}

        if username:
            password = url_password
            netloc = parsed[1]
        elif '@' in parsed[1]:
            credentials, netloc = parsed[1].split('@', 1)
            if ':' in credentials:
                username, password = credentials.split(':', 1)
            else:
                username = credentials
                password = ''

            parsed = list(parsed)
            parsed[1] = netloc

            # reconstruct url without credentials
            url = urlunparse(parsed)

        if username and not force_basic_auth:
            passman = urllib_request.HTTPPasswordMgrWithDefaultRealm()

            # this creates a password manager
            passman.add_password(None, netloc, username, password)

            # because we have put None at the start it will always
            # use this username/password combination for  urls
            # for which `theurl` is a super-url
            authhandler = urllib_request.HTTPBasicAuthHandler(passman)

            # create the AuthHandler
            handlers.append(authhandler)

        elif username and force_basic_auth:
            headers["Authorization"] = basic_auth_header(username, password)

        else:
            try:
                rc = netrc.netrc(os.environ.get('NETRC'))
                login = rc.authenticators(parsed[1])
            except IOError:
                login = None

            if login:
                username, _, password = login
                if username and password:
                    headers["Authorization"] = basic_auth_header(username, password)

    if not use_proxy:
        proxyhandler = urllib_request.ProxyHandler({})
        handlers.append(proxyhandler)

    if HAS_SSLCONTEXT and not validate_certs:
        # In 2.7.9, the default context validates certificates
        context = SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= ssl.OP_NO_SSLv2
        context.options |= ssl.OP_NO_SSLv3
        context.verify_mode = ssl.CERT_NONE
        context.check_hostname = False
        handlers.append(urllib_request.HTTPSHandler(context=context))

    # pre-2.6 versions of python cannot use the custom https
    # handler, since the socket class is lacking create_connection.
    # Some python builds lack HTTPS support.
    if hasattr(socket, 'create_connection') and CustomHTTPSHandler:
        handlers.append(CustomHTTPSHandler)

    handlers.append(RedirectHandlerFactory(follow_redirects, validate_certs))

    opener = urllib_request.build_opener(*handlers)
    urllib_request.install_opener(opener)

    if method:
        if method.upper() not in ('OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT','PATCH'):
            raise ConnectionError('invalid HTTP request method; %s' % method.upper())
        request = RequestWithMethod(url, method.upper(), data)
    else:
        request = urllib_request.Request(url, data)

    # add the custom agent header, to help prevent issues
    # with sites that block the default urllib agent string
    request.add_header('User-agent', http_agent)

    # if we're ok with getting a 304, set the timestamp in the
    # header, otherwise make sure we don't get a cached copy
    if last_mod_time and not force:
        tstamp = last_mod_time.strftime('%a, %d %b %Y %H:%M:%S +0000')
        request.add_header('If-Modified-Since', tstamp)
    else:
        request.add_header('cache-control', 'no-cache')

    # user defined headers now, which may override things we've set above
    if headers:
        if not isinstance(headers, dict):
            raise ValueError("headers provided to fetch_url() must be a dict")
        for header in headers:
            request.add_header(header, headers[header])

    urlopen_args = [request, None]
    if sys.version_info >= (2,6,0):
        # urlopen in python prior to 2.6.0 did not
        # have a timeout parameter
        urlopen_args.append(timeout)

    r = urllib_request.urlopen(*urlopen_args)
    return r