Beispiel #1
0
    def _create_socket(self):
        # TODO: remove the try block once python-nss is guaranteed to contain
        # these values
        try:
            #pylint: disable=E1101
            ssl_enable_renegotiation  = ssl.SSL_ENABLE_RENEGOTIATION
            ssl_require_safe_negotiation = ssl.SSL_REQUIRE_SAFE_NEGOTIATION
            ssl_renegotiate_requires_xtn = ssl.SSL_RENEGOTIATE_REQUIRES_XTN
        except:
            ssl_enable_renegotiation  = 20
            ssl_require_safe_negotiation = 21
            ssl_renegotiate_requires_xtn = 2

        # Create the socket here so we can do things like let the caller
        # override the NSS callbacks
        self.sock = ssl.SSLSocket(family=self.family)
        self.sock.set_ssl_option(ssl.SSL_SECURITY, True)
        self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
        try:
            self.sock.set_ssl_version_range(self.tls_version_min, self.tls_version_max)
        except NSPRError as e:
            root_logger.error('Failed to set TLS range to %s, %s' % (self.tls_version_min, self.tls_version_max))
            raise
        self.sock.set_ssl_option(ssl_require_safe_negotiation, False)
        self.sock.set_ssl_option(ssl_enable_renegotiation, ssl_renegotiate_requires_xtn)
        # Provide a callback which notifies us when the SSL handshake is complete
        self.sock.set_handshake_callback(self.handshake_callback)

        # Provide a callback to verify the servers certificate
        self.sock.set_auth_certificate_callback(auth_certificate_callback,
                                                nss.get_default_certdb())
        self.sock.set_hostname(self.host)
Beispiel #2
0
 def verify_ca_cert_validity(self, nickname):
     certdb = cert = None
     if nss.nss_is_initialized():
         nss.nss_shutdown()
     nss.nss_init(self.secdir)
     try:
         certdb = nss.get_default_certdb()
         cert = nss.find_cert_from_nickname(nickname)
         if not cert.subject:
             raise ValueError("has empty subject")
         try:
             bc = cert.get_extension(nss.SEC_OID_X509_BASIC_CONSTRAINTS)
         except KeyError:
             raise ValueError("missing basic constraints")
         bc = nss.BasicConstraints(bc.value)
         if not bc.is_ca:
             raise ValueError("not a CA certificate")
         intended_usage = nss.certificateUsageSSLCA
         try:
             approved_usage = cert.verify_now(certdb, True, intended_usage)
         except NSPRError as e:
             if e.errno != -8102:  # SEC_ERROR_INADEQUATE_KEY_USAGE
                 raise ValueError(e.strerror)
             approved_usage = 0
         if approved_usage & intended_usage != intended_usage:
             raise ValueError('invalid for a CA')
     finally:
         del certdb, cert
         nss.nss_shutdown()
Beispiel #3
0
    def _create_socket(self):
        ssl_enable_renegotiation = getattr(
            ssl, 'SSL_ENABLE_RENEGOTIATION', 20)
        ssl_require_safe_negotiation = getattr(
            ssl,'SSL_REQUIRE_SAFE_NEGOTIATION', 21)
        ssl_renegotiate_requires_xtn = getattr(
            ssl, 'SSL_RENEGOTIATE_REQUIRES_XTN', 2)

        # Create the socket here so we can do things like let the caller
        # override the NSS callbacks
        self.sock = ssl.SSLSocket(family=self.family)
        self.sock.set_ssl_option(ssl.SSL_SECURITY, True)
        self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
        try:
            self.sock.set_ssl_version_range(self.tls_version_min, self.tls_version_max)
        except NSPRError:
            root_logger.error('Failed to set TLS range to %s, %s' % (self.tls_version_min, self.tls_version_max))
            raise
        self.sock.set_ssl_option(ssl_require_safe_negotiation, False)
        self.sock.set_ssl_option(ssl_enable_renegotiation, ssl_renegotiate_requires_xtn)
        # Provide a callback which notifies us when the SSL handshake is complete
        self.sock.set_handshake_callback(self.handshake_callback)

        # Provide a callback to verify the servers certificate
        self.sock.set_auth_certificate_callback(auth_certificate_callback,
                                                nss.get_default_certdb())
        self.sock.set_hostname(self.host)
Beispiel #4
0
    def verify_server_cert_validity(self, nickname, hostname):
        """Verify a certificate is valid for a SSL server with given hostname

        Raises a ValueError if the certificate is invalid.
        """
        certdb = cert = None
        if nss.nss_is_initialized():
            nss.nss_shutdown()
        nss.nss_init(self.secdir)
        try:
            certdb = nss.get_default_certdb()
            cert = nss.find_cert_from_nickname(nickname)
            intended_usage = nss.certificateUsageSSLServer
            try:
                approved_usage = cert.verify_now(certdb, True, intended_usage)
            except NSPRError as e:
                if e.errno != -8102:
                    raise ValueError(e.strerror)
                approved_usage = 0
            if not approved_usage & intended_usage:
                raise ValueError('invalid for a SSL server')
            if not cert.verify_hostname(hostname):
                raise ValueError('invalid for server %s' % hostname)
        finally:
            del certdb, cert
            nss.nss_shutdown()

        return None
Beispiel #5
0
 def verify_ca_cert_validity(self, nickname):
     certdb = cert = None
     if nss.nss_is_initialized():
         nss.nss_shutdown()
     nss.nss_init(self.secdir)
     try:
         certdb = nss.get_default_certdb()
         cert = nss.find_cert_from_nickname(nickname)
         if not cert.subject:
             raise ValueError("has empty subject")
         try:
             bc = cert.get_extension(nss.SEC_OID_X509_BASIC_CONSTRAINTS)
         except KeyError:
             raise ValueError("missing basic constraints")
         bc = nss.BasicConstraints(bc.value)
         if not bc.is_ca:
             raise ValueError("not a CA certificate")
         intended_usage = nss.certificateUsageSSLCA
         try:
             approved_usage = cert.verify_now(certdb, True, intended_usage)
         except NSPRError as e:
             if e.errno != -8102:    # SEC_ERROR_INADEQUATE_KEY_USAGE
                 raise ValueError(e.strerror)
             approved_usage = 0
         if approved_usage & intended_usage != intended_usage:
             raise ValueError('invalid for a CA')
     finally:
         del certdb, cert
         nss.nss_shutdown()
Beispiel #6
0
    def verify_server_cert_validity(self, nickname, hostname):
        """Verify a certificate is valid for a SSL server with given hostname

        Raises a ValueError if the certificate is invalid.
        """
        certdb = cert = None
        if nss.nss_is_initialized():
            nss.nss_shutdown()
        nss.nss_init(self.secdir)
        try:
            certdb = nss.get_default_certdb()
            cert = nss.find_cert_from_nickname(nickname)
            intended_usage = nss.certificateUsageSSLServer
            try:
                approved_usage = cert.verify_now(certdb, True, intended_usage)
            except NSPRError as e:
                if e.errno != -8102:
                    raise ValueError(e.strerror)
                approved_usage = 0
            if not approved_usage & intended_usage:
                raise ValueError('invalid for a SSL server')
            if not cert.verify_hostname(hostname):
                raise ValueError('invalid for server %s' % hostname)
        finally:
            del certdb, cert
            nss.nss_shutdown()

        return None
Beispiel #7
0
    def _create_socket(self):
        # TODO: remove the try block once python-nss is guaranteed to contain
        # these values
        try:
            #pylint: disable=E1101
            ssl_enable_renegotiation = ssl.SSL_ENABLE_RENEGOTIATION
            ssl_require_safe_negotiation = ssl.SSL_REQUIRE_SAFE_NEGOTIATION
            ssl_renegotiate_requires_xtn = ssl.SSL_RENEGOTIATE_REQUIRES_XTN
        except:
            ssl_enable_renegotiation = 20
            ssl_require_safe_negotiation = 21
            ssl_renegotiate_requires_xtn = 2

        # Create the socket here so we can do things like let the caller
        # override the NSS callbacks
        self.sock = ssl.SSLSocket(family=self.family)
        self.sock.set_ssl_option(ssl.SSL_SECURITY, True)
        self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
        try:
            self.sock.set_ssl_version_range(self.tls_version_min,
                                            self.tls_version_max)
        except NSPRError as e:
            root_logger.error('Failed to set TLS range to %s, %s' %
                              (self.tls_version_min, self.tls_version_max))
            raise
        self.sock.set_ssl_option(ssl_require_safe_negotiation, False)
        self.sock.set_ssl_option(ssl_enable_renegotiation,
                                 ssl_renegotiate_requires_xtn)
        # Provide a callback which notifies us when the SSL handshake is complete
        self.sock.set_handshake_callback(self.handshake_callback)

        # Provide a callback to verify the servers certificate
        self.sock.set_auth_certificate_callback(auth_certificate_callback,
                                                nss.get_default_certdb())
        self.sock.set_hostname(self.host)
Beispiel #8
0
 def connection_factory(host, port):
     conn = nsslib.NSSConnection(host, port, dbdir=secdir)
     conn.set_debuglevel(0)
     conn.connect()
     conn.sock.set_client_auth_data_callback(
         nsslib.client_auth_data_callback,
         nickname, password, nss.get_default_certdb())
     return conn
Beispiel #9
0
    def __init__(self, host, port, timeout=3, **kwargs):
        http.client.HTTPConnection.__init__(
            self, host, port, timeout=timeout, **kwargs)

        log.info('%s init %s', self.__class__.__name__, host)
        self.sock = None
        self._timeout = timeout
        self._certdb = nss.get_default_certdb()
Beispiel #10
0
 def __init__(self, certdb=None, log=None, *args, **kwargs):
     if not nss.nss_is_initialized():
         NSSAdapterException('NSS is not initialized')
     if certdb is None:
         self.certdb = nss.get_default_certdb()
     else:
         self.certdb = certdb
     self.log = log if log is not None else logger
     super(NSSTransportAdapter, self).__init__(*args, **kwargs)
Beispiel #11
0
def client():
    valid_addr = False
    # Get the IP Address of our server
    try:
        addr_info = io.AddrInfo(options.hostname)
    except:
        print("ERROR: could not resolve hostname \"%s\"" % options.hostname)
        return

    for net_addr in addr_info:
        net_addr.port = options.port
        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 verify the servers certificate
        sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())

        try:
            print("try connecting to: %s" % (net_addr))
            sock.connect(net_addr,
                         timeout=io.seconds_to_interval(timeout_secs))
            print("connected to: %s" % (net_addr))
            valid_addr = True
            break
        except:
            continue

    if not valid_addr:
        print("ERROR: could not connect to \"%s\"" % options.hostname)
        return

    try:
        # Talk to the server
        n_received = 0
        sock.send(request.encode('utf-8'))
        while True:
            buf = sock.recv(1024)
            n_received += len(buf)
            if not buf:
                print("\nclient lost connection, received %d bytes" %
                      (n_received))
                break
    except Exception as e:
        print(e)
        sock.shutdown()
        return

    sock.shutdown()
    return
Beispiel #12
0
def https_request(host, port, url, secdir, password, nickname, operation, args,
                  **kw):
    """
    :param url:        The URL to post to.
    :param operation:  GET, POST, (PUT and DELETE not yet implemented)
    :param args:       arguments for GET command line, or for POST
    :param kw:         Keyword arguments to encode into POST body.
    :return:           (http_status, http_reason_phrase, http_headers, http_body)
                       as (integer, unicode, dict, str)

    Perform a client authenticated HTTPS request
    """
    if isinstance(host, six.text_type):
        host = host.encode('utf-8')
    uri = 'https://%s%s' % (ipautil.format_netloc(host, port), url)
    logging.info('sslget %r', uri)

    request_headers = {
        "Content-type": "application/xml",
        "Accept": "application/xml"
    }
    if operation == "POST":
        if args is not None:
            post = args
        elif kw is not None:
            post = urlencode(kw)
            request_headers = {
                "Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain"
            }
    conn = None
    try:
        conn = nsslib.NSSConnection(host, port, dbdir=secdir)
        conn.set_debuglevel(0)
        conn.connect()
        conn.sock.set_client_auth_data_callback(
            nsslib.client_auth_data_callback, nickname, password,
            nss.get_default_certdb())
        if operation == "GET":
            url = url + "?" + args
            conn.request("GET", url)
        elif operation == "POST":
            conn.request("POST", url, post, request_headers)

        res = conn.getresponse()

        http_status = res.status
        http_reason_phrase = six.text_type(res.reason, 'utf-8')
        http_headers = res.msg.dict
        http_body = res.read()
    except Exception as e:
        raise NetworkError(uri=uri, error=str(e))
    finally:
        if conn is not None:
            conn.close()

    return http_status, http_reason_phrase, http_headers, http_body
Beispiel #13
0
 def connection_factory(host, port):
     conn = nsslib.NSSConnection(host, port, dbdir=secdir,
                                 tls_version_min=api.env.tls_version_min,
                                 tls_version_max=api.env.tls_version_max)
     conn.set_debuglevel(0)
     conn.connect()
     conn.sock.set_client_auth_data_callback(
         nsslib.client_auth_data_callback,
         nickname, password, nss.get_default_certdb())
     return conn
Beispiel #14
0
    def __init__(self, host, port, timeout=3, **kwargs):
        http.client.HTTPConnection.__init__(self,
                                            host,
                                            port,
                                            timeout=timeout,
                                            **kwargs)

        log.info('%s init %s', self.__class__.__name__, host)
        self.sock = None
        self._timeout = timeout
        self._certdb = nss.get_default_certdb()
Beispiel #15
0
 def connection_factory(host, port):
     no_init = secdir == nsslib.current_dbdir
     conn = nsslib.NSSConnection(host, port, dbdir=secdir, no_init=no_init,
                                 tls_version_min=api.env.tls_version_min,
                                 tls_version_max=api.env.tls_version_max)
     conn.set_debuglevel(0)
     conn.connect()
     conn.sock.set_client_auth_data_callback(
         nsslib.client_auth_data_callback,
         nickname, password, nss.get_default_certdb())
     return conn
Beispiel #16
0
def https_request(
        host, port, url, secdir, password, nickname, operation, args, **kw):
    """
    :param url:        The URL to post to.
    :param operation:  GET, POST, (PUT and DELETE not yet implemented)
    :param args:       arguments for GET command line, or for POST
    :param kw:         Keyword arguments to encode into POST body.
    :return:           (http_status, http_reason_phrase, http_headers, http_body)
                       as (integer, unicode, dict, str)

    Perform a client authenticated HTTPS request
    """
    if isinstance(host, six.text_type):
        host = host.encode('utf-8')
    uri = 'https://%s%s' % (ipautil.format_netloc(host, port), url)
    logging.info('sslget %r', uri)

    request_headers = {"Content-type": "application/xml",
                       "Accept": "application/xml"}
    if operation == "POST":
        if args is not None:
            post = args
        elif kw is not None:
            post = urlencode(kw)
            request_headers = {"Content-type": "application/x-www-form-urlencoded",
                               "Accept": "text/plain"}
    conn = None
    try:
        conn = nsslib.NSSConnection(host, port, dbdir=secdir)
        conn.set_debuglevel(0)
        conn.connect()
        conn.sock.set_client_auth_data_callback(nsslib.client_auth_data_callback,
                                                nickname,
                                                password, nss.get_default_certdb())
        if operation == "GET":
            url = url + "?" + args
            conn.request("GET", url)
        elif operation == "POST":
            conn.request("POST", url, post, request_headers)

        res = conn.getresponse()

        http_status = res.status
        http_reason_phrase = six.text_type(res.reason, 'utf-8')
        http_headers = res.msg.dict
        http_body = res.read()
    except Exception as e:
        raise NetworkError(uri=uri, error=str(e))
    finally:
        if conn is not None:
            conn.close()

    return http_status, http_reason_phrase, http_headers, http_body
Beispiel #17
0
    def _create_socket(self, family):
        self.sock = ssl.SSLSocket(family)
        self.sock.set_ssl_option(ssl.SSL_SECURITY, True)
        self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
        self.sock.set_hostname(self.host)

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

        # Provide a callback to verify the servers certificate
        self.sock.set_auth_certificate_callback(auth_certificate_callback,
                                                nss.get_default_certdb())
    def _create_socket(self, family):
        self.sock = ssl.SSLSocket(family)
        self.sock.set_ssl_option(ssl.SSL_SECURITY, True)
        self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
        self.sock.set_hostname(self.host)

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

        # Provide a callback to verify the servers certificate
        self.sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())
def client():
    valid_addr = False
    # Get the IP Address of our server
    try:
        addr_info = io.AddrInfo(hostname)
    except:
        print "ERROR: could not resolve hostname \"%s\"" % hostname
        return

    for net_addr in addr_info:
        net_addr.port = port
        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 verify the servers certificate
        sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())

        try:
            print "try connecting to: %s" % (net_addr)
            sock.connect(net_addr, timeout=io.seconds_to_interval(timeout_secs))
            print "connected to: %s" % (net_addr)
            valid_addr = True
            break
        except:
            continue

    if not valid_addr:
        print "ERROR: could not connect to \"%s\"" % hostname
        return

    try:
        # Talk to the server
        n_received = 0
        sock.send(request)
        while True:
            buf = sock.recv(1024)
            n_received += len(buf)
            if not buf:
                print "\nclient lost connection, received %d bytes" % (n_received)
                break
    except Exception, e:
        print e.strerror
        sock.shutdown()
        return
Beispiel #20
0
def https_request(host, port, url, secdir, password, nickname, **kw):
    """
    :param url: The URL to post to.
    :param kw:  Keyword arguments to encode into POST body.
    :return:   (http_status, http_reason_phrase, http_headers, http_body)
               as (integer, unicode, dict, str)

    Perform a client authenticated HTTPS request
    """
    if isinstance(host, unicode):
        host = host.encode('utf-8')
    uri = 'https://%s%s' % (ipautil.format_netloc(host, port), url)
    post = urlencode(kw)
    root_logger.debug('https_request %r', uri)
    root_logger.debug('https_request post %r', post)
    request_headers = {
        "Content-type": "application/x-www-form-urlencoded",
        "Accept": "text/plain"
    }
    try:
        conn = nsslib.NSSConnection(host,
                                    port,
                                    dbdir=secdir,
                                    tls_version_min=api.env.tls_version_min,
                                    tls_version_max=api.env.tls_version_max)
        conn.set_debuglevel(0)
        conn.connect()
        conn.sock.set_client_auth_data_callback(
            nsslib.client_auth_data_callback, nickname, password,
            nss.get_default_certdb())
        conn.request("POST", url, post, request_headers)

        res = conn.getresponse()

        http_status = res.status
        http_reason_phrase = unicode(res.reason, 'utf-8')
        http_headers = res.msg.dict
        http_body = res.read()
        conn.close()
    except Exception, e:
        raise NetworkError(uri=uri, error=str(e))
Beispiel #21
0
def https_request(host, port, url, secdir, password, nickname, **kw):
    """
    :param url: The URL to post to.
    :param kw:  Keyword arguments to encode into POST body.
    :return:   (http_status, http_reason_phrase, http_headers, http_body)
               as (integer, unicode, dict, str)

    Perform a client authenticated HTTPS request
    """
    if isinstance(host, unicode):
        host = host.encode('utf-8')
    uri = 'https://%s%s' % (ipautil.format_netloc(host, port), url)
    post = urlencode(kw)
    root_logger.debug('https_request %r', uri)
    root_logger.debug('https_request post %r', post)
    request_headers = {"Content-type": "application/x-www-form-urlencoded",
                       "Accept": "text/plain"}
    try:
        conn = nsslib.NSSConnection(host, port, dbdir=secdir,
                                    tls_version_min=api.env.tls_version_min,
                                    tls_version_max=api.env.tls_version_max)
        conn.set_debuglevel(0)
        conn.connect()
        conn.sock.set_client_auth_data_callback(nsslib.client_auth_data_callback,
                                                nickname,
                                                password, nss.get_default_certdb())
        conn.request("POST", url, post, request_headers)

        res = conn.getresponse()

        http_status = res.status
        http_reason_phrase = unicode(res.reason, 'utf-8')
        http_headers = res.msg.dict
        http_body = res.read()
        conn.close()
    except Exception, e:
        raise NetworkError(uri=uri, error=str(e))
Beispiel #22
0
    def auth_certificate_callback(self, sock, check_sig, is_server):
        cert_is_valid = False
        certdb = nss.get_default_certdb()

        cert = sock.get_peer_certificate()

        logging.debug("auth_certificate_callback: check_sig=%s is_server=%s\n%s",
                      check_sig, is_server, str(cert))

        pin_args = sock.get_pkcs11_pin_arg()
        if pin_args is None:
            pin_args = ()

        intended_usage = nss.certificateUsageSSLServer

        try:
            # If the cert fails validation it will raise an exception, the errno attribute
            # will be set to the error code matching the reason why the validation failed
            # and the strerror attribute will contain a string describing the reason.
            approved_usage = cert.verify_now(certdb, check_sig, intended_usage, *pin_args)
        except Exception, e:
            logging.error('cert validation failed for "%s" (%s)', cert.subject, e.strerror)
            cert_is_valid = False
            return cert_is_valid
Beispiel #23
0
def server():
    global family

    if verbose: print "starting server:"

    # Initialize
    # Setup an IP Address to listen on any of our interfaces
    if family == io.PR_AF_UNSPEC:
        family = io.PR_AF_INET
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, port, family)

    if use_ssl:
        if info: print "server: using SSL"
        ssl.set_domestic_policy()
        nss.set_password_callback(password_callback)

        # Perform basic SSL server configuration
        ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
        ssl.config_server_session_id_cache()

        # Get our certificate and private key
        server_cert = nss.find_cert_from_nickname(server_nickname, password)
        priv_key = nss.find_key_by_any_cert(server_cert, password)
        server_cert_kea = server_cert.find_kea_type();

        #if verbose: print "server cert:\n%s" % server_cert

        sock = ssl.SSLSocket(net_addr.family)

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback, nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    if verbose: print "listening on: %s" % (net_addr)
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        if verbose: print "client connect from: %s" % (client_addr)

        while True:
            try:
                # Handle the client connection
                buf = client_sock.recv(1024)
                if not buf:
                    print >>sys.stderr, "server: lost lost connection to %s" % (client_addr)
                    break

                if info: print "server: received \"%s\"" % (buf)
                reply = "{%s}" % buf # echo
                if info: print "server: sending \"%s\"" % (reply)
                client_sock.send(reply) # echo

                time.sleep(sleep_time)
                client_sock.shutdown()
                client_sock.close()
                break
            except Exception, e:
                print >>sys.stderr, "server: %s" % e
                break
        break
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
Beispiel #25
0
        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)
            valid_addr = True
            break
        except Exception, e:
            sock.close()
def main():
    # Command line argument processing
    parser = optparse.OptionParser()

    parser.set_defaults(dbdir = '/etc/pki/nssdb',
                        db_passwd = 'db_passwd',
                        input_format = 'pem',
                        check_sig = True,
                        print_cert = False,
                        with_log = True,
                        check_ca = True,
                        )

    param_group = optparse.OptionGroup(parser, 'NSS Database',
                                       'Specify & control the NSS Database')

    param_group.add_option('-d', '--dbdir', dest='dbdir',
                           help='NSS database directory, default="%default"')
    param_group.add_option('-P', '--db-passwd', dest='db_passwd',
                           help='NSS database password, default="%default"')

    parser.add_option_group(param_group)

    param_group = optparse.OptionGroup(parser, 'Certificate',
                                       'Specify how the certificate is loaded')

    param_group.add_option('-f', '--file', dest='cert_filename',
                           help='read cert from file')
    param_group.add_option('--format', dest='input_format', choices=['pem', 'der'],
                           help='import format for certificate (der|pem) default="%default"')
    param_group.add_option('-n', '--nickname', dest='cert_nickname',
                           help='load cert from NSS database by looking it up under this nickname')


    parser.add_option_group(param_group)

    param_group = optparse.OptionGroup(parser, 'Validation',
                                       'Control the validation')

    param_group.add_option('-u', '--usage', dest='cert_usage', action='append', choices=cert_usage_map.keys(),
                           help='may be specified multiple times, default="CheckAllUsages", may be one of: %s' % ', '.join(sorted(cert_usage_map.keys())))
    param_group.add_option('-c', '--check-sig', action='store_true', dest='check_sig',
                           help='check signature default=%default')
    param_group.add_option('-C', '--no-check-sig', action='store_false', dest='check_sig',
                           help='check signature')
    param_group.add_option('-l', '--log', action='store_true', dest='with_log',
                           help='use verify log, default=%default')
    param_group.add_option('-L', '--no-log', action='store_false', dest='with_log',
                           help='use verify log, default=%default')
    param_group.add_option('-a', '--check-ca', action='store_true', dest='check_ca',
                           help='check if cert is CA, default=%default')
    param_group.add_option('-A', '--no-check-ca', action='store_false', dest='check_ca',
                           help='check if cert is CA, default=%default')

    parser.add_option_group(param_group)

    param_group = optparse.OptionGroup(parser, 'Miscellaneous',
                                       'Miscellaneous options')

    param_group.add_option('-p', '--print-cert', action='store_true', dest='print_cert',
                           help='print the certificate in a friendly fashion, default=%default')

    parser.add_option_group(param_group)

    options, args = parser.parse_args()

    # Process the command line arguments

    # Get usage bitmask
    if options.cert_usage:
        intended_usage = 0
        for usage in options.cert_usage:
            try:
                flag = cert_usage_map[usage]
            except KeyError:
                print "Unknown usage '%s', valid values: %s" % (usage, ', '.join(sorted(cert_usage_map.keys())))
                return 1
            else:
                intended_usage |= flag
    else:
        # We can't use nss.certificateUsageCheckAllUsages here because
        # it's a special value of zero instead of being the bitwise OR
        # of all the certificateUsage* flags (go figure!)
        intended_usage = 0
        for usage in cert_usage_map.values():
            intended_usage |= usage

    if options.cert_filename and options.cert_nickname:
        print >>sys.stderr, "You may not specify both a cert filename and a nickname, only one or the other"
        return 1

    if not options.cert_filename and not options.cert_nickname:
        print >>sys.stderr, "You must specify either a cert filename or a nickname to load"
        return 1

    # Initialize NSS.
    print indented_output('NSS Database', options.dbdir)
    print
    nss.nss_init(options.dbdir)
    certdb = nss.get_default_certdb()
    nss.set_password_callback(password_callback)

    # Load the cert
    if options.cert_filename:
        # Read the certificate as DER encoded data then initialize a Certificate from the DER data
        filename = options.cert_filename
        si = nss.read_der_from_file(filename, options.input_format.lower() == 'pem')
        # Parse the DER encoded data returning a Certificate object
        cert = nss.Certificate(si)
    else:
        try:
            cert = nss.find_cert_from_nickname(options.cert_nickname)
        except Exception, e:
            print e
            print >>sys.stderr, 'Unable to load cert nickname "%s" from database "%s"' % \
                (options.cert_nickname, options.dbdir)
            return 1
Beispiel #27
0
 def setUp(self):
     nss.nss_init_read_write(db_name)
     self.certdb = nss.get_default_certdb()
Beispiel #28
0
def Server():
    # Setup an IP Address to listen on any of our interfaces
    if options.family == io.PR_AF_UNSPEC:
        options.family = io.PR_AF_INET
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, options.port, options.family)

    if options.use_ssl:
        # Perform basic SSL server configuration
        ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
        ssl.config_server_session_id_cache()

        # Get our certificate and private key
        server_cert = nss.find_cert_from_nickname(options.server_nickname, options.password)
        priv_key = nss.find_key_by_any_cert(server_cert, options.password)
        server_cert_kea = server_cert.find_kea_type();

        print("server cert:\n%s" % server_cert)

        sock = ssl.SSLSocket(net_addr.family)

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(options.password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if options.client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if options.client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback, nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    print("listening on: %s" % (net_addr))
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if options.use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        print("client connect from: %s" % (client_addr))

        while True:
            try:
                # Handle the client connection
                buf = client_sock.readline()
                if not buf:
                    print("server lost lost connection to %s" % (client_addr))
                    break

                buf = buf.decode('utf-8')
                buf = buf.rstrip()                 # remove newline record separator
                print("server received: %s" % (buf))

                data ='Goodbye' + '\n' # newline is protocol record separator
                client_sock.send(data.encode('utf-8'))
                try:
                    client_sock.shutdown(io.PR_SHUTDOWN_RCV)
                    client_sock.close()
                except:
                    pass
                break
            except Exception as e:
                print(e.strerror)
                break
        break

    try:
        sock.shutdown()
        sock.close()
        if options.use_ssl:
            ssl.shutdown_server_session_id_cache()
    except Exception as e:
        print(e)
        pass
Beispiel #29
0
        self.sock = ssl.SSLSocket(family=self.family)
        self.sock.set_ssl_option(ssl.SSL_SECURITY, True)
        self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
        try:
            self.sock.set_ssl_version_range(self.tls_version_min, self.tls_version_max)
        except NSPRError, e:
            root_logger.error('Failed to set TLS range to %s, %s' % (self.tls_version_min, self.tls_version_max))
            raise
        self.sock.set_ssl_option(ssl_require_safe_negotiation, False)
        self.sock.set_ssl_option(ssl_enable_renegotiation, ssl_renegotiate_requires_xtn)
        # Provide a callback which notifies us when the SSL handshake is complete
        self.sock.set_handshake_callback(self.handshake_callback)

        # Provide a callback to verify the servers certificate
        self.sock.set_auth_certificate_callback(auth_certificate_callback,
                                                nss.get_default_certdb())
        self.sock.set_hostname(self.host)

    def password_callback(self, slot, retry, password):
        if not retry and password: return password
        return getpass.getpass("Enter password for %s: " % slot.token_name);

    def handshake_callback(self, sock):
        """
        Verify callback. If we get here then the certificate is ok.
        """
        channel = sock.get_ssl_channel_info()
        suite = ssl.get_cipher_suite_info(channel.cipher_suite)
        root_logger.debug("handshake complete, peer = %s", sock.get_peer_name())
        root_logger.debug('Protocol: %s' % channel.protocol_version_str.upper())
        root_logger.debug('Cipher: %s' % suite.cipher_suite_name)
Beispiel #30
0
 def setUp(self):
     nss.nss_init_read_write(db_name)
     self.certdb = nss.get_default_certdb()
Beispiel #31
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
Beispiel #32
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 Server():
    global family

    # Perform basic SSL server configuration
    ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
    ssl.config_server_session_id_cache()

    # Get our certificate and private key
    server_cert = nss.find_cert_from_nickname(server_nickname, password)
    priv_key = nss.find_key_by_any_cert(server_cert, password)
    server_cert_kea = server_cert.find_kea_type();

    print "server cert:\n%s" % server_cert

    # Setup an IP Address to listen on any of our interfaces
    if family == io.PR_AF_UNSPEC:
        family = io.PR_AF_INET
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, port, family)

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

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback, nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    print "listening on: %s" % (net_addr)
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        print "client connect from: %s" % (client_addr)

        while True:
            try:
                # Handle the client connection
                buf = client_sock.recv(1024)
                if not buf:
                    print "server lost lost connection to %s" % (client_addr)
                    break

                print "server received: %s" % (buf)

                client_sock.send("Goodbye")
                try:
                    client_sock.shutdown(io.PR_SHUTDOWN_RCV)
                    client_sock.close()
                except:
                    pass
                break
            except Exception, e:
                print e.strerror
                break
        break
Beispiel #34
0
 def __init__(self):
     self.certdb_dir = os.path.expanduser(config.NSS_DB_DIR)
     nss.nss_init(self.certdb_dir)
     nss.enable_ocsp_checking()
     self.certdb = nss.get_default_certdb()
Beispiel #35
0
def Server():
    # Setup an IP Address to listen on any of our interfaces
    if options.family == io.PR_AF_UNSPEC:
        options.family = io.PR_AF_INET
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, options.port, options.family)

    if options.use_ssl:
        # Perform basic SSL server configuration
        ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
        ssl.config_server_session_id_cache()

        # Get our certificate and private key
        server_cert = nss.find_cert_from_nickname(options.server_nickname,
                                                  options.password)
        priv_key = nss.find_key_by_any_cert(server_cert, options.password)
        server_cert_kea = server_cert.find_kea_type()

        print("server cert:\n%s" % server_cert)

        sock = ssl.SSLSocket(net_addr.family)

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(options.password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if options.client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if options.client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    print("listening on: %s" % (net_addr))
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if options.use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        print("client connect from: %s" % (client_addr))

        while True:
            try:
                # Handle the client connection
                buf = client_sock.readline()
                if not buf:
                    print("server lost lost connection to %s" % (client_addr))
                    break

                buf = buf.decode('utf-8')
                buf = buf.rstrip()  # remove newline record separator
                print("server received: %s" % (buf))

                data = 'Goodbye' + '\n'  # newline is protocol record separator
                client_sock.send(data.encode('utf-8'))
                try:
                    client_sock.shutdown(io.PR_SHUTDOWN_RCV)
                    client_sock.close()
                except:
                    pass
                break
            except Exception as e:
                print(e.strerror)
                break
        break

    try:
        sock.shutdown()
        sock.close()
        if options.use_ssl:
            ssl.shutdown_server_session_id_cache()
    except Exception as e:
        print(e)
        pass
Beispiel #36
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)
Beispiel #37
0
def main():
    global options

    parser = argparse.ArgumentParser(description='certificate trust example')

    # === NSS Database Group ===
    group = parser.add_argument_group('NSS Database',
                                      'Specify & control the NSS Database')
    group.add_argument('-d', '--db-name',
                       help='NSS database name (e.g. "sql:pki")')

    group.add_argument('-P', '--db-passwd',
                       help='NSS database password')

    # === Certificate Group ===
    group = parser.add_argument_group('Certificate',
                                      'Specify how the certificate is loaded')

    group.add_argument('-f', '--file', dest='cert_filename',
                       help='read cert from file')

    group.add_argument('-F', '--input-format', choices=['pem', 'der'],
                       help='format of input cert')

    group.add_argument('-n', '--nickname', dest='cert_nickname',
                       help='load cert from NSS database by looking it up under this nickname')

    group.add_argument('-t', '--trust', dest='cert_trust',
                       help='set the cert trust flags, see certutil for format')

    group.add_argument('-i', '--install-cert', action='store_true', dest='cert_perm',
                           help='check signature')
    group.add_argument('-p', '--print-cert', action='store_true', dest='print_cert',
                       help='print the certificate in a friendly fashion')

    parser.set_defaults(db_name = 'sql:pki',
                        db_passwd = 'db_passwd',
                        input_format = 'pem',
                        install_cert = False,
                        print_cert = False,
                        )

    options = parser.parse_args()

    # Process the command line arguments

    if options.cert_perm:
        if not options.cert_filename:
            print("You must specify a cert filename to install a cert in the database", file=sys.stderr)
            return 1

        if not options.cert_nickname:
            print("You must specify a cert nickname to install a cert in the database", file=sys.stderr)
            return 1
    else:
        if options.cert_filename and options.cert_nickname:
            print("You may not specify both a cert filename and a nickname, only one or the other", file=sys.stderr)
            return 1

        if not options.cert_filename and not options.cert_nickname:
            print("You must specify either a cert filename or a nickname to load", file=sys.stderr)
            return 1


    # Initialize NSS.
    print('NSS Database: %s' % (options.db_name))
    print()
    # Initialize the database as read/write, otherwise we would not
    # be able to import a cert
    nss.nss_init_read_write(options.db_name)
    certdb = nss.get_default_certdb()

    # Since we may update the cert make sure we're using the key slot
    # and not just the internal slot
    slot = nss.get_internal_key_slot()

    # If we're importing or modifying a cert we'll need to authenticate
    # to the database, the password callback supplies the password during
    # authentication.
    nss.set_password_callback(password_callback)

    # Load the cert
    if options.cert_filename:
        # Read the certificate as DER encoded data then initialize a Certificate from the DER data
        filename = options.cert_filename
        si = nss.read_der_from_file(filename, options.input_format.lower() == 'pem')
        # Parse the DER encoded data returning a Certificate object.
        #
        # If we've been asked to install the cert in the database the
        # options.cert_perm flag will be True and we'll need to supply
        # the nickname (which is used to locate the cert in the database).
        cert = nss.Certificate(si, certdb,
                               options.cert_perm, options.cert_nickname)
    else:
        try:
            cert = nss.find_cert_from_nickname(options.cert_nickname)
        except Exception as e:
            print(e)
            print('Unable to load cert nickname "%s" from database "%s"' % \
                (options.cert_nickname, options.db_name), file=sys.stderr)
            return 1

    # Dump the cert if the user wants to see it
    if options.print_cert:
        print(cert)
    else:
        print('cert subject: %s' % (cert.subject))
    print()

    # Change the cert trust if specified
    if options.cert_trust:
        cert.set_trust_attributes(options.cert_trust, certdb, slot)

    illustrate_ssl_trust(cert)

    return 0
Beispiel #38
0
def server():
    if verbose:
        print("starting server:")

    # Initialize
    # Setup an IP Address to listen on any of our interfaces
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, port)

    if use_ssl:
        if info:
            print("server: using SSL")
        ssl.set_domestic_policy()
        nss.set_password_callback(password_callback)

        # Perform basic SSL server configuration
        ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
        ssl.config_server_session_id_cache()

        # Get our certificate and private key
        server_cert = nss.find_cert_from_nickname(server_nickname, password)
        priv_key = nss.find_key_by_any_cert(server_cert, password)
        server_cert_kea = server_cert.find_kea_type()

        #if verbose:
        #    print("server cert:\n%s" % server_cert)

        sock = ssl.SSLSocket(net_addr.family)

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    if verbose:
        print("listening on: %s" % (net_addr))
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        if verbose:
            print("client connect from: %s" % (client_addr))

        while True:
            try:
                # Handle the client connection
                buf = client_sock.readline(
                )  # newline is protocol record separator
                if not buf:
                    print("server: lost lost connection to %s" % (client_addr),
                          file=sys.stderr)
                    break
                buf = buf.decode('utf-8')
                buf = buf.rstrip()  # remove newline record separator

                if info:
                    print("server: received \"%s\"" % (buf))
                reply = "{%s}" % buf  # echo embedded inside braces
                if info:
                    print("server: sending \"%s\"" % (reply))
                data = reply + "\n"  # send echo with record separator
                client_sock.send(data.encode('utf-8'))

                time.sleep(sleep_time)
                client_sock.shutdown()
                client_sock.close()
                break
            except Exception as e:
                print("server: %s" % e, file=sys.stderr)
                break
        break

    # Clean up
    sock.shutdown()
    sock.close()
    if use_ssl:
        ssl.shutdown_server_session_id_cache()
Beispiel #39
0
def main():
    global options

    parser = argparse.ArgumentParser(
        description='certificate validation example')

    # === NSS Database Group ===
    group = parser.add_argument_group('NSS Database',
                                      'Specify & control the NSS Database')
    group.add_argument('-d',
                       '--db-name',
                       help='NSS database name (e.g. "sql:pki")')

    group.add_argument('-P', '--db-passwd', help='NSS database password')

    # === Certificate Group ===
    group = parser.add_argument_group('Certificate',
                                      'Specify how the certificate is loaded')

    group.add_argument('-f',
                       '--file',
                       dest='cert_filename',
                       help='read cert from file')

    group.add_argument('-F',
                       '--input-format',
                       choices=['pem', 'der'],
                       help='format of input cert')

    group.add_argument(
        '-n',
        '--nickname',
        dest='cert_nickname',
        help='load cert from NSS database by looking it up under this nickname'
    )

    # === Validation Group ===
    group = parser.add_argument_group('Validation', 'Control the validation')

    group.add_argument(
        '-u',
        '--usage',
        dest='cert_usage',
        action='append',
        choices=list(cert_usage_map.keys()),
        help='certificate usage flags, may be specified multiple times')
    group.add_argument('-c',
                       '--check-sig',
                       action='store_true',
                       dest='check_sig',
                       help='check signature')
    group.add_argument('-C',
                       '--no-check-sig',
                       action='store_false',
                       dest='check_sig',
                       help='do not check signature')
    group.add_argument('-l',
                       '--log',
                       action='store_true',
                       dest='with_log',
                       help='use verify log')
    group.add_argument('-L',
                       '--no-log',
                       action='store_false',
                       dest='with_log',
                       help='do not use verify log')
    group.add_argument('-a',
                       '--check-ca',
                       action='store_true',
                       dest='check_ca',
                       help='check if cert is CA')
    group.add_argument('-A',
                       '--no-check-ca',
                       action='store_false',
                       dest='check_ca',
                       help='do not check if cert is CA')

    # === Miscellaneous Group ===
    group = parser.add_argument_group('Miscellaneous', 'Miscellaneous options')

    group.add_argument('-p',
                       '--print-cert',
                       action='store_true',
                       dest='print_cert',
                       help='print the certificate in a friendly fashion')

    parser.set_defaults(
        db_name='sql:pki',
        db_passwd='db_passwd',
        input_format='pem',
        check_sig=True,
        with_log=True,
        check_ca=True,
        print_cert=False,
    )

    options = parser.parse_args()

    # Process the command line arguments

    # Get usage bitmask
    if options.cert_usage:
        intended_usage = 0
        for usage in options.cert_usage:
            try:
                flag = cert_usage_map[usage]
            except KeyError:
                print("Unknown usage '%s', valid values: %s" %
                      (usage, ', '.join(sorted(cert_usage_map.keys()))))
                return 1
            else:
                intended_usage |= flag
    else:
        # We can't use nss.certificateUsageCheckAllUsages here because
        # it's a special value of zero instead of being the bitwise OR
        # of all the certificateUsage* flags (go figure!)
        intended_usage = 0
        for usage in list(cert_usage_map.values()):
            intended_usage |= usage

    if options.cert_filename and options.cert_nickname:
        print(
            "You may not specify both a cert filename and a nickname, only one or the other",
            file=sys.stderr)
        return 1

    if not options.cert_filename and not options.cert_nickname:
        print("You must specify either a cert filename or a nickname to load",
              file=sys.stderr)
        return 1

    # Initialize NSS.
    print(indented_output('NSS Database', options.db_name))
    print()
    nss.nss_init(options.db_name)
    certdb = nss.get_default_certdb()
    nss.set_password_callback(password_callback)

    # Load the cert
    if options.cert_filename:
        # Read the certificate as DER encoded data then initialize a Certificate from the DER data
        filename = options.cert_filename
        si = nss.read_der_from_file(filename,
                                    options.input_format.lower() == 'pem')
        # Parse the DER encoded data returning a Certificate object
        cert = nss.Certificate(si)
    else:
        try:
            cert = nss.find_cert_from_nickname(options.cert_nickname)
        except Exception as e:
            print(e)
            print('Unable to load cert nickname "%s" from database "%s"' % \
                (options.cert_nickname, options.db_name), file=sys.stderr)
            return 1

    # Dump the cert if the user wants to see it
    if options.print_cert:
        print(cert)
    else:
        print(indented_output('cert subject', cert.subject))
    print()

    # Dump the usages attached to the cert
    print(
        indented_output('cert has these usages',
                        nss.cert_type_flags(cert.cert_type)))

    # Should we check if the cert is a CA cert?
    if options.check_ca:
        # CA Cert?
        is_ca, cert_type = cert.is_ca_cert(True)
        print()
        print(indented_output('is CA cert boolean', is_ca))
        print(
            indented_output('is CA cert returned usages',
                            nss.cert_type_flags(cert_type)))

    print()
    print(
        indented_output('verifying usages for',
                        nss.cert_usage_flags(intended_usage)))
    print()

    # Use the log or non-log variant to verify the cert
    #
    # Note: Anytime a NSPR or NSS function returns an error in python-nss it
    # raises a NSPRError exception. When an exception is raised the normal
    # return values are discarded because the flow of control continues at
    # the first except block prepared to catch the exception. Normally this
    # is what is desired because the return values would be invalid due to
    # the error. However the certificate verification functions are an
    # exception (no pun intended). An error might be returned indicating the
    # cert failed verification but you may still need access to the returned
    # usage bitmask and the log (if using the log variant). To handle this a
    # special error exception `CertVerifyError` (derived from `NSPRError`)
    # is defined which in addition to the normal NSPRError fields will also
    # contain the returned usages and optionally the CertVerifyLog
    # object. If no exception is raised these are returned as normal return
    # values.

    approved_usage = 0
    if options.with_log:
        try:
            approved_usage, log = cert.verify_with_log(certdb,
                                                       options.check_sig,
                                                       intended_usage, None)
        except nss_error.CertVerifyError as e:
            # approved_usage and log available in CertVerifyError exception on failure.
            print(e)
            print()
            print(indented_obj('log', e.log))
            print()
            print(
                indented_output('approved usages from exception',
                                nss.cert_usage_flags(e.usages)))
            approved_usage = e.usages  # Get the returned usage bitmask from the exception
        except Exception as e:
            print(e)
        else:
            print(
                indented_output('approved usages',
                                nss.cert_usage_flags(approved_usage)))
            if log.count:
                print()
                print(indented_obj('log', log))
    else:
        try:
            approved_usage = cert.verify(certdb, options.check_sig,
                                         intended_usage, None)
        except nss_error.CertVerifyError as e:
            # approved_usage available in CertVerifyError exception on failure.
            print(e)
            print(
                indented_output('approved usages from exception',
                                nss.cert_usage_flags(e.usages)))
            approved_usage = e.usages  # Get the returned usage bitmask from the exception
        except Exception as e:
            print(e)
        else:
            print(
                indented_output('approved usages',
                                nss.cert_usage_flags(approved_usage)))

    # The cert is valid if all the intended usages are in the approved usages
    valid = (intended_usage & approved_usage) == intended_usage

    print()
    if valid:
        print(
            indented_output('SUCCESS: cert is approved for',
                            nss.cert_usage_flags(intended_usage)))
        return 0
    else:
        print(
            indented_output(
                'FAIL: cert not approved for',
                nss.cert_usage_flags(intended_usage ^ approved_usage)))
        return 1
Beispiel #40
0
 def __init__(self):
     self.certdb_dir = os.path.expanduser(config.NSS_DB_DIR)
     nss.nss_init(self.certdb_dir)
     nss.enable_ocsp_checking()
     self.certdb = nss.get_default_certdb()
Beispiel #41
0
def main():
    global options

    parser = argparse.ArgumentParser(description='certificate validation example')

    # === NSS Database Group ===
    group = parser.add_argument_group('NSS Database',
                                      'Specify & control the NSS Database')
    group.add_argument('-d', '--db-name',
                       help='NSS database name (e.g. "sql:pki")')

    group.add_argument('-P', '--db-passwd',
                       help='NSS database password')

    # === Certificate Group ===
    group = parser.add_argument_group('Certificate',
                                      'Specify how the certificate is loaded')

    group.add_argument('-f', '--file', dest='cert_filename',
                       help='read cert from file')

    group.add_argument('-F', '--input-format', choices=['pem', 'der'],
                       help='format of input cert')

    group.add_argument('-n', '--nickname', dest='cert_nickname',
                       help='load cert from NSS database by looking it up under this nickname')

    # === Validation Group ===
    group = parser.add_argument_group('Validation',
                                      'Control the validation')

    group.add_argument('-u', '--usage', dest='cert_usage', action='append', choices=list(cert_usage_map.keys()),
                           help='certificate usage flags, may be specified multiple times')
    group.add_argument('-c', '--check-sig', action='store_true', dest='check_sig',
                           help='check signature')
    group.add_argument('-C', '--no-check-sig', action='store_false', dest='check_sig',
                           help='do not check signature')
    group.add_argument('-l', '--log', action='store_true', dest='with_log',
                           help='use verify log')
    group.add_argument('-L', '--no-log', action='store_false', dest='with_log',
                           help='do not use verify log')
    group.add_argument('-a', '--check-ca', action='store_true', dest='check_ca',
                           help='check if cert is CA')
    group.add_argument('-A', '--no-check-ca', action='store_false', dest='check_ca',
                           help='do not check if cert is CA')

    # === Miscellaneous Group ===
    group = parser.add_argument_group('Miscellaneous',
                                      'Miscellaneous options')

    group.add_argument('-p', '--print-cert', action='store_true', dest='print_cert',
                       help='print the certificate in a friendly fashion')


    parser.set_defaults(db_name = 'sql:pki',
                        db_passwd = 'db_passwd',
                        input_format = 'pem',
                        check_sig = True,
                        with_log = True,
                        check_ca = True,
                        print_cert = False,
                        )

    options = parser.parse_args()

    # Process the command line arguments

    # Get usage bitmask
    if options.cert_usage:
        intended_usage = 0
        for usage in options.cert_usage:
            try:
                flag = cert_usage_map[usage]
            except KeyError:
                print("Unknown usage '%s', valid values: %s" % (usage, ', '.join(sorted(cert_usage_map.keys()))))
                return 1
            else:
                intended_usage |= flag
    else:
        # We can't use nss.certificateUsageCheckAllUsages here because
        # it's a special value of zero instead of being the bitwise OR
        # of all the certificateUsage* flags (go figure!)
        intended_usage = 0
        for usage in list(cert_usage_map.values()):
            intended_usage |= usage

    if options.cert_filename and options.cert_nickname:
        print("You may not specify both a cert filename and a nickname, only one or the other", file=sys.stderr)
        return 1

    if not options.cert_filename and not options.cert_nickname:
        print("You must specify either a cert filename or a nickname to load", file=sys.stderr)
        return 1

    # Initialize NSS.
    print(indented_output('NSS Database', options.db_name))
    print()
    nss.nss_init(options.db_name)
    certdb = nss.get_default_certdb()
    nss.set_password_callback(password_callback)

    # Load the cert
    if options.cert_filename:
        # Read the certificate as DER encoded data then initialize a Certificate from the DER data
        filename = options.cert_filename
        si = nss.read_der_from_file(filename, options.input_format.lower() == 'pem')
        # Parse the DER encoded data returning a Certificate object
        cert = nss.Certificate(si)
    else:
        try:
            cert = nss.find_cert_from_nickname(options.cert_nickname)
        except Exception as e:
            print(e)
            print('Unable to load cert nickname "%s" from database "%s"' % \
                (options.cert_nickname, options.db_name), file=sys.stderr)
            return 1

    # Dump the cert if the user wants to see it
    if options.print_cert:
        print(cert)
    else:
        print(indented_output('cert subject', cert.subject))
    print()

    # Dump the usages attached to the cert
    print(indented_output('cert has these usages', nss.cert_type_flags(cert.cert_type)))

    # Should we check if the cert is a CA cert?
    if options.check_ca:
        # CA Cert?
        is_ca, cert_type = cert.is_ca_cert(True)
        print()
        print(indented_output('is CA cert boolean', is_ca))
        print(indented_output('is CA cert returned usages', nss.cert_type_flags(cert_type)))

    print()
    print(indented_output('verifying usages for', nss.cert_usage_flags(intended_usage)))
    print()

    # Use the log or non-log variant to verify the cert
    #
    # Note: Anytime a NSPR or NSS function returns an error in python-nss it
    # raises a NSPRError exception. When an exception is raised the normal
    # return values are discarded because the flow of control continues at
    # the first except block prepared to catch the exception. Normally this
    # is what is desired because the return values would be invalid due to
    # the error. However the certificate verification functions are an
    # exception (no pun intended). An error might be returned indicating the
    # cert failed verification but you may still need access to the returned
    # usage bitmask and the log (if using the log variant). To handle this a
    # special error exception `CertVerifyError` (derived from `NSPRError`)
    # is defined which in addition to the normal NSPRError fields will also
    # contain the returned usages and optionally the CertVerifyLog
    # object. If no exception is raised these are returned as normal return
    # values.

    approved_usage = 0
    if options.with_log:
        try:
            approved_usage, log = cert.verify_with_log(certdb, options.check_sig, intended_usage, None)
        except nss_error.CertVerifyError as e:
            # approved_usage and log available in CertVerifyError exception on failure.
            print(e)
            print()
            print(indented_obj('log', e.log))
            print()
            print(indented_output('approved usages from exception', nss.cert_usage_flags(e.usages)))
            approved_usage = e.usages # Get the returned usage bitmask from the exception
        except Exception as e:
            print(e)
        else:
            print(indented_output('approved usages', nss.cert_usage_flags(approved_usage)))
            if log.count:
                print()
                print(indented_obj('log', log))
    else:
        try:
            approved_usage = cert.verify(certdb, options.check_sig, intended_usage, None)
        except nss_error.CertVerifyError as e:
            # approved_usage available in CertVerifyError exception on failure.
            print(e)
            print(indented_output('approved usages from exception', nss.cert_usage_flags(e.usages)))
            approved_usage = e.usages # Get the returned usage bitmask from the exception
        except Exception as e:
            print(e)
        else:
            print(indented_output('approved usages', nss.cert_usage_flags(approved_usage)))

    # The cert is valid if all the intended usages are in the approved usages
    valid = (intended_usage & approved_usage) == intended_usage

    print()
    if valid:
        print(indented_output('SUCCESS: cert is approved for', nss.cert_usage_flags(intended_usage)))
        return 0
    else:
        print(indented_output('FAIL: cert not approved for', nss.cert_usage_flags(intended_usage ^ approved_usage)))
        return 1
Beispiel #42
0
        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:
            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, e:
            sock.close()
Beispiel #43
0
from conf import config


if __name__ == "__main__":
    parser = optparse.OptionParser("usage: %prog -f <folder with certificates> ")
    parser.add_option("-f", "--folder", dest="folder", help="Directory that holds certificates")

    (opts, args) = parser.parse_args()
    if opts.folder is None:
        parser.error("Specify the name of directory")

    path = os.path.expanduser(opts.folder)

    certdb_dir = os.path.expanduser(config.NSS_DB_DIR)
    nss.nss_init(certdb_dir)
    certdb = nss.get_default_certdb()
    db = PinDB("pfc", "keycontinuity")

    for i in os.listdir(path):
        file = os.path.join(path, i)
        if os.path.isfile(file):
            # f = open(file).readlines()
            # f =  ''.join(f)
            try:
                a = M2Crypto.X509.load_cert(file, format=FORMAT_DER)
            except:
                # we should transform PEM encoding to DER
                cmdstr = ["openssl", "x509", "-in", file, "-inform", "PEM", "-out", file, "-outform", "DER"]
                subprocess.call(cmdstr)
                a = M2Crypto.X509.load_cert(file, format=FORMAT_DER)
Beispiel #44
0
def server():
    global family

    if verbose: print "starting server:"

    # Initialize
    # Setup an IP Address to listen on any of our interfaces
    if family == io.PR_AF_UNSPEC:
        family = io.PR_AF_INET
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, port, family)

    if use_ssl:
        if info: print "server: using SSL"
        ssl.set_domestic_policy()
        nss.set_password_callback(password_callback)

        # Perform basic SSL server configuration
        ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
        ssl.config_server_session_id_cache()

        # Get our certificate and private key
        server_cert = nss.find_cert_from_nickname(server_nickname, password)
        priv_key = nss.find_key_by_any_cert(server_cert, password)
        server_cert_kea = server_cert.find_kea_type()

        #if verbose: print "server cert:\n%s" % server_cert

        sock = ssl.SSLSocket(net_addr.family)

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    if verbose: print "listening on: %s" % (net_addr)
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        if verbose: print "client connect from: %s" % (client_addr)

        while True:
            try:
                # Handle the client connection
                buf = client_sock.recv(1024)
                if not buf:
                    print >> sys.stderr, "server: lost lost connection to %s" % (
                        client_addr)
                    break

                if info: print "server: received \"%s\"" % (buf)
                reply = "{%s}" % buf  # echo
                if info: print "server: sending \"%s\"" % (reply)
                client_sock.send(reply)  # echo

                time.sleep(sleep_time)
                client_sock.shutdown()
                client_sock.close()
                break
            except Exception, e:
                print >> sys.stderr, "server: %s" % e
                break
        break
def Server():
    global family

    # Perform basic SSL server configuration
    ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
    ssl.config_server_session_id_cache()

    # Get our certificate and private key
    server_cert = nss.find_cert_from_nickname(server_nickname, password)
    priv_key = nss.find_key_by_any_cert(server_cert, password)
    server_cert_kea = server_cert.find_kea_type()

    print "server cert:\n%s" % server_cert

    # Setup an IP Address to listen on any of our interfaces
    if family == io.PR_AF_UNSPEC:
        family = io.PR_AF_INET
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, port, family)

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

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback,
                                           nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    print "listening on: %s" % (net_addr)
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        print "client connect from: %s" % (client_addr)

        while True:
            try:
                # Handle the client connection
                buf = client_sock.recv(1024)
                if not buf:
                    print "server lost lost connection to %s" % (client_addr)
                    break

                print "server received: %s" % (buf)

                client_sock.send("Goodbye")
                try:
                    client_sock.shutdown(io.PR_SHUTDOWN_RCV)
                    client_sock.close()
                except:
                    pass
                break
            except Exception, e:
                print e.strerror
                break
        break
def server():
    if verbose:
        print("starting server:")

    # Initialize
    # Setup an IP Address to listen on any of our interfaces
    net_addr = io.NetworkAddress(io.PR_IpAddrAny, port)

    if use_ssl:
        if info:
            print("server: using SSL")
        ssl.set_domestic_policy()
        nss.set_password_callback(password_callback)

        # Perform basic SSL server configuration
        ssl.set_default_cipher_pref(ssl.SSL_RSA_WITH_NULL_MD5, True)
        ssl.config_server_session_id_cache()

        # Get our certificate and private key
        server_cert = nss.find_cert_from_nickname(server_nickname, password)
        priv_key = nss.find_key_by_any_cert(server_cert, password)
        server_cert_kea = server_cert.find_kea_type();

        #if verbose:
        #    print("server cert:\n%s" % server_cert)

        sock = ssl.SSLSocket(net_addr.family)

        # Set server SSL socket options
        sock.set_pkcs11_pin_arg(password)
        sock.set_ssl_option(ssl.SSL_SECURITY, True)
        sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_SERVER, True)

        # If we're doing client authentication then set it up
        if client_cert_action >= REQUEST_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUEST_CERTIFICATE, True)
        if client_cert_action == REQUIRE_CLIENT_CERT_ONCE:
            sock.set_ssl_option(ssl.SSL_REQUIRE_CERTIFICATE, True)
        sock.set_auth_certificate_callback(auth_certificate_callback, nss.get_default_certdb())

        # Configure the server SSL socket
        sock.config_secure_server(server_cert, priv_key, server_cert_kea)

    else:
        sock = io.Socket(net_addr.family)

    # Bind to our network address and listen for clients
    sock.bind(net_addr)
    if verbose:
        print("listening on: %s" % (net_addr))
    sock.listen()

    while True:
        # Accept a connection from a client
        client_sock, client_addr = sock.accept()
        if use_ssl:
            client_sock.set_handshake_callback(handshake_callback)

        if verbose:
            print("client connect from: %s" % (client_addr))

        while True:
            try:
                # Handle the client connection
                buf = client_sock.readline()   # newline is protocol record separator
                if not buf:
                    print("server: lost lost connection to %s" % (client_addr), file=sys.stderr)
                    break
                buf = buf.decode('utf-8')
                buf = buf.rstrip()             # remove newline record separator

                if info:
                    print("server: received \"%s\"" % (buf))
                reply = "{%s}" % buf           # echo embedded inside braces
                if info:
                    print("server: sending \"%s\"" % (reply))
                data = reply + "\n" # send echo with record separator
                client_sock.send(data.encode('utf-8'))

                time.sleep(sleep_time)
                client_sock.shutdown()
                client_sock.close()
                break
            except Exception as e:
                print("server: %s" % e, file=sys.stderr)
                break
        break

    # Clean up
    sock.shutdown()
    sock.close()
    if use_ssl:
        ssl.shutdown_server_session_id_cache()