Esempio n. 1
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
Esempio n. 2
0
def load_certificate(data, datatype=PEM, dbdir=None):
    """
    Given a base64-encoded certificate, with or without the
    header/footer, return a request object.

    Returns a nss.Certificate type
    """
    if type(data) in (tuple, list):
        data = data[0]

    if (datatype == PEM):
        data = strip_header(data)
        data = base64.b64decode(data)

    if not nss.nss_is_initialized():
        if dbdir is None:
            if 'in_tree' in api.env:
                if api.env.in_tree:
                    dbdir = api.env.dot_ipa + os.sep + 'alias'
                else:
                    dbdir = "/etc/httpd/alias"
                nss.nss_init(dbdir)
            else:
                nss.nss_init_nodb()
        else:
            nss.nss_init(dbdir)

    return nss.Certificate(buffer(data))
Esempio n. 3
0
    def __init__(self, host, port=None, strict=None):
        six.moves.http_client.HTTPConnection.__init__(self, host, port, strict)

        logging.debug('%s init %s', self.__class__.__name__, host)
        if not nss.nss_is_initialized():
            nss.nss_init_nodb()
        self.sock = None
Esempio n. 4
0
def load_certificate(data, datatype=PEM, dbdir=None):
    """
    Given a base64-encoded certificate, with or without the
    header/footer, return a request object.

    Returns a nss.Certificate type
    """
    if type(data) in (tuple, list):
        data = data[0]

    if (datatype == PEM):
        data = strip_header(data)
        data = base64.b64decode(data)

    if not nss.nss_is_initialized():
        if dbdir is None:
            if 'in_tree' in api.env:
                if api.env.in_tree:
                    dbdir = api.env.dot_ipa + os.sep + 'alias'
                else:
                    dbdir = "/etc/httpd/alias"
                nss.nss_init(dbdir)
            else:
                nss.nss_init_nodb()
        else:
            nss.nss_init(dbdir)

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

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

        root_logger.debug('%s init %s', self.__class__.__name__, host)
        if not no_init and nss.nss_is_initialized():
            # close any open NSS database and use the new one
            ssl.clear_session_cache()
            try:
                nss.nss_shutdown()
            except NSPRError, e:
                if e.errno != error.SEC_ERROR_NOT_INITIALIZED:
                    raise e
Esempio n. 6
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()
Esempio n. 7
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()
Esempio n. 8
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
Esempio n. 9
0
    def init(self):
        if nss.nss_is_initialized():
            return

        if _password_callback is not None:
            nss.set_password_callback(_password_callback)

        nss.nss_init(_certdb)
        ssl.set_domestic_policy()
Esempio n. 10
0
    def init(self):
        if nss.nss_is_initialized():
            return

        if _password_callback is not None:
            nss.set_password_callback(_password_callback)

        nss.nss_init(_certdb)
        ssl.set_domestic_policy()
Esempio n. 11
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)
    def __init__(self, host, port=None, strict=None, dbdir=None):
        httplib.HTTPConnection.__init__(self, host, port, strict)

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

        logging.debug('%s init %s', self.__class__.__name__, host)
        if not nss.nss_is_initialized(): nss.nss_init(dbdir)
        self.sock = None
        ssl.set_domestic_policy()
        nss.set_password_callback(password_callback)
Esempio n. 13
0
    def __init__(self, host, port=None, strict=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                 certdb=None, log=None):
        httplib.HTTPConnection.__init__(self, host, port, strict, timeout)
        if not nss.nss_is_initialized():
            NSSAdapterException('NSS is not initialized')

        if not isinstance(certdb, nss.CertDB):
            raise TypeError(certdb)
        self.certdb = certdb
        self.log = log if log is not None else logger
Esempio n. 14
0
    def __init__(self, host, port=None, strict=None, dbdir=None):
        six.moves.http_client.HTTPConnection.__init__(self, host, port, strict)

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

        logging.debug('%s init host=%s dbdir=%s', self.__class__.__name__, host, dbdir)
        if not nss.nss_is_initialized(): nss.nss_init(dbdir)
        self.sock = None
        ssl.set_domestic_policy()
        nss.set_password_callback(password_callback)
Esempio n. 15
0
    def shutdown(self):
        if not nss.nss_is_initialized():
            return

        try:
            ssl.clear_session_cache()
        except Exception:
            pass
        try:
            nss.nss_shutdown()
        except Exception:
            pass
Esempio n. 16
0
    def shutdown(self):
        if not nss.nss_is_initialized():
            return

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

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

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

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

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

            nss.nss_init(dbdir)

            global current_dbdir
            current_dbdir = dbdir

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

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

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

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

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

            nss.nss_init(dbdir)

            global current_dbdir
            current_dbdir = dbdir

        ssl.set_domestic_policy()
        nss.set_password_callback(self.password_callback)
        self.tls_version_min = str(tls_version_min)
        self.tls_version_max = str(tls_version_max)
Esempio n. 19
0
def load_certificate_request(csr, datatype=PEM):
    """
    Given a base64-encoded certificate request, with or without the
    header/footer, return a request object.
    """
    if datatype == PEM:
        csr = strip_header(csr)
        csr = base64.b64decode(csr)

    # A fail-safe so we can always read a CSR. python-nss/NSS will segfault
    # otherwise
    if not nss.nss_is_initialized():
        nss.nss_init_nodb()

    return nss.CertificateRequest(csr)
Esempio n. 20
0
def load_certificate_request(csr, datatype=PEM):
    """
    Given a base64-encoded certificate request, with or without the
    header/footer, return a request object.
    """
    if datatype == PEM:
        csr = strip_header(csr)
        csr = base64.b64decode(csr)

    # A fail-safe so we can always read a CSR. python-nss/NSS will segfault
    # otherwise
    if not nss.nss_is_initialized():
        nss.nss_init_nodb()

    return nss.CertificateRequest(csr)
Esempio n. 21
0
def initialize_nss_database(dbdir=None):
    """
    Initializes NSS database, if not initialized yet. Uses a proper database
    directory (.ipa/alias or HTTPD_ALIAS_DIR), depending on the value of
    api.env.in_tree.
    """

    if not nss.nss_is_initialized():
        if dbdir is None:
            if 'in_tree' in api.env:
                if api.env.in_tree:
                    dbdir = api.env.dot_ipa + os.sep + 'alias'
                else:
                    dbdir = paths.HTTPD_ALIAS_DIR
                nss.nss_init(dbdir)
            else:
                nss.nss_init_nodb()
        else:
            nss.nss_init(dbdir)
Esempio n. 22
0
def initialize_nss_database(dbdir=None):
    """
    Initializes NSS database, if not initialized yet. Uses a proper database
    directory (.ipa/alias or HTTPD_ALIAS_DIR), depending on the value of
    api.env.in_tree.
    """

    if not nss.nss_is_initialized():
        if dbdir is None:
            if 'in_tree' in api.env:
                if api.env.in_tree:
                    dbdir = api.env.dot_ipa + os.sep + 'alias'
                else:
                    dbdir = paths.HTTPD_ALIAS_DIR
                nss.nss_init(dbdir)
            else:
                nss.nss_init_nodb()
        else:
            nss.nss_init(dbdir)
    def __init__(self, host, port=None, strict=None):
        httplib.HTTPConnection.__init__(self, host, port, strict)

        logging.debug('%s init %s', self.__class__.__name__, host)
        if not nss.nss_is_initialized(): nss.nss_init_nodb()
        self.sock = None