Пример #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
Пример #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()
Пример #3
0
 def test_full(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "full.xml"))
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == [
             (
                 u"KID1",
                 {
                     "ipatokenotpkey": u"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
                     "ipatokennotafter": u"20060531000000Z",
                     "ipatokennotbefore": u"20060501000000Z",
                     "ipatokenserial": u"SerialNo-IssueNo",
                     "ipatokentotpclockoffset": 60000,
                     "ipatokenotpalgorithm": u"sha1",
                     "ipatokenvendor": u"iana.dummy",
                     "description": u"FriendlyName",
                     "ipatokentotptimestep": 200,
                     "ipatokenhotpcounter": 0,
                     "ipatokenmodel": u"Model",
                     "ipatokenotpdigits": 8,
                     "type": u"hotp",
                 },
             )
         ]
     finally:
         nss.nss_shutdown()
Пример #4
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()
Пример #5
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
Пример #6
0
    def __init__(self, host, port=None, strict=None,
                 dbdir=None, family=socket.AF_UNSPEC, no_init=False,
                 tls_version_min='tls1.1', tls_version_max='tls1.2'):
        """
        :param host: the server to connect to
        :param port: the port to use (default is set in HTTPConnection)
        :param dbdir: the NSS database directory
        :param family: network family to use (default AF_UNSPEC)
        :param no_init: do not initialize the NSS database. This requires
                        that the database has already been initialized or
                        the request will fail.
        :param tls_min_version: mininum version of SSL/TLS supported
        :param tls_max_version: maximum version of SSL/TLS supported.
        """
        httplib.HTTPConnection.__init__(self, host, port, strict)
        NSSAddressFamilyFallback.__init__(self, family)

        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
Пример #7
0
def run_server():
    pid = os.fork()
    if pid == 0:
        nss.nss_init(db_name)
        server()
        nss.nss_shutdown()
    time.sleep(sleep_time)
    return pid
Пример #8
0
def run_server():
    pid = os.fork()
    if pid == 0:
        nss.nss_init(certdir)
        server()
        nss.nss_shutdown()
    time.sleep(sleep_time)
    return pid
Пример #9
0
 def test_figure8(self):
     nss.nss_init_nodb()
     try:
         PSKCDocument(os.path.join(basename, "pskc-figure8.xml"))
     except NotImplementedError:  # X.509 is not supported.
         pass
     else:
         assert False
     finally:
         nss.nss_shutdown()
Пример #10
0
 def test_invalid(self):
     nss.nss_init_nodb()
     try:
         PSKCDocument(os.path.join(basename, "pskc-invalid.xml"))
     except ValueError:  # File is invalid.
         pass
     else:
         assert False
     finally:
         nss.nss_shutdown()
Пример #11
0
 def test_invalid(self):
     nss.nss_init_nodb()
     try:
         PSKCDocument(os.path.join(basename, "pskc-invalid.xml"))
     except ValueError: # File is invalid.
         pass
     else:
         assert False
     finally:
         nss.nss_shutdown()
Пример #12
0
 def test_figure8(self):
     nss.nss_init_nodb()
     try:
         PSKCDocument(os.path.join(basename, "pskc-figure8.xml"))
     except NotImplementedError: # X.509 is not supported.
         pass
     else:
         assert False
     finally:
         nss.nss_shutdown()
Пример #13
0
 def test_mini(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-mini.xml"))
         [(t.id, t.options) for t in doc.getKeyPackages()]
     except ValidationError: # Unsupported token type.
         pass
     else:
         assert False
     finally:
         nss.nss_shutdown()
Пример #14
0
 def test_mini(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-mini.xml"))
         [(t.id, t.options) for t in doc.getKeyPackages()]
     except ValidationError:  # Unsupported token type.
         pass
     else:
         assert False
     finally:
         nss.nss_shutdown()
Пример #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
Пример #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
Пример #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)
        self.tls_version_min = str(tls_version_min)
        self.tls_version_max = str(tls_version_max)
Пример #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)
        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]
Пример #19
0
 def test_figure7(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-figure7.xml"))
         assert doc.keyname == 'My Password 1'
         doc.setKey('qwerty')
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == \
             [(u'123456', {
                 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ',
                 'ipatokenvendor': u'TokenVendorAcme',
                 'ipatokenserial': u'987654321',
                 'ipatokenotpdigits': 8,
                 'type': u'hotp'})]
     finally:
         nss.nss_shutdown()
Пример #20
0
 def test_figure7(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-figure7.xml"))
         assert doc.keyname == 'My Password 1'
         doc.setKey('qwerty')
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == \
             [(u'123456', {
                 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ',
                 'ipatokenvendor': u'TokenVendorAcme',
                 'ipatokenserial': u'987654321',
                 'ipatokenotpdigits': 8,
                 'type': u'hotp'})]
     finally:
         nss.nss_shutdown()
Пример #21
0
 def test_figure6(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-figure6.xml"))
         assert doc.keyname == 'Pre-shared-key'
         doc.setKey('12345678901234567890123456789012'.decode('hex'))
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == \
             [(u'12345678', {
                 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ',
                 'ipatokenvendor': u'Manufacturer',
                 'ipatokenserial': u'987654321',
                 'ipatokenhotpcounter': 0,
                 'ipatokenotpdigits': 8,
                 'type': u'hotp'})]
     finally:
         nss.nss_shutdown()
Пример #22
0
 def test_figure6(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-figure6.xml"))
         assert doc.keyname == 'Pre-shared-key'
         doc.setKey('12345678901234567890123456789012'.decode('hex'))
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == \
             [(u'12345678', {
                 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ',
                 'ipatokenvendor': u'Manufacturer',
                 'ipatokenserial': u'987654321',
                 'ipatokenhotpcounter': 0,
                 'ipatokenotpdigits': 8,
                 'type': u'hotp'})]
     finally:
         nss.nss_shutdown()
Пример #23
0
 def test_figure7(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-figure7.xml"))
         assert doc.keyname == "My Password 1"
         doc.setKey("qwerty")
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == [
             (
                 u"123456",
                 {
                     "ipatokenotpkey": u"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
                     "ipatokenvendor": u"TokenVendorAcme",
                     "ipatokenserial": u"987654321",
                     "ipatokenotpdigits": 8,
                     "type": u"hotp",
                 },
             )
         ]
     finally:
         nss.nss_shutdown()
Пример #24
0
 def test_figure6(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "pskc-figure6.xml"))
         assert doc.keyname == "Pre-shared-key"
         doc.setKey("12345678901234567890123456789012".decode("hex"))
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == [
             (
                 u"12345678",
                 {
                     "ipatokenotpkey": u"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
                     "ipatokenvendor": u"Manufacturer",
                     "ipatokenserial": u"987654321",
                     "ipatokenhotpcounter": 0,
                     "ipatokenotpdigits": 8,
                     "type": u"hotp",
                 },
             )
         ]
     finally:
         nss.nss_shutdown()
Пример #25
0
 def test_full(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "full.xml"))
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == \
             [(u'KID1', {
                 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ',
                 'ipatokennotafter': u'20060531000000Z',
                 'ipatokennotbefore': u'20060501000000Z',
                 'ipatokenserial': u'SerialNo-IssueNo',
                 'ipatokentotpclockoffset': 60000,
                 'ipatokenotpalgorithm': u'sha1',
                 'ipatokenvendor': u'iana.dummy',
                 'description': u'FriendlyName',
                 'ipatokentotptimestep': 200,
                 'ipatokenhotpcounter': 0,
                 'ipatokenmodel': u'Model',
                 'ipatokenotpdigits': 8,
                 'type': u'hotp',
             })]
     finally:
         nss.nss_shutdown()
Пример #26
0
 def test_full(self):
     nss.nss_init_nodb()
     try:
         doc = PSKCDocument(os.path.join(basename, "full.xml"))
         assert [(t.id, t.options) for t in doc.getKeyPackages()] == \
             [(u'KID1', {
                 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ',
                 'ipatokennotafter': u'20060531000000Z',
                 'ipatokennotbefore': u'20060501000000Z',
                 'ipatokenserial': u'SerialNo-IssueNo',
                 'ipatokentotpclockoffset': 60000,
                 'ipatokenotpalgorithm': u'sha1',
                 'ipatokenvendor': u'iana.dummy',
                 'description': u'FriendlyName',
                 'ipatokentotptimestep': 200,
                 'ipatokenhotpcounter': 0,
                 'ipatokenmodel': u'Model',
                 'ipatokenotpdigits': 8,
                 'type': u'hotp',
             })]
     finally:
         nss.nss_shutdown()
Пример #27
0
    def test_shutdown_callback(self):
        int_value = 43
        str_value = u"foobar"
        count = 0
        dict_value = {'count': count}

        def shutdown_callback(nss_data, i, s, d):
            self.assertEqual(isinstance(nss_data, dict), True)

            self.assertEqual(isinstance(i, int), True)
            self.assertEqual(i, int_value)

            self.assertEqual(isinstance(s, six.string_types), True)
            self.assertEqual(s, str_value)

            self.assertEqual(isinstance(d, dict), True)
            self.assertEqual(d, dict_value)
            d['count'] += 1
            return True

        nss.nss_init_nodb()
        nss.set_shutdown_callback(shutdown_callback, int_value, str_value, dict_value)
        nss.nss_shutdown()
        self.assertEqual(dict_value['count'], count + 1)

        # Callback should not be invoked again after shutdown
        nss.nss_init_nodb()
        nss.nss_shutdown()
        self.assertEqual(dict_value['count'], count + 1)

        # Callback should not be invoked if cleared
        nss.nss_init_nodb()
        nss.set_shutdown_callback(shutdown_callback, int_value, str_value, dict_value)
        nss.set_shutdown_callback(None)
        nss.nss_shutdown()
        self.assertEqual(dict_value['count'], count + 1)
Пример #28
0
    def execute(self, argv):

        try:
            opts, args = getopt.getopt(argv, 'i:v',
                                       ['instance=', 'verbose', 'help'])

        except getopt.GetoptError as e:
            print('ERROR: ' + str(e))
            self.usage()
            sys.exit(1)

        if len(args) < 1:
            print('ERROR: missing subsystem ID')
            self.usage()
            sys.exit(1)

        if len(args) < 2:
            print('ERROR: missing cert ID')
            self.usage()
            sys.exit(1)

        subsystem_name = args[0]
        cert_id = args[1]
        instance_name = 'pki-tomcat'

        for o, a in opts:
            if o in ('-i', '--instance'):
                instance_name = a

            elif o in ('-v', '--verbose'):
                self.set_verbose(True)

            elif o == '--help':
                self.print_help()
                sys.exit()

            else:
                print('ERROR: unknown option ' + o)
                self.usage()
                sys.exit(1)

        instance = pki.server.PKIInstance(instance_name)
        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        subsystem_cert = subsystem.get_subsystem_cert(cert_id)

        # get cert data from NSS database
        nss.nss_init(instance.nssdb_dir)
        nss_cert = nss.find_cert_from_nickname(subsystem_cert['nickname'])
        data = base64.b64encode(nss_cert.der_data)
        del nss_cert
        nss.nss_shutdown()
        subsystem_cert['data'] = data

        # format cert data for LDAP database
        lines = [data[i:i + 64] for i in range(0, len(data), 64)]
        data = string.join(lines, '\r\n') + '\r\n'

        # get cert request from local CA
        # TODO: add support for remote CA
        ca = instance.get_subsystem('ca')
        results = ca.find_cert_requests(cert=data)
        cert_request = results[-1]
        request = cert_request['request']

        # format cert request for CS.cfg
        lines = request.splitlines()
        if lines[0] == '-----BEGIN CERTIFICATE REQUEST-----':
            lines = lines[1:]
        if lines[-1] == '-----END CERTIFICATE REQUEST-----':
            lines = lines[:-1]
        request = string.join(lines, '')
        subsystem_cert['request'] = request

        # store cert data and request in CS.cfg
        subsystem.update_subsystem_cert(subsystem_cert)
        subsystem.save()

        self.print_message('Updated "%s" subsystem certificate' % cert_id)

        SubsystemCertCLI.print_subsystem_cert(subsystem_cert)
Пример #29
0
    def renew_external_step_2(self, ca, old_cert):
        print "Importing the renewed CA certificate, please wait"

        options = self.options
        cert_file, ca_file = installutils.load_external_cert(
            options.external_cert_files, x509.subject_base())

        nss_cert = None
        nss.nss_init(ca.dogtag_constants.ALIAS_DIR)
        try:
            nss_cert = x509.load_certificate(old_cert, x509.DER)
            subject = nss_cert.subject
            der_subject = x509.get_der_subject(old_cert, x509.DER)
            #pylint: disable=E1101
            pkinfo = nss_cert.subject_public_key_info.format()
            #pylint: enable=E1101

            nss_cert = x509.load_certificate_from_file(cert_file.name)
            cert = nss_cert.der_data
            if nss_cert.subject != subject:
                raise admintool.ScriptError(
                    "Subject name mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            if x509.get_der_subject(cert, x509.DER) != der_subject:
                raise admintool.ScriptError(
                    "Subject name encoding mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: disable=E1101
            if nss_cert.subject_public_key_info.format() != pkinfo:
                raise admintool.ScriptError(
                    "Subject public key info mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: enable=E1101
        finally:
            del nss_cert
            nss.nss_shutdown()

        with certs.NSSDatabase() as tmpdb:
            pw = ipautil.write_tmp_file(ipautil.ipa_generate_password())
            tmpdb.create_db(pw.name)
            tmpdb.add_cert(old_cert, 'IPA CA', 'C,,')

            try:
                tmpdb.add_cert(cert, 'IPA CA', 'C,,')
            except ipautil.CalledProcessError, e:
                raise admintool.ScriptError(
                    "Not compatible with the current CA certificate: %s" % e)

            ca_certs = x509.load_certificate_list_from_file(ca_file.name)
            for ca_cert in ca_certs:
                tmpdb.add_cert(ca_cert.der_data, str(ca_cert.subject), 'C,,')
            del ca_certs
            del ca_cert

            try:
                tmpdb.verify_ca_cert_validity('IPA CA')
            except ValueError, e:
                raise admintool.ScriptError(
                    "Not a valid CA certificate: %s (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)" % e)
Пример #30
0
 def main(cls, argv):
     nss.nss_init_nodb()
     try:
         super(OTPTokenImport, cls).main(argv)
     finally:
         nss.nss_shutdown()
Пример #31
0
    def renew_external_step_2(self, ca, old_cert):
        print("Importing the renewed CA certificate, please wait")

        options = self.options
        conn = api.Backend.ldap2
        cert_file, ca_file = installutils.load_external_cert(
            options.external_cert_files, x509.subject_base())

        nss_cert = None
        nss.nss_init(paths.PKI_TOMCAT_ALIAS_DIR)
        try:
            nss_cert = x509.load_certificate(old_cert, x509.DER)
            subject = nss_cert.subject
            der_subject = x509.get_der_subject(old_cert, x509.DER)
            #pylint: disable=E1101
            pkinfo = nss_cert.subject_public_key_info.format()
            #pylint: enable=E1101

            nss_cert = x509.load_certificate_from_file(cert_file.name)
            cert = nss_cert.der_data
            if nss_cert.subject != subject:
                raise admintool.ScriptError(
                    "Subject name mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            if x509.get_der_subject(cert, x509.DER) != der_subject:
                raise admintool.ScriptError(
                    "Subject name encoding mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: disable=E1101
            if nss_cert.subject_public_key_info.format() != pkinfo:
                raise admintool.ScriptError(
                    "Subject public key info mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: enable=E1101
        finally:
            del nss_cert
            nss.nss_shutdown()

        with certs.NSSDatabase() as tmpdb:
            pw = ipautil.write_tmp_file(ipautil.ipa_generate_password())
            tmpdb.create_db(pw.name)
            tmpdb.add_cert(old_cert, 'IPA CA', 'C,,')

            try:
                tmpdb.add_cert(cert, 'IPA CA', 'C,,')
            except ipautil.CalledProcessError as e:
                raise admintool.ScriptError(
                    "Not compatible with the current CA certificate: %s" % e)

            ca_certs = x509.load_certificate_list_from_file(ca_file.name)
            for ca_cert in ca_certs:
                tmpdb.add_cert(ca_cert.der_data, str(ca_cert.subject), 'C,,')
            del ca_certs
            del ca_cert

            try:
                tmpdb.verify_ca_cert_validity('IPA CA')
            except ValueError as e:
                raise admintool.ScriptError(
                    "Not a valid CA certificate: %s (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)" % e)

            trust_chain = tmpdb.get_trust_chain('IPA CA')[:-1]
            for nickname in trust_chain:
                try:
                    ca_cert = tmpdb.get_cert(nickname)
                except RuntimeError:
                    break
                certstore.put_ca_cert_nss(
                    conn, api.env.basedn, ca_cert, nickname, ',,')

        dn = DN(('cn', self.cert_nickname), ('cn', 'ca_renewal'),
                ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
        try:
            entry = conn.get_entry(dn, ['usercertificate'])
            entry['usercertificate'] = [cert]
            conn.update_entry(entry)
        except errors.NotFound:
            entry = conn.make_entry(
                dn,
                objectclass=['top', 'pkiuser', 'nscontainer'],
                cn=[self.cert_nickname],
                usercertificate=[cert])
            conn.add_entry(entry)
        except errors.EmptyModlist:
            pass

        try:
            ca.set_renewal_master()
        except errors.NotFound:
            raise admintool.ScriptError("CA renewal master not found")

        self.resubmit_request(ca, 'ipaRetrieval')

        print("CA certificate successfully renewed")
Пример #32
0
 def tearDown(self):
     del self.encoding_ctx
     del self.decoding_ctx
     nss.nss_shutdown()
Пример #33
0
    def renew_external_step_2(self, ca, old_cert):
        print "Importing the renewed CA certificate, please wait"

        options = self.options
        cert_file, ca_file = installutils.load_external_cert(
            options.external_cert_files, x509.subject_base())

        nss_cert = None
        nss.nss_init(ca.dogtag_constants.ALIAS_DIR)
        try:
            nss_cert = x509.load_certificate(old_cert, x509.DER)
            subject = nss_cert.subject
            der_subject = x509.get_der_subject(old_cert, x509.DER)
            #pylint: disable=E1101
            pkinfo = nss_cert.subject_public_key_info.format()
            #pylint: enable=E1101

            nss_cert = x509.load_certificate_from_file(cert_file.name)
            cert = nss_cert.der_data
            if nss_cert.subject != subject:
                raise admintool.ScriptError(
                    "Subject name mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            if x509.get_der_subject(cert, x509.DER) != der_subject:
                raise admintool.ScriptError(
                    "Subject name encoding mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: disable=E1101
            if nss_cert.subject_public_key_info.format() != pkinfo:
                raise admintool.ScriptError(
                    "Subject public key info mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: enable=E1101
        finally:
            del nss_cert
            nss.nss_shutdown()

        with certs.NSSDatabase() as tmpdb:
            pw = ipautil.write_tmp_file(ipautil.ipa_generate_password())
            tmpdb.create_db(pw.name)
            tmpdb.add_cert(old_cert, 'IPA CA', 'C,,')

            try:
                tmpdb.add_cert(cert, 'IPA CA', 'C,,')
            except ipautil.CalledProcessError, e:
                raise admintool.ScriptError(
                    "Not compatible with the current CA certificate: %s" % e)

            ca_certs = x509.load_certificate_list_from_file(ca_file.name)
            for ca_cert in ca_certs:
                tmpdb.add_cert(ca_cert.der_data, str(ca_cert.subject), 'C,,')
            del ca_certs
            del ca_cert

            try:
                tmpdb.verify_ca_cert_validity('IPA CA')
            except ValueError, e:
                raise admintool.ScriptError(
                    "Not a valid CA certificate: %s (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)" % e)
Пример #34
0
 def tearDown(self):
     nss.nss_shutdown()
Пример #35
0
 def test_ssl(self):
     request = "foo"
     nss.nss_init(certdir)
     reply = client(request)
     nss.nss_shutdown()
     self.assertEqual("{%s}" % request, reply)
Пример #36
0
    def renew_external_step_2(self, ca, old_cert):
        print("Importing the renewed CA certificate, please wait")

        options = self.options
        conn = api.Backend.ldap2
        cert_file, ca_file = installutils.load_external_cert(
            options.external_cert_files, x509.subject_base())

        nss_cert = None
        nss.nss_init(paths.PKI_TOMCAT_ALIAS_DIR)
        try:
            nss_cert = x509.load_certificate(old_cert, x509.DER)
            subject = nss_cert.subject
            der_subject = x509.get_der_subject(old_cert, x509.DER)
            #pylint: disable=E1101
            pkinfo = nss_cert.subject_public_key_info.format()
            #pylint: enable=E1101

            nss_cert = x509.load_certificate_from_file(cert_file.name)
            cert = nss_cert.der_data
            if nss_cert.subject != subject:
                raise admintool.ScriptError(
                    "Subject name mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            if x509.get_der_subject(cert, x509.DER) != der_subject:
                raise admintool.ScriptError(
                    "Subject name encoding mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: disable=E1101
            if nss_cert.subject_public_key_info.format() != pkinfo:
                raise admintool.ScriptError(
                    "Subject public key info mismatch (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)")
            #pylint: enable=E1101
        finally:
            del nss_cert
            nss.nss_shutdown()

        with certs.NSSDatabase() as tmpdb:
            pw = ipautil.write_tmp_file(ipautil.ipa_generate_password())
            tmpdb.create_db(pw.name)
            tmpdb.add_cert(old_cert, 'IPA CA', 'C,,')

            try:
                tmpdb.add_cert(cert, 'IPA CA', 'C,,')
            except ipautil.CalledProcessError as e:
                raise admintool.ScriptError(
                    "Not compatible with the current CA certificate: %s" % e)

            ca_certs = x509.load_certificate_list_from_file(ca_file.name)
            for ca_cert in ca_certs:
                tmpdb.add_cert(ca_cert.der_data, str(ca_cert.subject), 'C,,')
            del ca_certs
            del ca_cert

            try:
                tmpdb.verify_ca_cert_validity('IPA CA')
            except ValueError as e:
                raise admintool.ScriptError(
                    "Not a valid CA certificate: %s (visit "
                    "http://www.freeipa.org/page/Troubleshooting for "
                    "troubleshooting guide)" % e)

            trust_chain = tmpdb.get_trust_chain('IPA CA')[:-1]
            for nickname in trust_chain:
                try:
                    ca_cert = tmpdb.get_cert(nickname)
                except RuntimeError:
                    break
                certstore.put_ca_cert_nss(conn, api.env.basedn, ca_cert,
                                          nickname, ',,')

        dn = DN(('cn', self.cert_nickname), ('cn', 'ca_renewal'),
                ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
        try:
            entry = conn.get_entry(dn, ['usercertificate'])
            entry['usercertificate'] = [cert]
            conn.update_entry(entry)
        except errors.NotFound:
            entry = conn.make_entry(
                dn,
                objectclass=['top', 'pkiuser', 'nscontainer'],
                cn=[self.cert_nickname],
                usercertificate=[cert])
            conn.add_entry(entry)
        except errors.EmptyModlist:
            pass

        try:
            ca.set_renewal_master()
        except errors.NotFound:
            raise admintool.ScriptError("CA renewal master not found")

        self.resubmit_request(ca, 'ipaRetrieval')

        print("CA certificate successfully renewed")
if client and server:
    print "can't be both client and server"
    sys.exit(1)
if not (client or server):
    print "must be one of client or server"
    sys.exit(1)

# Perform basic configuration and setup
if certdir is None:
    nss.nss_init_nodb()
else:
    nss.nss_init(certdir)

ssl.set_domestic_policy()
nss.set_password_callback(password_callback)

# Run as a client or as a server
if client:
    print "starting as client"
    Client()

if server:
    print "starting as server"
    Server()

try:
    nss.nss_shutdown()
except Exception, e:
    print e
Пример #38
0
 def tearDown(self):
     nss.nss_shutdown()
Пример #39
0
            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, 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

    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)
Пример #40
0
    def execute(self, argv):

        try:
            opts, args = getopt.getopt(argv, 'i:v', [
                'instance=',
                'verbose', 'help'])

        except getopt.GetoptError as e:
            print('ERROR: ' + str(e))
            self.usage()
            sys.exit(1)

        if len(args) < 1:
            print('ERROR: missing subsystem ID')
            self.usage()
            sys.exit(1)

        if len(args) < 2:
            print('ERROR: missing cert ID')
            self.usage()
            sys.exit(1)

        subsystem_name = args[0]
        cert_id = args[1]
        instance_name = 'pki-tomcat'

        for o, a in opts:
            if o in ('-i', '--instance'):
                instance_name = a

            elif o in ('-v', '--verbose'):
                self.set_verbose(True)

            elif o == '--help':
                self.print_help()
                sys.exit()

            else:
                print('ERROR: unknown option ' + o)
                self.usage()
                sys.exit(1)

        instance = pki.server.PKIInstance(instance_name)
        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        subsystem_cert = subsystem.get_subsystem_cert(cert_id)

        # get cert data from NSS database
        nss.nss_init(instance.nssdb_dir)
        nss_cert = nss.find_cert_from_nickname(subsystem_cert['nickname'])
        data = base64.b64encode(nss_cert.der_data)
        del nss_cert
        nss.nss_shutdown()
        subsystem_cert['data'] = data

        # format cert data for LDAP database
        lines = [data[i:i + 64] for i in range(0, len(data), 64)]
        data = string.join(lines, '\r\n') + '\r\n'

        # get cert request from local CA
        # TODO: add support for remote CA
        ca = instance.get_subsystem('ca')
        results = ca.find_cert_requests(cert=data)
        cert_request = results[-1]
        request = cert_request['request']

        # format cert request for CS.cfg
        lines = request.splitlines()
        if lines[0] == '-----BEGIN CERTIFICATE REQUEST-----':
            lines = lines[1:]
        if lines[-1] == '-----END CERTIFICATE REQUEST-----':
            lines = lines[:-1]
        request = string.join(lines, '')
        subsystem_cert['request'] = request

        # store cert data and request in CS.cfg
        subsystem.update_subsystem_cert(subsystem_cert)
        subsystem.save()

        self.print_message('Updated "%s" subsystem certificate' % cert_id)

        SubsystemCertCLI.print_subsystem_cert(subsystem_cert)
Пример #41
0
 def test_ssl(self):
     request = "foo"
     nss.nss_init(db_name)
     reply = client(request)
     nss.nss_shutdown()
     self.assertEqual("{%s}" % request, reply)
Пример #42
0
 def main(cls, argv):
     nss.nss_init_nodb()
     try:
         super(OTPTokenImport, cls).main(argv)
     finally:
         nss.nss_shutdown()
Пример #43
0
 def tearDown(self):
     del self.encoding_ctx
     del self.decoding_ctx
     nss.nss_shutdown()