Exemple #1
0
    def __init__(self, host, port=None, strict=None,
                 dbdir=None, family=socket.AF_UNSPEC, no_init=False,
                 tls_version_min='tls1.1', tls_version_max='tls1.2'):
        """
        :param host: the server to connect to
        :param port: the port to use (default is set in HTTPConnection)
        :param dbdir: the NSS database directory
        :param family: network family to use (default AF_UNSPEC)
        :param no_init: do not initialize the NSS database. This requires
                        that the database has already been initialized or
                        the request will fail.
        :param tls_min_version: mininum version of SSL/TLS supported
        :param tls_max_version: maximum version of SSL/TLS supported.
        """
        httplib.HTTPConnection.__init__(self, host, port, strict)
        NSSAddressFamilyFallback.__init__(self, family)

        if not dbdir:
            raise RuntimeError("dbdir is required")

        root_logger.debug('%s init %s', self.__class__.__name__, host)
        if not no_init and nss.nss_is_initialized():
            # close any open NSS database and use the new one
            ssl.clear_session_cache()
            try:
                nss.nss_shutdown()
            except NSPRError, e:
                if e.errno != error.SEC_ERROR_NOT_INITIALIZED:
                    raise e
Exemple #2
0
def initialize_nss(dbdir):
    """Initialize NSS

    nss_init() initializes NSS and the DB globally.
    """
    # global settings
    nss.nss_init(dbdir)
    ssl.set_domestic_policy()
    ssl.clear_session_cache()
    # thread local callback
    nss.set_password_callback(password_callback)
Exemple #3
0
    def shutdown(self):
        if not nss.nss_is_initialized():
            return

        try:
            ssl.clear_session_cache()
        except Exception:
            pass
        try:
            nss.nss_shutdown()
        except Exception:
            pass
Exemple #4
0
    def shutdown(self):
        if not nss.nss_is_initialized():
            return

        try:
            ssl.clear_session_cache()
        except Exception:
            pass
        try:
            nss.nss_shutdown()
        except Exception:
            pass
Exemple #5
0
    def __init__(
        self,
        host,
        port=None,
        strict=None,
        dbdir=None,
        family=socket.AF_UNSPEC,
        no_init=False,
        tls_version_min="tls1.1",
        tls_version_max="tls1.2",
    ):
        """
        :param host: the server to connect to
        :param port: the port to use (default is set in HTTPConnection)
        :param dbdir: the NSS database directory
        :param family: network family to use (default AF_UNSPEC)
        :param no_init: do not initialize the NSS database. This requires
                        that the database has already been initialized or
                        the request will fail.
        :param tls_min_version: mininum version of SSL/TLS supported
        :param tls_max_version: maximum version of SSL/TLS supported.
        """
        httplib.HTTPConnection.__init__(self, host, port, strict)
        NSSAddressFamilyFallback.__init__(self, family)

        root_logger.debug("%s init %s", self.__class__.__name__, host)

        # If initialization is requested, initialize the new database.
        if not no_init:

            if nss.nss_is_initialized():
                ssl.clear_session_cache()
                try:
                    nss.nss_shutdown()
                except NSPRError as e:
                    if e.errno != error.SEC_ERROR_NOT_INITIALIZED:
                        raise e

            if not dbdir:
                raise RuntimeError("dbdir is required")

            nss.nss_init(dbdir)

            global current_dbdir
            current_dbdir = dbdir

        ssl.set_domestic_policy()
        nss.set_password_callback(self.password_callback)
        self.tls_version_min = str(tls_version_min)
        self.tls_version_max = str(tls_version_max)
Exemple #6
0
    def __init__(self,
                 host,
                 port=None,
                 strict=None,
                 dbdir=None,
                 family=socket.AF_UNSPEC,
                 no_init=False,
                 tls_version_min='tls1.1',
                 tls_version_max='tls1.2'):
        """
        :param host: the server to connect to
        :param port: the port to use (default is set in HTTPConnection)
        :param dbdir: the NSS database directory
        :param family: network family to use (default AF_UNSPEC)
        :param no_init: do not initialize the NSS database. This requires
                        that the database has already been initialized or
                        the request will fail.
        :param tls_min_version: mininum version of SSL/TLS supported
        :param tls_max_version: maximum version of SSL/TLS supported.
        """
        httplib.HTTPConnection.__init__(self, host, port, strict)
        NSSAddressFamilyFallback.__init__(self, family)

        root_logger.debug('%s init %s', self.__class__.__name__, host)

        # If initialization is requested, initialize the new database.
        if not no_init:

            if nss.nss_is_initialized():
                ssl.clear_session_cache()
                try:
                    nss.nss_shutdown()
                except NSPRError as e:
                    if e.errno != error.SEC_ERROR_NOT_INITIALIZED:
                        raise e

            if not dbdir:
                raise RuntimeError("dbdir is required")

            nss.nss_init(dbdir)

            global current_dbdir
            current_dbdir = dbdir

        ssl.set_domestic_policy()
        nss.set_password_callback(self.password_callback)
        tls_versions = get_proper_tls_version_span(tls_version_min,
                                                   tls_version_max)
        self.tls_version_min = tls_versions[0]
        self.tls_version_max = tls_versions[-1]
Exemple #7
0
 def close(self):
     """Close the connection to the HTTP server."""
     if self.sock:
         self.sock.close()  # close it manually... there may be other refs
         self.sock = None
         ssl.clear_session_cache()
Exemple #8
0
 def close(self):
     """Close the connection to the HTTP server."""
     if self.sock:
         self.sock.close()  # close it manually... there may be other refs
         self.sock = None
         ssl.clear_session_cache()
        print >>sys.stderr, "client: %s" % e
        try:
            sock.close()
        except:
            pass
        return

    try:
        sock.shutdown()
    except Exception, e:
        print >>sys.stderr, "client: %s" % e

    try:
        sock.close()
        if use_ssl:
            ssl.clear_session_cache()
    except Exception, e:
        print >>sys.stderr, "client: %s" % e

    return buf

# -----------------------------------------------------------------------------
# Server Implementation
# -----------------------------------------------------------------------------

def server():
    global family

    if verbose: print "starting server:"

    # Initialize
Exemple #10
0
def client(request):
    if use_ssl:
        if info:
            print("client: using SSL")
        ssl.set_domestic_policy()

    # Get the IP Address of our server
    try:
        addr_info = io.AddrInfo(hostname)
    except Exception as e:
        print("client: could not resolve host address \"%s\"" % hostname,
              file=sys.stderr)
        return

    for net_addr in addr_info:
        net_addr.port = port

        if use_ssl:
            sock = ssl.SSLSocket(net_addr.family)

            # Set client SSL socket options
            sock.set_ssl_option(ssl.SSL_SECURITY, True)
            sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
            sock.set_hostname(hostname)

            # Provide a callback which notifies us when the SSL handshake is complete
            sock.set_handshake_callback(handshake_callback)

            # Provide a callback to supply our client certificate info
            sock.set_client_auth_data_callback(client_auth_data_callback,
                                               client_nickname, password,
                                               nss.get_default_certdb())

            # Provide a callback to verify the servers certificate
            sock.set_auth_certificate_callback(auth_certificate_callback,
                                               nss.get_default_certdb())
        else:
            sock = io.Socket(net_addr.family)

        try:
            if verbose:
                print("client trying connection to: %s" % (net_addr))
            sock.connect(net_addr,
                         timeout=io.seconds_to_interval(timeout_secs))
            if verbose:
                print("client connected to: %s" % (net_addr))
            break
        except Exception as e:
            sock.close()
            print("client: connection to: %s failed (%s)" % (net_addr, e),
                  file=sys.stderr)

    # Talk to the server
    try:
        if info:
            print("client: sending \"%s\"" % (request))
        data = request + "\n"
        # newline is protocol record separator
        sock.send(data.encode('utf-8'))
        buf = sock.readline()
        if not buf:
            print("client: lost connection", file=sys.stderr)
            sock.close()
            return
        buf = buf.decode('utf-8')
        buf = buf.rstrip()  # remove newline record separator
        if info:
            print("client: received \"%s\"" % (buf))
    except Exception as e:
        print("client: %s" % e, file=sys.stderr)
        try:
            sock.close()
        except:
            pass
        return

    try:
        sock.shutdown()
    except Exception as e:
        print("client: %s" % e, file=sys.stderr)

    try:
        sock.close()
        if use_ssl:
            ssl.clear_session_cache()
    except Exception as e:
        print("client: %s" % e, file=sys.stderr)

    return buf
Exemple #11
0
        print >> sys.stderr, "client: %s" % e
        try:
            sock.close()
        except:
            pass
        return

    try:
        sock.shutdown()
    except Exception, e:
        print >> sys.stderr, "client: %s" % e

    try:
        sock.close()
        if use_ssl:
            ssl.clear_session_cache()
    except Exception, e:
        print >> sys.stderr, "client: %s" % e

    return buf


# -----------------------------------------------------------------------------
# Server Implementation
# -----------------------------------------------------------------------------


def server():
    global family

    if verbose: print "starting server:"
Exemple #12
0
def Client():
    valid_addr = False
    # Get the IP Address of our server
    try:
        addr_info = io.AddrInfo(options.hostname)
    except Exception as e:
        print("could not resolve host address \"%s\"" % options.hostname)
        return

    for net_addr in addr_info:
        if options.family != io.PR_AF_UNSPEC:
            if net_addr.family != options.family:
                continue
        net_addr.port = options.port

        if options.use_ssl:
            sock = ssl.SSLSocket(net_addr.family)

            # Set client SSL socket options
            sock.set_ssl_option(ssl.SSL_SECURITY, True)
            sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
            sock.set_hostname(options.hostname)

            # Provide a callback which notifies us when the SSL handshake is complete
            sock.set_handshake_callback(handshake_callback)

            # Provide a callback to supply our client certificate info
            sock.set_client_auth_data_callback(
                client_auth_data_callback,
                options.client_nickname,
                options.password,
                nss.get_default_certdb(),
            )

            # Provide a callback to verify the servers certificate
            sock.set_auth_certificate_callback(auth_certificate_callback,
                                               nss.get_default_certdb())
        else:
            sock = io.Socket(net_addr.family)

        try:
            print("client trying connection to: %s" % (net_addr))
            sock.connect(net_addr,
                         timeout=io.seconds_to_interval(timeout_secs))
            print("client connected to: %s" % (net_addr))
            valid_addr = True
            break
        except Exception as e:
            sock.close()
            print("client connection to: %s failed (%s)" % (net_addr, e))

    if not valid_addr:
        print("Could not establish valid address for \"%s\" in family %s" %
              (options.hostname, io.addr_family_name(options.family)))
        return

    # Talk to the server
    try:
        data = 'Hello' + '\n'  # newline is protocol record separator
        sock.send(data.encode('utf-8'))
        buf = sock.readline()
        if not buf:
            print("client lost connection")
            sock.close()
            return
        buf = buf.decode('utf-8')
        buf = buf.rstrip()  # remove newline record separator
        print("client received: %s" % (buf))
    except Exception as e:
        print(e.strerror)
        try:
            sock.close()
        except:
            pass
        return

    # End of (simple) protocol session?
    if buf == 'Goodbye':
        try:
            sock.shutdown()
        except:
            pass

    try:
        sock.close()
        if options.use_ssl:
            ssl.clear_session_cache()
    except Exception as e:
        print(e)
Exemple #13
0
def Client():
    valid_addr = False
    # Get the IP Address of our server
    try:
        addr_info = io.AddrInfo(options.hostname)
    except Exception as e:
        print("could not resolve host address \"%s\"" % options.hostname)
        return

    for net_addr in addr_info:
        if options.family != io.PR_AF_UNSPEC:
            if net_addr.family != options.family:
                continue
        net_addr.port = options.port

        if options.use_ssl:
            sock = ssl.SSLSocket(net_addr.family)

            # Set client SSL socket options
            sock.set_ssl_option(ssl.SSL_SECURITY, True)
            sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
            sock.set_hostname(options.hostname)

            # Provide a callback which notifies us when the SSL handshake is complete
            sock.set_handshake_callback(handshake_callback)

            # Provide a callback to supply our client certificate info
            sock.set_client_auth_data_callback(client_auth_data_callback, options.client_nickname,
                                               options.password, nss.get_default_certdb())

            # Provide a callback to verify the servers certificate
            sock.set_auth_certificate_callback(auth_certificate_callback,
                                               nss.get_default_certdb())
        else:
            sock = io.Socket(net_addr.family)

        try:
            print("client trying connection to: %s" % (net_addr))
            sock.connect(net_addr, timeout=io.seconds_to_interval(timeout_secs))
            print("client connected to: %s" % (net_addr))
            valid_addr = True
            break
        except Exception as e:
            sock.close()
            print("client connection to: %s failed (%s)" % (net_addr, e))

    if not valid_addr:
        print("Could not establish valid address for \"%s\" in family %s" % \
        (options.hostname, io.addr_family_name(options.family)))
        return

    # Talk to the server
    try:
        data = 'Hello' + '\n' # newline is protocol record separator
        sock.send(data.encode('utf-8'))
        buf = sock.readline()
        if not buf:
            print("client lost connection")
            sock.close()
            return
        buf = buf.decode('utf-8')
        buf = buf.rstrip()        # remove newline record separator
        print("client received: %s" % (buf))
    except Exception as e:
        print(e.strerror)
        try:
            sock.close()
        except:
            pass
        return

    # End of (simple) protocol session?
    if buf == 'Goodbye':
        try:
            sock.shutdown()
        except:
            pass

    try:
        sock.close()
        if options.use_ssl:
            ssl.clear_session_cache()
    except Exception as e:
        print(e)
def client(request):
    if use_ssl:
        if info:
            print("client: using SSL")
        ssl.set_domestic_policy()

    # Get the IP Address of our server
    try:
        addr_info = io.AddrInfo(hostname)
    except Exception as e:
        print("client: could not resolve host address \"%s\"" % hostname, file=sys.stderr)
        return

    for net_addr in addr_info:
        net_addr.port = port

        if use_ssl:
            sock = ssl.SSLSocket(net_addr.family)

            # Set client SSL socket options
            sock.set_ssl_option(ssl.SSL_SECURITY, True)
            sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
            sock.set_hostname(hostname)

            # Provide a callback which notifies us when the SSL handshake is complete
            sock.set_handshake_callback(handshake_callback)

            # Provide a callback to supply our client certificate info
            sock.set_client_auth_data_callback(client_auth_data_callback, client_nickname,
                                               password, nss.get_default_certdb())

            # Provide a callback to verify the servers certificate
            sock.set_auth_certificate_callback(auth_certificate_callback,
                                               nss.get_default_certdb())
        else:
            sock = io.Socket(net_addr.family)

        try:
            if verbose:
                print("client trying connection to: %s" % (net_addr))
            sock.connect(net_addr, timeout=io.seconds_to_interval(timeout_secs))
            if verbose:
                print("client connected to: %s" % (net_addr))
            break
        except Exception as e:
            sock.close()
            print("client: connection to: %s failed (%s)" % (net_addr, e), file=sys.stderr)

    # Talk to the server
    try:
        if info:
            print("client: sending \"%s\"" % (request))
        data = request + "\n"; # newline is protocol record separator
        sock.send(data.encode('utf-8'))
        buf = sock.readline()
        if not buf:
            print("client: lost connection", file=sys.stderr)
            sock.close()
            return
        buf = buf.decode('utf-8')
        buf = buf.rstrip()        # remove newline record separator
        if info:
            print("client: received \"%s\"" % (buf))
    except Exception as e:
        print("client: %s" % e, file=sys.stderr)
        try:
            sock.close()
        except:
            pass
        return

    try:
        sock.shutdown()
    except Exception as e:
        print("client: %s" % e, file=sys.stderr)

    try:
        sock.close()
        if use_ssl:
            ssl.clear_session_cache()
    except Exception as e:
        print("client: %s" % e, file=sys.stderr)

    return buf