コード例 #1
0
ファイル: subsystem.py プロジェクト: tiran/pki
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(
                argv, 'i:v',
                ['instance=', 'show-all', 'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.usage()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        show_all = False

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

            elif o == '--show-all':
                show_all = True

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.usage()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing subsystem ID')
            self.usage()
            sys.exit(1)

        if len(args) < 2:
            logger.error('Missing cert ID')
            self.usage()
            sys.exit(1)

        subsystem_name = args[0]
        cert_id = args[1]

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

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('ERROR: No %s subsystem in instance %s.',
                         subsystem_name, instance_name)
            sys.exit(1)
        cert = subsystem.get_subsystem_cert(cert_id)
        self.print_message('"{}" subsystem "{}" certificate'.format(
            subsystem_name, cert_id))
        SubsystemCertCLI.print_subsystem_cert(cert, show_all)
コード例 #2
0
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'cert-file=', 'csr-file=',
                'pkcs12-file=', 'pkcs12-password='******'pkcs12-password-file=',
                'friendly-name=',
                'cert-encryption=', 'key-encryption=',
                'append', 'no-trust-flags', 'no-key', 'no-chain',
                'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        cert_file = None
        csr_file = None
        pkcs12_file = None
        pkcs12_password = None
        pkcs12_password_file = None
        friendly_name = None
        cert_encryption = None
        key_encryption = None
        append = False
        include_trust_flags = True
        include_key = True
        include_chain = True

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

            elif o == '--cert-file':
                cert_file = a

            elif o == '--csr-file':
                csr_file = a

            elif o == '--pkcs12-file':
                pkcs12_file = a

            elif o == '--pkcs12-password':
                pkcs12_password = a

            elif o == '--pkcs12-password-file':
                pkcs12_password_file = a

            elif o == '--friendly-name':
                friendly_name = a

            elif o == '--cert-encryption':
                cert_encryption = a

            elif o == '--key-encryption':
                key_encryption = a

            elif o == '--append':
                append = True

            elif o == '--no-trust-flags':
                include_trust_flags = False

            elif o == '--no-key':
                include_key = False

            elif o == '--no-chain':
                include_chain = False

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('option %s not recognized', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing cert ID.')
            self.print_help()
            sys.exit(1)

        cert_id = args[0]

        if not (cert_file or csr_file or pkcs12_file):
            logger.error('missing output file')
            self.print_help()
            sys.exit(1)

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

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name, cert_tag = pki.server.PKIServer.split_cert_id(cert_id)

        # If cert ID is instance specific, get it from first subsystem
        if not subsystem_name:
            subsystem_name = instance.get_subsystems()[0].name

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error(
                'No %s subsystem in instance %s.',
                subsystem_name, instance_name)
            sys.exit(1)

        cert = subsystem.get_subsystem_cert(cert_tag)

        if not cert:
            logger.error('missing %s certificate', cert_id)
            self.print_help()
            sys.exit(1)

        if cert_id == 'sslserver':
            full_name = instance.get_sslserver_cert_nickname()
            i = full_name.find(':')
            if i < 0:
                nickname = full_name
                token = None

            else:
                nickname = full_name[i + 1:]
                token = full_name[:i]

        else:
            # get nickname and token from CS.cfg
            nickname = cert['nickname']
            token = cert['token']

        logger.info('Nickname: %s', nickname)
        logger.info('Token: %s', token)

        nssdb = instance.open_nssdb(token)

        try:
            if cert_file:

                logger.info('Exporting %s certificate into %s.', cert_id, cert_file)

                cert_data = cert.get('data')
                if cert_data is None:
                    logger.error('Unable to find certificate data for %s', cert_id)
                    sys.exit(1)

                cert_data = pki.nssdb.convert_cert(cert_data, 'base64', 'pem')
                with open(cert_file, 'w') as f:
                    f.write(cert_data)

            if csr_file:

                logger.info('Exporting %s CSR into %s.', cert_id, csr_file)

                cert_request = cert.get('request')
                if cert_request is None:
                    logger.error('Unable to find certificate request for %s', cert_id)
                    sys.exit(1)

                csr_data = pki.nssdb.convert_csr(cert_request, 'base64', 'pem')
                with open(csr_file, 'w') as f:
                    f.write(csr_data)

            if pkcs12_file:

                logger.info('Exporting %s certificate and key into %s.', cert_id, pkcs12_file)

                if not pkcs12_password and not pkcs12_password_file:
                    pkcs12_password = getpass.getpass(prompt='Enter password for PKCS #12 file: ')

                logger.info('Friendly name: %s', friendly_name)

                nssdb.export_cert(
                    nickname=nickname,
                    pkcs12_file=pkcs12_file,
                    pkcs12_password=pkcs12_password,
                    pkcs12_password_file=pkcs12_password_file,
                    friendly_name=friendly_name,
                    cert_encryption=cert_encryption,
                    key_encryption=key_encryption,
                    append=append,
                    include_trust_flags=include_trust_flags,
                    include_key=include_key,
                    include_chain=include_chain)

        finally:
            nssdb.close()
コード例 #3
0
ファイル: cert.py プロジェクト: edewata/pki
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'show-all', 'pretty-print',
                'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        show_all = False
        pretty_print = False

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

            elif o == '--show-all':
                show_all = True

            elif o == '--pretty-print':
                pretty_print = True

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('option %s not recognized', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing cert ID.')
            self.print_help()
            sys.exit(1)

        cert_id = args[0]

        instance = pki.server.instance.PKIServerFactory.create(instance_name)

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name, cert_tag = pki.server.PKIServer.split_cert_id(cert_id)

        # If cert ID is instance specific, get it from first subsystem
        if not subsystem_name:
            subsystem_name = instance.get_subsystems()[0].name

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error(
                'No %s subsystem in instance %s.',
                subsystem_name, instance_name)
            sys.exit(1)

        cert = subsystem.get_subsystem_cert(cert_tag)
        CertCLI.print_system_cert(cert, show_all)

        if pretty_print:

            print()

            nssdb = instance.open_nssdb()
            try:
                nssdb.show_cert(
                    nickname=cert['nickname'],
                    token=cert['token'])
            finally:
                nssdb.close()
コード例 #4
0
    def execute(self, argv):
        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'cert=', 'format=',
                'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        subsystem_name = self.parent.parent.parent.name
        cert_path = None
        cert_format = 'PEM'

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

            elif o == '--cert':
                cert_path = a

            elif o == '--format':
                cert_format = a

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing user ID')
            self.print_help()
            sys.exit(1)

        user_id = args[0]

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        subsystem.add_user_cert(user_id, cert_path=cert_path, cert_format=cert_format)
コード例 #5
0
ファイル: db.py プロジェクト: edewata/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'hostname=', 'port=', 'secure=', 'auth=', 'bindDN=',
                'bindPWPrompt=', 'nickname=', 'database=', 'baseDN=',
                'multiSuffix=', 'maxConns=', 'minConns=', 'verbose', 'debug',
                'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        hostname = None
        port = None
        secure = None
        auth = None
        bindDN = None
        bindPWPrompt = None
        nickname = None
        database = None
        baseDN = None
        multiSuffix = None
        maxConns = None
        minConns = None

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

            elif o == '--hostname':
                hostname = a

            elif o == '--port':
                if not a.isdigit():
                    raise ValueError('Invalid input: %s accepts a number' % o)
                port = a

            elif o == '--secure':
                if a.lower() not in ['true', 'false']:
                    raise ValueError(
                        'Invalid input: %s accepts True or False' % o)
                secure = a.lower() == 'true'

            elif o == '--auth':
                if a not in ['BasicAuth', 'SslClientAuth']:
                    raise ValueError('Invalid input: %s' % a)
                auth = a

            elif o == '--bindDN':
                bindDN = a

            elif o == '--bindPWPrompt':
                bindPWPrompt = a

            elif o == '--nickname':
                nickname = a

            elif o == '--database':
                database = a

            elif o == '--baseDN':
                baseDN = a

            elif o == '--multiSuffix':
                if a.lower() not in ['true', 'false']:
                    raise ValueError(
                        'Invalid input: %s accepts True or False' % o)
                multiSuffix = a.lower() == 'true'

            elif o == '--maxConns':
                if not a.isdigit():
                    raise ValueError('Invalid input: %s accepts a number' % o)
                maxConns = a

            elif o == '--minConns':
                if not a.isdigit():
                    raise ValueError('Invalid input: %s accepts a number' % o)
                minConns = a

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name = self.parent.parent.parent.name
        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        name = 'internaldb.%s'

        if hostname:
            subsystem.config[name % 'ldapconn.host'] = hostname

        if port:
            subsystem.config[name % 'ldapconn.port'] = port

        if secure is not None:
            if secure:
                subsystem.config[name % 'ldapconn.secureConn'] = 'true'
            else:
                subsystem.config[name % 'ldapconn.secureConn'] = 'false'

        if auth:
            subsystem.config[name % 'ldapauth.authtype'] = auth

        if bindDN:
            subsystem.config[name % 'ldapauth.bindDN'] = bindDN

        if bindPWPrompt:
            subsystem.config[name % 'ldapauth.bindPWPrompt'] = bindPWPrompt

        if nickname:
            subsystem.config[name % 'ldapauth.clientCertNickname'] = nickname

        if database:
            subsystem.config[name % 'database'] = database

        if baseDN:
            subsystem.config[name % 'basedn'] = baseDN

        if multiSuffix is not None:
            if multiSuffix:
                subsystem.config[name % 'multipleSuffix.enable'] = 'true'
            else:
                subsystem.config[name % 'multipleSuffix.enable'] = 'false'

        if maxConns:
            subsystem.config[name % 'maxConns'] = maxConns

        if minConns:
            subsystem.config[name % 'minConns'] = minConns

        subsystem.save()

        SubsystemDBCLI.print_config(subsystem)
コード例 #6
0
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:D:w:x:g:v', [
                'instance=', 'bind-dn=', 'bind-password='******'generate-ldif=',
                'verbose', 'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        bind_dn = None
        bind_password = None

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

            elif o in ('-D', '--bind-dn'):
                bind_dn = a

            elif o in ('-w', '--bind-password'):
                bind_password = a

            elif o in ('-g', '--generate-ldif'):
                self.out_file = a

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

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

        if not instance.is_valid():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem('kra')

        if not subsystem:
            logger.error('No KRA subsystem in instance %s.', instance_name)
            sys.exit(1)

        self.delete_vlv(subsystem, bind_dn, bind_password)

        print('KRA VLVs deleted from the database for ' + instance_name)
コード例 #7
0
    def spawn(self, deployer):

        external = deployer.configuration_file.external
        standalone = deployer.configuration_file.standalone
        subordinate = deployer.configuration_file.subordinate
        clone = deployer.configuration_file.clone

        if config.str2bool(deployer.mdict['pki_skip_installation']):
            logger.info('Skipping subsystem creation')
            return

        logger.info('Creating %s subsystem', deployer.mdict['pki_subsystem'])

        # If pki_one_time_pin is not specified, generate a new one
        if 'pki_one_time_pin' not in deployer.mdict:
            pin = ''.join(
                random.choice(string.ascii_letters + string.digits)
                for x in range(20))
            deployer.mdict['pki_one_time_pin'] = pin
            deployer.mdict['PKI_RANDOM_NUMBER_SLOT'] = pin

        instance = self.instance

        # Create /var/log/pki/<instance>/<subsystem>
        instance.makedirs(deployer.mdict['pki_subsystem_log_path'],
                          exist_ok=True)

        # Create /var/log/pki/<instance>/<subsystem>/archive
        instance.makedirs(deployer.mdict['pki_subsystem_archive_log_path'],
                          exist_ok=True)

        # Create /var/log/pki/<instance>/<subsystem>/signedAudit
        instance.makedirs(
            deployer.mdict['pki_subsystem_signed_audit_log_path'],
            exist_ok=True)

        # Create /etc/pki/<instance>/<subsystem>
        instance.makedirs(deployer.mdict['pki_subsystem_configuration_path'],
                          exist_ok=True)

        # Copy /usr/share/pki/<subsystem>/conf/CS.cfg
        # to /etc/pki/<instance>/<subsystem>/CS.cfg
        instance.copyfile(deployer.mdict['pki_source_cs_cfg'],
                          deployer.mdict['pki_target_cs_cfg'],
                          slots=deployer.slots,
                          params=deployer.mdict)

        # Copy /usr/share/pki/<subsystem>/conf/registry.cfg
        # to /etc/pki/<instance>/<subsystem>/registry.cfg
        instance.copy(deployer.mdict['pki_source_registry_cfg'],
                      deployer.mdict['pki_target_registry_cfg'])

        if deployer.mdict['pki_subsystem'] == "CA":

            # Copy /usr/share/pki/ca/emails
            # to /etc/pki/<instance>/ca/emails
            instance.copy(deployer.mdict['pki_source_emails'],
                          deployer.mdict['pki_subsystem_emails_path'])

            # Link /var/lib/pki/<instance>/ca/emails
            # to /etc/pki/<instance>/ca/emails
            emails_path = os.path.join(instance.conf_dir, 'ca', 'emails')
            emails_link = os.path.join(instance.base_dir, 'ca', 'emails')
            instance.symlink(emails_path, emails_link)

            # Copy /usr/share/pki/ca/profiles
            # to /etc/pki/<instance>/ca/profiles
            instance.copy(deployer.mdict['pki_source_profiles'],
                          deployer.mdict['pki_subsystem_profiles_path'])

            # Link /var/lib/pki/<instance>/ca/profiles
            # to /etc/pki/<instance>/ca/profiles
            profiles_path = os.path.join(instance.conf_dir, 'ca', 'profiles')
            profiles_link = os.path.join(instance.base_dir, 'ca', 'profiles')
            instance.symlink(profiles_path, profiles_link)

            # Copy /usr/share/pki/<subsystem>/conf/flatfile.txt
            # to /etc/pki/<instance>/<subsystem>/flatfile.txt
            instance.copy(deployer.mdict['pki_source_flatfile_txt'],
                          deployer.mdict['pki_target_flatfile_txt'])

            # Copy /usr/share/pki/<subsystem>/conf/<type>AdminCert.profile
            # to /etc/pki/<instance>/<subsystem>/adminCert.profile
            instance.copy(deployer.mdict['pki_source_admincert_profile'],
                          deployer.mdict['pki_target_admincert_profile'])

            # Copy /usr/share/pki/<subsystem>/conf/caAuditSigningCert.profile
            # to /etc/pki/<instance>/<subsystem>/caAuditSigningCert.profile
            instance.copy(
                deployer.mdict['pki_source_caauditsigningcert_profile'],
                deployer.mdict['pki_target_caauditsigningcert_profile'])

            # Copy /usr/share/pki/<subsystem>/conf/caCert.profile
            # to /etc/pki/<instance>/<subsystem>/caCert.profile
            instance.copy(deployer.mdict['pki_source_cacert_profile'],
                          deployer.mdict['pki_target_cacert_profile'])

            # Copy /usr/share/pki/<subsystem>/conf/caOCSPCert.profile
            # to /etc/pki/<instance>/<subsystem>/caOCSPCert.profile
            instance.copy(deployer.mdict['pki_source_caocspcert_profile'],
                          deployer.mdict['pki_target_caocspcert_profile'])

            # Copy /usr/share/pki/<subsystem>/conf/<type>ServerCert.profile
            # to /etc/pki/<instance>/<subsystem>/serverCert.profile
            instance.copy(deployer.mdict['pki_source_servercert_profile'],
                          deployer.mdict['pki_target_servercert_profile'])

            # Copy /usr/share/pki/<subsystem>/conf/<type>SubsystemCert.profile
            # to /etc/pki/<instance>/<subsystem>/subsystemCert.profile
            instance.copy(deployer.mdict['pki_source_subsystemcert_profile'],
                          deployer.mdict['pki_target_subsystemcert_profile'])

            # Copy /usr/share/pki/<subsystem>/conf/proxy.conf
            # to /etc/pki/<instance>/<subsystem>/proxy.conf
            instance.copyfile(deployer.mdict['pki_source_proxy_conf'],
                              deployer.mdict['pki_target_proxy_conf'],
                              slots=deployer.slots,
                              params=deployer.mdict)

        elif deployer.mdict['pki_subsystem'] == "TPS":

            # Copy /usr/share/pki/<subsystem>/conf/registry.cfg
            # to /etc/pki/<instance>/<subsystem>/registry.cfg
            instance.copy(deployer.mdict['pki_source_registry_cfg'],
                          deployer.mdict['pki_target_registry_cfg'])

            # Copy /usr/share/pki/<subsystem>/conf/phoneHome.xml
            # to /etc/pki/<instance>/<subsystem>/phoneHome.xml
            instance.copyfile(deployer.mdict['pki_source_phone_home_xml'],
                              deployer.mdict['pki_target_phone_home_xml'],
                              slots=deployer.slots,
                              params=deployer.mdict)

        # Link /var/lib/pki/<instance>/<subsystem>/conf
        # to /etc/pki/<instance>/<subsystem>
        instance.symlink(deployer.mdict['pki_subsystem_configuration_path'],
                         deployer.mdict['pki_subsystem_conf_link'])

        # Link /var/lib/pki/<instance>/<subsystem>/logs
        # to /var/log/pki/<instance>/<subsystem>
        instance.symlink(deployer.mdict['pki_subsystem_log_path'],
                         deployer.mdict['pki_subsystem_logs_link'])

        # Link /var/lib/pki/<instance>/<subsystem>/registry
        # to /etc/sysconfig/pki/tomcat/<instance>
        instance.symlink(deployer.mdict['pki_instance_registry_path'],
                         deployer.mdict['pki_subsystem_registry_link'])

        instance = self.instance
        instance.load()

        subsystem = instance.get_subsystem(
            deployer.mdict['pki_subsystem'].lower())

        subsystem.config['preop.subsystem.name'] = deployer.mdict[
            'pki_subsystem_name']

        certs = subsystem.find_system_certs()
        for cert in certs:

            # get CS.cfg tag and pkispawn tag
            config_tag = cert['id']
            deploy_tag = config_tag

            if config_tag == 'signing':  # for CA and OCSP
                deploy_tag = subsystem.name + '_signing'

            keytype = deployer.mdict['pki_%s_key_type' % deploy_tag]
            subsystem.config['preop.cert.%s.keytype' % config_tag] = keytype

        # configure SSL server cert
        if subsystem.type == 'CA' and clone or subsystem.type != 'CA':

            subsystem.config['preop.cert.sslserver.type'] = 'remote'
            keytype = subsystem.config['preop.cert.sslserver.keytype']

            if keytype.lower() == 'ecc':
                subsystem.config[
                    'preop.cert.sslserver.profile'] = 'caECInternalAuthServerCert'

            elif keytype.lower() == 'rsa':
                subsystem.config[
                    'preop.cert.sslserver.profile'] = 'caInternalAuthServerCert'

        # configure subsystem cert
        if deployer.mdict['pki_security_domain_type'] == 'new':

            subsystem.config['preop.cert.subsystem.type'] = 'local'
            subsystem.config[
                'preop.cert.subsystem.profile'] = 'subsystemCert.profile'

        else:  # deployer.mdict['pki_security_domain_type'] == 'existing':

            subsystem.config['preop.cert.subsystem.type'] = 'remote'
            keytype = subsystem.config['preop.cert.subsystem.keytype']

            if keytype.lower() == 'ecc':
                subsystem.config[
                    'preop.cert.subsystem.profile'] = 'caECInternalAuthSubsystemCert'

            elif keytype.lower() == 'rsa':
                subsystem.config[
                    'preop.cert.subsystem.profile'] = 'caInternalAuthSubsystemCert'

        if external or standalone:

            # This is needed by IPA to detect step 1 completion.
            # See is_step_one_done() in ipaserver/install/cainstance.py.

            subsystem.config['preop.ca.type'] = 'otherca'

        elif subsystem.type != 'CA' or subordinate:

            subsystem.config['preop.ca.type'] = 'sdca'

        # configure cloning
        if config.str2bool(deployer.mdict['pki_clone']):
            subsystem.config['subsystem.select'] = 'Clone'
        else:
            subsystem.config['subsystem.select'] = 'New'

        # configure CA
        if subsystem.type == 'CA':

            if external or subordinate:
                subsystem.config['hierarchy.select'] = 'Subordinate'
            else:
                subsystem.config['hierarchy.select'] = 'Root'

            if subordinate:
                subsystem.config['preop.cert.signing.type'] = 'remote'
                subsystem.config[
                    'preop.cert.signing.profile'] = 'caInstallCACert'

        # configure OCSP
        if subsystem.type == 'OCSP':
            if clone:
                subsystem.config['ocsp.store.defStore.refreshInSec'] = '14400'

        # configure TPS
        if subsystem.type == 'TPS':
            subsystem.config['auths.instance.ldap1.ldap.basedn'] = \
                deployer.mdict['pki_authdb_basedn']
            subsystem.config['auths.instance.ldap1.ldap.ldapconn.host'] = \
                deployer.mdict['pki_authdb_hostname']
            subsystem.config['auths.instance.ldap1.ldap.ldapconn.port'] = \
                deployer.mdict['pki_authdb_port']
            subsystem.config['auths.instance.ldap1.ldap.ldapconn.secureConn'] = \
                deployer.mdict['pki_authdb_secure_conn']

        subsystem.save()
コード例 #8
0
    def execute(self, argv):

        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'pkcs12-file=', 'pkcs12-password='******'pkcs12-password-file=', 'verbose', 'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        pkcs12_file = None
        pkcs12_password = None

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

            elif o == '--pkcs12-file':
                pkcs12_file = a

            elif o == '--pkcs12-password':
                pkcs12_password = a.encode()

            elif o == '--pkcs12-password-file':
                with io.open(a, 'rb') as f:
                    pkcs12_password = f.read()

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        if not pkcs12_file:
            logger.error('Missing PKCS #12 file')
            self.print_help()
            sys.exit(1)

        if not pkcs12_password:
            logger.error('Missing PKCS #12 password')
            self.print_help()
            sys.exit(1)

        instance = pki.server.instance.PKIInstance(instance_name)
        if not instance.is_valid():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem('ca')
        if not subsystem:
            logger.error('No CA subsystem in instance %s', instance_name)
            sys.exit(1)

        tmpdir = tempfile.mkdtemp()

        try:
            pkcs12_password_file = os.path.join(tmpdir, 'pkcs12_password.txt')
            with open(pkcs12_password_file, 'wb') as f:
                f.write(pkcs12_password)

            subsystem.export_cert_chain(pkcs12_file, pkcs12_password_file)

        finally:
            shutil.rmtree(tmpdir)
コード例 #9
0
ファイル: selftest.py プロジェクト: tstellar/pki
    def execute(self, argv):

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

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

        # To hold the subsystem names
        subsystems = []
        test = None
        instance_name = 'pki-tomcat'

        if len(args) == 1:
            test = args[0]

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

            elif o == '--subsystem':
                subsystems.append(a)

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

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

        # Load instance
        instance = pki.server.instance.PKIInstance(instance_name)

        if not instance.is_valid():
            print('ERROR: Invalid instance %s.' % instance_name)
            sys.exit(1)

        instance.load()

        # To hold the instance of the loaded subsystems
        target_subsystems = []

        # Load subsystem or subsystems
        if not subsystems:
            for subsys in instance.subsystems:
                target_subsystems.append(subsys)
        else:
            for subsys in subsystems:
                target_subsystems.append(instance.get_subsystem(subsys))

        try:
            # Enable critical tests for all subsystems listed in target_subsystems
            for subsys in target_subsystems:
                subsys.set_startup_test_criticality(test=test, critical=True)
                # Save the updated CS.cfg to disk
                subsys.save()

        except pki.server.PKIServerException as e:
            logging.error(str(e))
            sys.exit(1)
コード例 #10
0
    def execute(self, argv):

        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'cert=', 'cert-file=', 'verbose', 'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        cert = None

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

            elif o == '--cert':
                cert = a

            elif o == '--cert-file':
                with io.open(a, 'rb') as f:
                    cert = f.read()

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIInstance(instance_name)
        if not instance.is_valid():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem('ca')
        if not subsystem:
            logger.error('No CA subsystem in instance %s', instance_name)
            sys.exit(1)

        results = subsystem.find_cert_requests(cert=cert)

        self.print_message('%s entries matched' % len(results))

        first = True
        for request in results:
            if first:
                first = False
            else:
                print()

            CACertRequestCLI.print_request(request)
コード例 #11
0
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(
                argv, 'i:v',
                ['instance=', 'output-file=', 'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        if len(args) != 1:
            logger.error('Missing request ID')
            self.print_help()
            sys.exit(1)

        request_id = args[0]
        instance_name = 'pki-tomcat'
        output_file = None

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

            elif o == '--output-file':
                output_file = a

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIInstance(instance_name)
        if not instance.is_valid():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem('ca')
        if not subsystem:
            logger.error('No CA subsystem in instance %s', instance_name)
            sys.exit(1)

        request = subsystem.get_cert_requests(request_id)

        if output_file:
            with io.open(output_file, 'wb') as f:
                f.write(request['request'])

        else:
            CACertRequestCLI.print_request(request, details=True)
コード例 #12
0
ファイル: subsystem.py プロジェクト: tiran/pki
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            logger.error(e)
            self.usage()
            sys.exit(1)

        instance_name = 'pki-tomcat'

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

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.usage()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing subsystem ID')
            self.usage()
            sys.exit(1)

        subsystem_name = args[0]

        if len(args) >= 2:
            cert_id = args[1]
        else:
            cert_id = None

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

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.', subsystem_name,
                         instance_name)
            sys.exit(1)

        if cert_id is not None:
            certs = [subsystem.get_subsystem_cert(cert_id)]
        else:
            certs = subsystem.find_system_certs()

        first = True
        certs_valid = True

        for cert in certs:

            if first:
                first = False
            else:
                print()

            certs_valid &= self.validate_certificate(instance, cert)

        if certs_valid:
            self.print_message("Validation succeeded")
            sys.exit(0)
        else:
            self.print_message("Validation failed")
            sys.exit(1)
コード例 #13
0
ファイル: subsystem.py プロジェクト: tiran/pki
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            logger.error(e)
            self.usage()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        cert_file = None

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

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            elif o == '--cert':
                cert_file = a

            else:
                logger.error('Unknown option: %s', o)
                self.usage()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing subsystem ID')
            self.usage()
            sys.exit(1)

        if len(args) < 2:
            logger.error('Missing cert ID')
            self.usage()
            sys.exit(1)

        subsystem_name = args[0]
        cert_id = args[1]

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

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.', subsystem_name,
                         instance_name)
            sys.exit(1)
        subsystem_cert = subsystem.get_subsystem_cert(cert_id)

        logger.info('Retrieving certificate %s from %s',
                    subsystem_cert['nickname'], subsystem_cert['token'])

        token = subsystem_cert['token']
        nssdb = instance.open_nssdb(token)

        if cert_file:
            if not os.path.isfile(cert_file):
                logger.error('%s certificate does not exist.', cert_file)
                self.usage()
                sys.exit(1)

            data = nssdb.get_cert(nickname=subsystem_cert['nickname'],
                                  output_format='base64')

            if data:
                logger.info('Removing old %s certificate from database.',
                            subsystem_cert['nickname'])
                nssdb.remove_cert(nickname=subsystem_cert['nickname'])

            logger.info('Adding new %s certificate into database.',
                        subsystem_cert['nickname'])
            nssdb.add_cert(nickname=subsystem_cert['nickname'],
                           cert_file=cert_file)

        # Retrieve the cert info from NSSDB
        # Note: This reloads `data` object if --cert option is provided
        data = nssdb.get_cert(nickname=subsystem_cert['nickname'],
                              output_format='base64')
        subsystem_cert['data'] = data

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

        logger.info('Retrieving certificate request from CA database')

        # TODO: add support for remote CA
        ca = instance.get_subsystem('ca')
        if not ca:
            logger.error('No CA subsystem in instance %s.', instance_name)
            sys.exit(1)

        results = ca.find_cert_requests(cert=data)

        if results:
            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 = ''.join(lines)
            subsystem_cert['request'] = request

        else:
            logger.warning('Certificate request not found')

        # 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)
コード例 #14
0
ファイル: subsystem.py プロジェクト: tiran/pki
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'cert-file=', 'csr-file=', 'pkcs12-file=',
                'pkcs12-password='******'pkcs12-password-file=', 'append',
                'no-trust-flags', 'no-key', 'no-chain', 'verbose', 'debug',
                'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        cert_file = None
        csr_file = None
        pkcs12_file = None
        pkcs12_password = None
        pkcs12_password_file = None
        append = False
        include_trust_flags = True
        include_key = True
        include_chain = True

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

            elif o == '--cert-file':
                cert_file = a

            elif o == '--csr-file':
                csr_file = a

            elif o == '--pkcs12-file':
                pkcs12_file = a

            elif o == '--pkcs12-password':
                pkcs12_password = a

            elif o == '--pkcs12-password-file':
                pkcs12_password_file = a

            elif o == '--append':
                append = True

            elif o == '--no-trust-flags':
                include_trust_flags = False

            elif o == '--no-key':
                include_key = False

            elif o == '--no-chain':
                include_chain = False

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing subsystem ID')
            self.print_help()
            sys.exit(1)

        subsystem_name = args[0]

        if not (cert_file or csr_file or pkcs12_file):
            logger.error('Missing output file')
            self.print_help()
            sys.exit(1)

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

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.', subsystem_name,
                         instance_name)
            sys.exit(1)
        subsystem_cert = None

        if len(args) >= 2:
            cert_id = args[1]
            subsystem_cert = subsystem.get_subsystem_cert(cert_id)

        if (cert_file or csr_file) and not subsystem_cert:
            logger.error('Missing cert ID')
            self.print_help()
            sys.exit(1)

        if cert_file:
            cert_data = subsystem_cert.get('data')
            if cert_data is None:
                logger.error("Unable to find certificate data for %s", cert_id)
                sys.exit(1)

            cert_data = pki.nssdb.convert_cert(cert_data, 'base64', 'pem')
            with open(cert_file, 'w') as f:
                f.write(cert_data)

        if csr_file:
            cert_request = subsystem_cert.get('request')
            if cert_request is None:
                logger.error('Unable to find certificate request for %s',
                             cert_id)
                sys.exit(1)

            csr_data = pki.nssdb.convert_csr(cert_request, 'base64', 'pem')
            with open(csr_file, 'w') as f:
                f.write(csr_data)

        if pkcs12_file:

            if not pkcs12_password and not pkcs12_password_file:
                pkcs12_password = getpass.getpass(
                    prompt='Enter password for PKCS #12 file: ')

            nicknames = []

            if subsystem_cert:
                nicknames.append(subsystem_cert['nickname'])

            else:
                subsystem_certs = subsystem.find_system_certs()
                for subsystem_cert in subsystem_certs:
                    nicknames.append(subsystem_cert['nickname'])

            nssdb = instance.open_nssdb()
            try:
                nssdb.export_pkcs12(pkcs12_file=pkcs12_file,
                                    pkcs12_password=pkcs12_password,
                                    pkcs12_password_file=pkcs12_password_file,
                                    nicknames=nicknames,
                                    append=append,
                                    include_trust_flags=include_trust_flags,
                                    include_key=include_key,
                                    include_chain=include_chain)

            finally:
                nssdb.close()
コード例 #15
0
ファイル: range.py プロジェクト: edewata/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'master=', 'session=', 'install-token=',
                'verbose', 'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        subsystem_name = self.parent.parent.name
        master_url = None
        session_id = None
        install_token = None

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

            elif o == '--master':
                master_url = a

            elif o == '--session':
                session_id = a

            elif o == '--install-token':
                install_token = a

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        if not master_url:
            raise Exception('Missing master URL')

        if not session_id and not install_token:
            raise Exception('Missing session ID or install token')

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        subsystem.request_ranges(master_url,
                                 session_id=session_id,
                                 install_token=install_token)
コード例 #16
0
    def spawn(self, deployer):

        external = deployer.configuration_file.external
        standalone = deployer.configuration_file.standalone
        step_one = deployer.configuration_file.external_step_one
        skip_configuration = deployer.configuration_file.skip_configuration

        if (external or standalone) and step_one or skip_configuration:
            logger.info('Skipping configuration')
            return

        logger.info('Configuring subsystem')

        try:
            PKISPAWN_STARTUP_TIMEOUT_SECONDS = \
                int(os.environ['PKISPAWN_STARTUP_TIMEOUT_SECONDS'])
        except (KeyError, ValueError):
            PKISPAWN_STARTUP_TIMEOUT_SECONDS = 60
        if PKISPAWN_STARTUP_TIMEOUT_SECONDS <= 0:
            PKISPAWN_STARTUP_TIMEOUT_SECONDS = 60

        instance = self.instance
        instance.load()

        subsystem = instance.get_subsystem(
            deployer.mdict['pki_subsystem'].lower())

        # configure internal database
        subsystem.config['internaldb.ldapconn.host'] = deployer.mdict[
            'pki_ds_hostname']

        if config.str2bool(deployer.mdict['pki_ds_secure_connection']):
            subsystem.config['internaldb.ldapconn.secureConn'] = 'true'
            subsystem.config['internaldb.ldapconn.port'] = deployer.mdict[
                'pki_ds_ldaps_port']
        else:
            subsystem.config['internaldb.ldapconn.secureConn'] = 'false'
            subsystem.config['internaldb.ldapconn.port'] = deployer.mdict[
                'pki_ds_ldap_port']

        subsystem.config['internaldb.ldapauth.bindDN'] = deployer.mdict[
            'pki_ds_bind_dn']
        subsystem.config['internaldb.basedn'] = deployer.mdict[
            'pki_ds_base_dn']
        subsystem.config['internaldb.database'] = deployer.mdict[
            'pki_ds_database']

        if config.str2bool(deployer.mdict['pki_share_db']):
            subsystem.config['preop.internaldb.dbuser'] = deployer.mdict[
                'pki_share_dbuser_dn']

        ocsp_uri = deployer.mdict.get('pki_default_ocsp_uri')
        if ocsp_uri:
            subsystem.config['ca.defaultOcspUri'] = ocsp_uri

        if subsystem.name == 'ca':
            serial_number_range_start = deployer.mdict.get(
                'pki_serial_number_range_start')
            if serial_number_range_start:
                subsystem.config[
                    'dbs.beginSerialNumber'] = serial_number_range_start

            serial_number_range_end = deployer.mdict.get(
                'pki_serial_number_range_end')
            if serial_number_range_end:
                subsystem.config[
                    'dbs.endSerialNumber'] = serial_number_range_end

            request_number_range_start = deployer.mdict.get(
                'pki_request_number_range_start')
            if request_number_range_start:
                subsystem.config[
                    'dbs.beginRequestNumber'] = request_number_range_start

            request_number_range_end = deployer.mdict.get(
                'pki_request_number_range_end')
            if request_number_range_end:
                subsystem.config[
                    'dbs.endRequestNumber'] = request_number_range_end

            replica_number_range_start = deployer.mdict.get(
                'pki_replica_number_range_start')
            if replica_number_range_start:
                subsystem.config[
                    'dbs.beginReplicaNumber'] = replica_number_range_start

            replica_number_range_end = deployer.mdict.get(
                'pki_replica_number_range_end')
            if replica_number_range_end:
                subsystem.config[
                    'dbs.endReplicaNumber'] = replica_number_range_end

        if subsystem.name == 'kra':
            if config.str2bool(deployer.mdict['pki_kra_ephemeral_requests']):
                logger.debug('Setting ephemeral requests to true')
                subsystem.config['kra.ephemeralRequests'] = 'true'

        if subsystem.name == 'tps':
            baseDN = subsystem.config['internaldb.basedn']
            dsHost = subsystem.config['internaldb.ldapconn.host']
            dsPort = subsystem.config['internaldb.ldapconn.port']

            subsystem.config[
                'tokendb.activityBaseDN'] = 'ou=Activities,' + baseDN
            subsystem.config['tokendb.baseDN'] = 'ou=Tokens,' + baseDN
            subsystem.config[
                'tokendb.certBaseDN'] = 'ou=Certificates,' + baseDN
            subsystem.config['tokendb.userBaseDN'] = baseDN
            subsystem.config['tokendb.hostport'] = dsHost + ':' + dsPort

        subsystem.save()

        token = pki.nssdb.normalize_token(deployer.mdict['pki_token_name'])
        nssdb = instance.open_nssdb()

        existing = deployer.configuration_file.existing
        step_two = deployer.configuration_file.external_step_two
        clone = deployer.configuration_file.clone
        master_url = deployer.mdict['pki_clone_uri']

        try:
            if existing or (external or standalone) and step_two:

                self.import_system_cert_requests(deployer, subsystem)
                self.import_system_certs(deployer, nssdb, subsystem)

                self.configure_system_certs(deployer, subsystem)
                self.update_system_certs(deployer, nssdb, subsystem)
                subsystem.save()

                self.validate_system_certs(deployer, nssdb, subsystem)

            else:  # self-signed CA

                # To be implemented in ticket #1692.

                # Generate CA cert request.
                # Self sign CA cert.
                # Import self-signed CA cert into NSS database.

                pass

        finally:
            nssdb.close()

        create_temp_sslserver_cert = self.create_temp_sslserver_cert(
            deployer, instance)

        server_config = instance.get_server_config()
        unsecurePort = server_config.get_unsecure_port()
        securePort = server_config.get_secure_port()

        if deployer.mdict['pki_security_domain_type'] == 'existing':

            logger.info('Joining existing domain')

            deployer.join_domain()

            subsystem.config['securitydomain.name'] = deployer.domain_info.id
            subsystem.config['securitydomain.select'] = 'existing'

            # hostname and ports point to security domain
            subsystem.config['securitydomain.host'] = deployer.sd_host.Hostname
            subsystem.config['securitydomain.httpport'] = deployer.sd_host.Port
            subsystem.config[
                'securitydomain.httpseeport'] = deployer.sd_host.SecurePort
            subsystem.config[
                'securitydomain.httpsadminport'] = deployer.sd_host.SecureAdminPort
            subsystem.config[
                'securitydomain.httpsagentport'] = deployer.sd_host.SecureAgentPort

        elif config.str2bool(deployer.mdict['pki_subordinate']) and \
                config.str2bool(deployer.mdict['pki_subordinate_create_new_security_domain']):

            logger.info('Creating new security subdomain')

            deployer.join_domain()

            sd_name = deployer.mdict['pki_subordinate_security_domain_name']
            subsystem.config['securitydomain.name'] = sd_name
            subsystem.config['securitydomain.select'] = 'new'

            # hostname and ports point to current host
            subsystem.config['securitydomain.host'] = deployer.mdict[
                'pki_hostname']
            subsystem.config['securitydomain.httpport'] = unsecurePort
            subsystem.config['securitydomain.httpsagentport'] = securePort
            subsystem.config['securitydomain.httpseeport'] = securePort
            subsystem.config['securitydomain.httpsadminport'] = securePort

        else:

            logger.info('Creating new security domain')

            sd_name = deployer.mdict['pki_security_domain_name']
            subsystem.config['securitydomain.name'] = sd_name
            subsystem.config['securitydomain.select'] = 'new'

            # hostname and ports point to current host
            subsystem.config['securitydomain.host'] = deployer.mdict[
                'pki_hostname']
            subsystem.config['securitydomain.httpport'] = unsecurePort
            subsystem.config['securitydomain.httpsagentport'] = securePort
            subsystem.config['securitydomain.httpseeport'] = securePort
            subsystem.config['securitydomain.httpsadminport'] = securePort

        subsystem.config['service.securityDomainPort'] = securePort

        hierarchy = subsystem.config.get('hierarchy.select')
        issuing_ca = deployer.mdict['pki_issuing_ca']

        if not (subsystem.type == 'CA' and hierarchy == 'Root'):

            if not external and not standalone:

                logger.info('Using CA at %s', issuing_ca)

                url = urllib.parse.urlparse(issuing_ca)

                subsystem.config['preop.ca.url'] = issuing_ca
                subsystem.config['preop.ca.hostname'] = url.hostname
                subsystem.config['preop.ca.httpsport'] = str(url.port)
                subsystem.config['preop.ca.httpsadminport'] = str(url.port)

        system_certs_imported = \
            deployer.mdict['pki_server_pkcs12_path'] != '' or \
            deployer.mdict['pki_clone_pkcs12_path'] != ''

        if not (subsystem.type == 'CA' and hierarchy == 'Root'):

            if external or standalone:
                subsystem.config['preop.ca.pkcs7'] = ''

            elif not clone and not system_certs_imported:

                logger.info('Retrieving CA certificate chain from %s',
                            issuing_ca)

                pem_chain = self.get_cert_chain(instance, issuing_ca)
                base64_chain = pki.nssdb.convert_pkcs7(pem_chain, 'pem',
                                                       'base64')
                subsystem.config['preop.ca.pkcs7'] = base64_chain

                logger.info('Importing CA certificate chain')

                nssdb = instance.open_nssdb()
                try:
                    nssdb.import_pkcs7(pkcs7_data=pem_chain,
                                       trust_attributes='CT,C,C')
                finally:
                    nssdb.close()

        if subsystem.type == 'CA' and clone and not system_certs_imported:

            logger.info('Retrieving CA certificate chain from %s', master_url)

            pem_chain = self.get_cert_chain(instance, master_url)
            base64_chain = pki.nssdb.convert_pkcs7(pem_chain, 'pem', 'base64')
            subsystem.config['preop.clone.pkcs7'] = base64_chain

            logger.info('Importing CA certificate chain')

            nssdb = instance.open_nssdb()
            try:
                nssdb.import_pkcs7(pkcs7_data=pem_chain,
                                   trust_attributes='CT,C,C')
            finally:
                nssdb.close()

        subsystem.save()

        if config.str2bool(deployer.mdict['pki_ds_remove_data']):

            if config.str2bool(deployer.mdict['pki_ds_create_new_db']):
                logger.info('Removing existing database')
                subsystem.remove_database(force=True)

            elif not config.str2bool(deployer.mdict['pki_clone']) or \
                    config.str2bool(deployer.mdict['pki_clone_setup_replication']):
                logger.info('Emptying existing database')
                subsystem.empty_database(force=True)

            else:
                logger.info('Reusing replicated database')

        logger.info('Initializing database')

        # In most cases, we want to replicate the schema and therefore not add it here.
        # We provide this option though in case the clone already has schema
        # and we want to replicate back to the master.

        # On the other hand, if we are not setting up replication,
        # then we are assuming that replication is already taken care of,
        # and schema has already been replicated.

        setup_schema = not config.str2bool(deployer.mdict['pki_clone']) or \
            not config.str2bool(deployer.mdict['pki_clone_setup_replication']) or \
            not config.str2bool(deployer.mdict['pki_clone_replicate_schema'])

        create_database = config.str2bool(
            deployer.mdict['pki_ds_create_new_db'])

        # When cloning a subsystem without setting up the replication agreements,
        # the database is a subtree of an existing tree and is already replicated,
        # so there is no need to set up the base entry.

        create_base = config.str2bool(deployer.mdict['pki_ds_create_new_db']) or \
            not config.str2bool(deployer.mdict['pki_clone']) or \
            config.str2bool(deployer.mdict['pki_clone_setup_replication'])

        create_containers = not config.str2bool(deployer.mdict['pki_clone'])

        # If the database is already replicated but not yet indexed, rebuild the indexes.

        rebuild_indexes = config.str2bool(deployer.mdict['pki_clone']) and \
            not config.str2bool(deployer.mdict['pki_clone_setup_replication']) and \
            config.str2bool(deployer.mdict['pki_clone_reindex_data'])

        setup_db_manager = not config.str2bool(deployer.mdict['pki_clone']) or \
            not config.str2bool(deployer.mdict['pki_clone_setup_replication'])

        # If setting up replication, set up VLV indexes after replication.

        setup_vlv_indexes = not config.str2bool(deployer.mdict['pki_clone']) or \
            not config.str2bool(deployer.mdict['pki_clone_setup_replication'])

        subsystem.init_database(setup_schema=setup_schema,
                                create_database=create_database,
                                create_base=create_base,
                                create_containers=create_containers,
                                rebuild_indexes=rebuild_indexes,
                                setup_db_manager=setup_db_manager,
                                setup_vlv_indexes=setup_vlv_indexes)

        if clone:

            if subsystem.type in ['CA', 'KRA']:

                logger.info('Updating ranges for %s clone', subsystem.type)
                subsystem.update_ranges(master_url, deployer.install_token)

            logger.info('Updating configuration for %s clone', subsystem.type)
            subsystem.update_config(master_url, deployer.install_token)

        # Start/Restart this Tomcat PKI Process
        # Optionally prepare to enable a java debugger
        # (e. g. - 'eclipse'):
        if config.str2bool(deployer.mdict['pki_enable_java_debugger']):
            config.prepare_for_an_external_java_debugger(
                deployer.mdict['pki_target_tomcat_conf_instance_id'])
        tomcat_instance_subsystems = \
            len(deployer.instance.tomcat_instance_subsystems())

        if tomcat_instance_subsystems == 1:
            logger.info('Starting server')
            instance.start()

        elif tomcat_instance_subsystems > 1:
            logger.info('Restarting server')
            instance.restart()

        # Configure status request timeout.  This is used for each
        # status request in wait_for_startup
        value = deployer.mdict['pki_status_request_timeout']
        if len(value) == 0:
            status_request_timeout = None
        else:
            status_request_timeout = int(value)
            if status_request_timeout <= 0:
                raise ValueError("timeout must be greater than zero")

        deployer.instance.wait_for_startup(
            subsystem,
            PKISPAWN_STARTUP_TIMEOUT_SECONDS,
            request_timeout=status_request_timeout,
        )

        # Optionally wait for debugger to attach (e. g. - 'eclipse'):
        if config.str2bool(deployer.mdict['pki_enable_java_debugger']):
            config.wait_to_attach_an_external_java_debugger()

        ca_cert = os.path.join(instance.nssdb_dir, "ca.crt")

        connection = pki.client.PKIConnection(
            protocol='https',
            hostname=deployer.mdict['pki_hostname'],
            port=deployer.mdict['pki_https_port'],
            trust_env=False,
            cert_paths=ca_cert)

        client = pki.system.SystemConfigClient(
            connection, subsystem=deployer.mdict['pki_subsystem_type'])

        # If pki_one_time_pin is not already defined, load from CS.cfg
        if 'pki_one_time_pin' not in deployer.mdict:
            deployer.mdict['pki_one_time_pin'] = subsystem.config['preop.pin']

        logger.info('Configuring %s subsystem', subsystem.type)

        if clone:

            logger.info('Setting up clone')

            clone_setup_request = deployer.config_client.create_clone_setup_request(
                subsystem)
            clone_setup_request.domainInfo = deployer.domain_info
            clone_setup_request.installToken = deployer.install_token
            client.setupClone(clone_setup_request)

        logger.info('Setting up database')

        database_setup_request = deployer.config_client.create_database_setup_request(
        )
        client.setupDatabase(database_setup_request)

        sslserver = subsystem.get_subsystem_cert('sslserver')

        for tag in subsystem.config['preop.cert.list'].split(','):

            logger.info('Setting up %s certificate', tag)
            cert = deployer.setup_cert(client, tag)

            if not cert:
                continue

            logger.debug('- cert: %s', cert['cert'])
            logger.debug('- request: %s', cert['request'])

            if tag == 'sslserver':
                sslserver['data'] = cert['cert']
                sslserver['request'] = cert['request']
                sslserver['token'] = cert['token']

        if not clone:

            logger.info('Setting up admin user')
            deployer.setup_admin(client)

        if config.str2bool(deployer.mdict['pki_backup_keys']):

            # by default store the backup file in the NSS databases directory
            if not deployer.mdict['pki_backup_file']:
                deployer.mdict['pki_backup_file'] = \
                    deployer.mdict['pki_server_database_path'] + '/' + \
                    deployer.mdict['pki_subsystem'].lower() + '_backup_keys.p12'

            logger.info('Backing up keys into %s',
                        deployer.mdict['pki_backup_file'])
            deployer.backup_keys(instance, subsystem)

        logger.info('Setting up security domain')
        sd_setup_request = deployer.config_client.create_security_domain_setup_request(
        )
        sd_setup_request.domainInfo = deployer.domain_info
        sd_setup_request.installToken = deployer.install_token
        client.setupSecurityDomain(sd_setup_request)

        if not config.str2bool(deployer.mdict['pki_share_db']):
            logger.info('Setting up database user')
            db_user_setup_request = deployer.config_client.create_database_user_setup_request(
            )
            client.setupDatabaseUser(db_user_setup_request)

        logger.info('Finalizing %s configuration', subsystem.type)
        finalize_config_request = deployer.config_client.create_finalize_config_request(
        )
        finalize_config_request.domainInfo = deployer.domain_info
        finalize_config_request.installToken = deployer.install_token
        client.finalizeConfiguration(finalize_config_request)

        if subsystem.type == 'TPS':
            logger.info('Setting up shared secret')
            deployer.setup_shared_secret(instance, subsystem)

        logger.info('%s configuration complete', subsystem.type)

        # Create an empty file that designates the fact that although
        # this server instance has been configured, it has NOT yet
        # been restarted!

        restart_server = os.path.join(instance.conf_dir,
                                      'restart_server_after_configuration')
        logger.debug('Creating %s', restart_server)

        open(restart_server, 'a').close()
        os.chown(restart_server, instance.uid, instance.gid)
        os.chmod(restart_server, 0o660)

        # If temp SSL server cert was created and there's a new perm cert,
        # replace it with the perm cert.
        if create_temp_sslserver_cert and sslserver and sslserver['data']:
            logger.info('Stopping server')
            instance.stop()

            # Remove temp SSL server cert.
            self.remove_temp_sslserver_cert(instance, sslserver)

            # Import perm SSL server cert unless it's already imported
            # earlier in external/standalone installation.

            if not (standalone
                    or external and subsystem.name in ['kra', 'ocsp']):

                nickname = sslserver['nickname']
                token = pki.nssdb.normalize_token(sslserver['token'])

                if not token:
                    token = deployer.mdict['pki_token_name']

                instance.set_sslserver_cert_nickname(nickname, token)

                self.import_perm_sslserver_cert(deployer, instance, sslserver)

            logger.info('Starting server')
            instance.start()

        elif config.str2bool(
                deployer.mdict['pki_restart_configured_instance']):
            logger.info('Restarting server')
            instance.restart()

        deployer.instance.wait_for_startup(
            subsystem,
            PKISPAWN_STARTUP_TIMEOUT_SECONDS,
            request_timeout=status_request_timeout,
        )
コード例 #17
0
ファイル: range.py プロジェクト: edewata/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(
                argv, 'i:v', ['instance=', 'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        subsystem_name = self.parent.parent.name

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

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        print('  Begin request ID: %s' %
              subsystem.config.get('dbs.beginRequestNumber'))
        print('  End request ID: %s' %
              subsystem.config.get('dbs.endRequestNumber'))

        print('  Begin serial number: %s' %
              subsystem.config.get('dbs.beginSerialNumber'))
        print('  End serial number: %s' %
              subsystem.config.get('dbs.endSerialNumber'))

        print('  Begin replica ID: %s' %
              subsystem.config.get('dbs.beginReplicaNumber'))
        print('  End replica ID: %s' %
              subsystem.config.get('dbs.endReplicaNumber'))

        print('  Enable serial management: %s' %
              subsystem.config.get('dbs.enableSerialManagement'))
コード例 #18
0
ファイル: audit.py プロジェクト: dogtagpki/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'enabled=', 'logFile=', 'bufferSize=',
                'flushInterval=', 'maxFileSize=', 'rolloverInterval=',
                'expirationTime=', 'logSigning=', 'signingCert=', 'verbose',
                'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        enabled = None
        logFile = None
        bufferSize = None
        flushInterval = None
        maxFileSize = None
        rolloverInterval = None
        expirationTime = None
        logSigning = None
        signingCert = None

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

            elif o == '--enabled':
                if a.lower().title() not in ['True', 'False']:
                    raise ValueError(
                        "Invalid input: Enabled must be True or False")
                enabled = a.lower() == 'true'

            elif o == '--logFile':
                logFile = a

            elif o == '--bufferSize':
                if not a.isdigit():
                    raise ValueError(
                        "Invalid input: Buffer size must be a number")
                bufferSize = a

            elif o == '--flushInterval':
                if not a.isdigit():
                    raise ValueError(
                        "Invalid input: Flush interval must be a number")
                flushInterval = a

            elif o == '--maxFileSize':
                if not a.isdigit():
                    raise ValueError(
                        "Invalid input: Max file size must be a number")
                maxFileSize = a

            elif o == '--rolloverInterval':
                if not a.isdigit():
                    raise ValueError(
                        "Invalid input: Rollover interval must be a number")
                rolloverInterval = a

            elif o == '--expirationTime':
                if not a.isdigit():
                    raise ValueError(
                        "Invalid input: Expiration time must be a number")
                expirationTime = a

            elif o == '--logSigning':
                if a.lower().title() not in ['True', 'False']:
                    raise ValueError(
                        "Invalid input: Log signing must be True or False")
                logSigning = a.lower() == 'true'

            elif o == '--signingCert':
                signingCert = a

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name = self.parent.parent.name
        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s.',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        name = 'log.instance.SignedAudit.%s'

        if enabled is None:
            pass
        elif enabled:
            subsystem.config[name % 'enable'] = 'true'
        else:
            subsystem.config[name % 'enable'] = 'false'

        if logFile:
            subsystem.config[name % 'fileName'] = logFile

        if bufferSize:
            subsystem.config[name % 'bufferSize'] = bufferSize

        if flushInterval:
            subsystem.config[name % 'flushInterval'] = flushInterval

        if maxFileSize:
            subsystem.config[name % 'maxFileSize'] = maxFileSize

        if rolloverInterval:
            subsystem.config[name % 'rolloverInterval'] = rolloverInterval

        if expirationTime:
            subsystem.config[name % 'expirationTime'] = expirationTime

        if logSigning is None:
            pass
        elif logSigning:
            subsystem.config[name % 'logSigning'] = 'true'
        else:
            subsystem.config[name % 'logSigning'] = 'false'

        if signingCert:
            subsystem.config[name % 'signedAuditCertNickname'] = signingCert

        subsystem.save()

        AuditCLI.print_audit_config(subsystem)
コード例 #19
0
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:D:w:x:g:v', [
                'instance=', 'bind-dn=', 'bind-password='******'generate-ldif=',
                'verbose', 'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        bind_dn = 'cn=Directory Manager'
        bind_password = None

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

            elif o in ('-D', '--bind-dn'):
                bind_dn = a

            elif o in ('-w', '--bind-password'):
                bind_password = a

            elif o in ('-g', '--generate-ldif'):
                self.out_file = a

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIInstance(instance_name)
        if not instance.is_valid():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)
        instance.load()

        subsystem = instance.get_subsystem('kra')
        if not subsystem:
            logger.error('No KRA subsystem in instance %s.', instance_name)
            sys.exit(1)

        if self.out_file:
            subsystem.customize_file(KRA_VLV_TASKS_PATH, self.out_file)
            print('KRA VLV reindex task written to ' + self.out_file)
            return

        self.reindex_vlv(subsystem, bind_dn, bind_password)

        print('KRA VLV reindex completed for ' + instance_name)
コード例 #20
0
ファイル: audit.py プロジェクト: dogtagpki/pki
    def execute(self, argv):

        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'enabled=', 'enabledByDefault=', 'verbose',
                'debug', 'help'
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        enabled = None
        enabled_by_default = None

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

            elif o == '--enabled':
                enabled = a == 'True'

            elif o == '--enabledByDefault':
                enabled_by_default = a == 'True'

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name = self.parent.parent.name
        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        events = subsystem.find_audit_event_configs(enabled,
                                                    enabled_by_default)

        self.print_message('%s entries matched' % len(events))

        first = True
        for event in events:
            if first:
                first = False
            else:
                print()

            print('  Event Name: %s' % event.get('name'))
            print('  Enabled: %s' % event.get('enabled'))
            print('  Filter: %s' % event.get('filter'))
コード例 #21
0
    def execute(self, argv):
        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=',
                'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        subsystem_name = self.parent.parent.name

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

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing user ID')
            self.print_help()
            sys.exit(1)

        user_id = args[0]

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        user = subsystem.get_user(user_id)

        print('  User ID: {}'.format(user['id']))

        full_name = user.get('fullName')
        if full_name:
            print('  Full Name: {}'.format(full_name))

        email = user.get('email')
        if email:
            print('  Email: {} '.format(email))

        phone = user.get('phone')
        if phone:
            print('  Phone: {} '.format(phone))

        user_type = user.get('type')
        if user_type:
            print('  Type: {} '.format(user_type))

        state = user.get('state')
        if state:
            print('  State: {} '.format(state))
コード例 #22
0
ファイル: audit.py プロジェクト: dogtagpki/pki
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        event_filter = None

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

            elif o in ('-f', '--filter'):
                event_filter = a

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) == 0:
            raise getopt.GetoptError("Missing event name.")
        if len(args) > 1:
            raise getopt.GetoptError("Too many arguments specified.")

        event_name = args[0]

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name = self.parent.parent.name
        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        subsystem.update_audit_event_filter(event_name, event_filter)
        subsystem.save()

        event = subsystem.get_audit_event_config(event_name)
        AuditCLI.print_audit_event_config(event)
コード例 #23
0
    def execute(self, argv):
        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'full-name=', 'email=',
                'password='******'password-file=',
                'phone=', 'type=', 'state=', 'tps-profiles=',
                'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        subsystem_name = self.parent.parent.name
        full_name = None
        email = None
        password = None
        password_file = None
        phone = None
        user_type = None
        state = None
        tps_profiles = None

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

            elif o == '--full-name':
                full_name = a

            elif o == '--email':
                email = a

            elif o == '--password':
                password = a

            elif o == '--password-file':
                password_file = a

            elif o == '--phone':
                phone = a

            elif o == '--type':
                user_type = a

            elif o == '--state':
                state = a

            elif o == '--tps-profiles':
                tps_profiles = [x.strip() for x in a.split(',')]

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

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

            else:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing user ID')
            self.print_help()
            sys.exit(1)

        user_id = args[0]

        if not full_name:
            logger.error('Missing full name')
            self.print_help()
            sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance: %s', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error('No %s subsystem in instance %s',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        subsystem.add_user(
            user_id,
            full_name=full_name,
            email=email,
            password=password,
            password_file=password_file,
            phone=phone,
            user_type=user_type,
            tps_profiles=tps_profiles,
            state=state)
コード例 #24
0
ファイル: audit.py プロジェクト: dogtagpki/pki
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'

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

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) == 0:
            raise getopt.GetoptError("Missing event name.")
        if len(args) > 1:
            raise getopt.GetoptError("Too many arguments specified.")

        event_name = args[0]

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name = self.parent.parent.name
        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        disable = subsystem.disable_audit_event(event_name)
        subsystem.save()

        msg = None
        if disable:
            msg = 'Audit event "{}" disabled. You may need to restart the ' \
                  'instance.'.format(event_name)
        else:
            msg = 'Audit event "{}" already disabled.'.format(event_name)

        print(len(msg) * '-')
        print(msg)
        print(len(msg) * '-')

        event = subsystem.get_audit_event_config(event_name)
        AuditCLI.print_audit_event_config(event)
コード例 #25
0
ファイル: tks.py プロジェクト: siltecon/pki
    def execute(self, argv):

        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'pkcs12-file=', 'pkcs12-password='******'pkcs12-password-file=', 'no-key', 'verbose', 'debug', 'help'
            ])

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

        instance_name = 'pki-tomcat'
        pkcs12_file = None
        pkcs12_password = None
        no_key = False

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

            elif o == '--pkcs12-file':
                pkcs12_file = a

            elif o == '--pkcs12-password':
                pkcs12_password = a.encode()

            elif o == '--pkcs12-password-file':
                with io.open(a, 'rb') as f:
                    pkcs12_password = f.read()

            elif o == '--no-key':
                no_key = True

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        if not pkcs12_file:
            logger.error('Missing PKCS #12 file')
            self.print_help()
            sys.exit(1)

        if not pkcs12_password:
            logger.error('Missing PKCS #12 password')
            self.print_help()
            sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem('tks')
        if not subsystem:
            logger.error('No TKS subsystem in instance %s.', instance_name)
            sys.exit(1)

        tmpdir = tempfile.mkdtemp()

        try:
            pkcs12_password_file = os.path.join(tmpdir, 'pkcs12_password.txt')
            with open(pkcs12_password_file, 'wb') as f:
                f.write(pkcs12_password)

            subsystem.export_system_cert('subsystem',
                                         pkcs12_file,
                                         pkcs12_password_file,
                                         no_key=no_key)
            subsystem.export_system_cert('audit_signing',
                                         pkcs12_file,
                                         pkcs12_password_file,
                                         no_key=no_key,
                                         append=True)
            instance.export_external_certs(pkcs12_file,
                                           pkcs12_password_file,
                                           append=True)

        finally:
            shutil.rmtree(tmpdir)
コード例 #26
0
ファイル: audit.py プロジェクト: dogtagpki/pki
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'

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

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)
        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name = self.parent.parent.name
        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.',
                         subsystem_name.upper(), instance_name)
            sys.exit(1)

        log_dir = subsystem.get_audit_log_dir()
        log_files = subsystem.get_audit_log_files()
        signing_cert = subsystem.get_subsystem_cert('audit_signing')

        tmpdir = tempfile.mkdtemp()

        try:
            file_list = os.path.join(tmpdir, 'audit.txt')

            with open(file_list, 'w', encoding='utf-8') as f:
                for filename in log_files:
                    f.write(os.path.join(log_dir, filename) + '\n')

            cmd = ['AuditVerify']

            if logger.isEnabledFor(logging.INFO):
                cmd.append('-v')

            cmd.extend([
                '-d', instance.nssdb_dir, '-n', signing_cert['nickname'], '-a',
                file_list
            ])

            if logger.isEnabledFor(logging.INFO):
                print('Command: %s' % ' '.join(cmd))

            subprocess.call(cmd)

        finally:
            shutil.rmtree(tmpdir)
コード例 #27
0
ファイル: cert.py プロジェクト: edewata/pki
    def execute(self, argv):
        logging.getLogger().setLevel(logging.INFO)

        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:p:v', [
                'instance=', 'cert=', 'extra-cert=', 'agent-uid=',
                'ldapi-socket=', 'ldap-url=', 'port=', 'verbose', 'debug', 'help',
            ])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        all_certs = True
        fix_certs = []
        extra_certs = []
        agent_uid = None
        ldap_url = None
        use_ldapi = False
        port = '8443'

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

            elif o == '--cert':
                all_certs = False
                fix_certs.append(a)

            elif o == '--extra-cert':
                try:
                    int(a)
                except ValueError:
                    logger.error('--extra-cert requires serial number as integer')
                    sys.exit(1)
                all_certs = False
                extra_certs.append(a)

            elif o == '--agent-uid':
                agent_uid = a

            elif o == '--ldapi-socket':
                if ldap_url is not None:
                    logger.error('--ldapi-socket cannot be used with --ldap-url')
                    sys.exit(1)
                use_ldapi = True
                ldap_url = 'ldapi://{}'.format(quote(a, safe=''))

            elif o == '--ldap-url':
                if use_ldapi:
                    logger.error('--ldap-url cannot be used with --ldapi-socket')
                    sys.exit(1)
                ldap_url = a

            elif o in ('-p', '--port'):
                port = a
                try:
                    n = int(port)
                    if n < 1 or n > 65535:
                        raise ValueError
                except ValueError:
                    logger.error('-p, --port requires a valid port number as integer')
                    sys.exit(1)

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('option %s not recognized', o)
                self.print_help()
                sys.exit(1)

        instance = pki.server.instance.PKIServerFactory.create(instance_name)

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        if not agent_uid:
            logger.error('Must specify --agent-uid')
            sys.exit(1)

        if agent_uid == "pkidbuser":
            logger.error('\'pkidbuser\' cannot be used.')
            sys.exit(1)

        instance.load()

        # 1. Make a list of certs to fix OR use the list provided through CLI options
        if all_certs:
            # TODO: Identify only certs that are EXPIRED or ALMOST EXPIRED
            for subsystem in instance.get_subsystems():
                # Retrieve the subsystem's system certificate
                certs = subsystem.find_system_certs()

                # Iterate on all subsystem's system certificate to prepend
                # subsystem name to the ID
                for cert in certs:
                    if cert['id'] != 'sslserver' and cert['id'] != 'subsystem':
                        cert['id'] = subsystem.name + '_' + cert['id']

                    # Append only unique certificates to other subsystem certificate list
                    # ca_signing isn't supported yet
                    if cert['id'] in fix_certs or cert['id'] == 'ca_signing':
                        continue

                    fix_certs.append(cert['id'])

        logger.info('Fixing the following system certs: %s', fix_certs)
        logger.info('Renewing the following additional certs: %s', extra_certs)

        # Get the CA subsystem and find out Base DN.
        ca_subsystem = instance.get_subsystem('ca')
        basedn = ca_subsystem.get_db_config()['internaldb.basedn']
        dbuser_dn = 'uid=pkidbuser,ou=people,{}'.format(basedn)
        agent_dn = 'uid={},ou=people,{}'.format(agent_uid, basedn)

        dm_pass = ''
        if not use_ldapi:
            # Prompt for DM password
            dm_pass = getpass.getpass(prompt='Enter Directory Manager password: '******'s up
        logger.info('Stopping the instance to proceed with system cert renewal')
        instance.stop()

        # 3. Find the subsystem and disable Self-tests
        try:
            # Placeholder used to hold subsystems whose selftest have been turned off
            # Note: This is initialized as a set to avoid duplicates
            # Example of duplicates:
            # fix_certs = [ca_ocsp_signing, ca_audit_signing] -> will add 'ca' entry twice
            target_subsys = set()

            if 'sslserver' in fix_certs or 'subsystem' in fix_certs:
                # If the cert is either sslserver/subsystem, disable selftest for all
                # subsystems since all subsystems use these 2 certs.
                target_subsys = set(instance.get_subsystems())

            else:
                for cert_id in fix_certs:
                    # Since we already filtered sslserver/subsystem, we can be quite sure
                    # that this split will definitely be of form: <subsys>_<cert_tag>
                    subsystem_name = cert_id.split('_', 1)[0]
                    subsystem = instance.get_subsystem(subsystem_name)

                    # If the subsystem is wrong, stop the process
                    if not subsystem:
                        logger.error('No %s subsystem in instance %s.',
                                     subsystem_name, instance_name)
                        sys.exit(1)

                    target_subsys.add(subsystem)

            if len(extra_certs) > 0:
                target_subsys.add(ca_subsystem)

            # Generate new password for agent account
            agent_pass = gen_random_password()

            with write_temp_file(agent_pass.encode('utf8')) as agent_pass_file, \
                    write_temp_file(dm_pass.encode('utf8')) as dm_pass_file, \
                    ldap_password_authn(
                        instance, target_subsys, dbuser_dn,
                        ldap_url, use_ldapi, dm_pass_file), \
                    suppress_selftest(target_subsys):

                # Verify LDAP connection and DM password
                cmd = ['ldapsearch'] + \
                    ldap_conn_args(ldap_url, use_ldapi, dm_pass_file) + \
                    ['-s', 'base', '-b', basedn, '1.1']
                try:
                    subprocess.check_output(cmd)
                except subprocess.CalledProcessError:
                    logger.error("Failed to connect/authenticate to LDAP at '%s'", ldap_url)
                    sys.exit(1)

                # Reset agent password
                logger.info('Resetting password for %s', agent_dn)
                ldappasswd(ldap_url, use_ldapi, dm_pass_file, agent_dn, agent_pass_file)

                # 4. Bring up the server using a temp SSL cert if the sslcert is expired
                if 'sslserver' in fix_certs:
                    # 4a. Create temp SSL cert
                    logger.info('Creating a temporary sslserver cert')
                    instance.cert_create(cert_id='sslserver', temp_cert=True)

                    # 4b. Delete the existing SSL Cert
                    logger.debug('Removing sslserver cert from instance')
                    instance.cert_del('sslserver')

                    # 4d. Import the temp sslcert into the instance
                    logger.debug('Importing temp sslserver cert')
                    instance.cert_import('sslserver')

                with start_stop(instance):
                    # Place renewal request for all certs in fix_certs
                    for cert_id in fix_certs:
                        logger.info('Requesting new cert for %s', cert_id)
                        instance.cert_create(
                            cert_id=cert_id, renew=True, username=agent_uid,
                            password=agent_pass, secure_port=port,
                            client_nssdb=instance.nssdb_dir)
                    for serial in extra_certs:
                        output = instance.cert_file('{}-renewed'.format(serial))
                        logger.info(
                            'Requesting new cert for %s; writing to %s',
                            serial, output)
                        try:
                            instance.cert_create(
                                serial=serial, renew=True, output=output, username=agent_uid,
                                password=agent_pass, secure_port=port,
                                client_nssdb=instance.nssdb_dir)
                        except pki.PKIException as e:
                            logger.error("Failed to renew certificate %s: %s", serial, e)

                # 8. Delete existing certs and then import the renewed system cert(s)
                for cert_id in fix_certs:
                    # Delete the existing cert from the instance
                    logger.debug('Removing old %s cert from instance %s', cert_id, instance_name)
                    instance.cert_del(cert_id)

                    # Import this new cert into the instance
                    logger.debug('Importing new %s cert into instance %s', cert_id, instance_name)
                    instance.cert_import(cert_id)

                # If subsystem cert was renewed and server was using
                # TLS auth, add the cert to pkidbuser entry
                if dbuser_dn and 'subsystem' in fix_certs:
                    logger.info('Importing new subsystem cert into %s', dbuser_dn)
                    with NamedTemporaryFile(mode='w+b') as der_file:
                        # convert subsystem cert to DER
                        subprocess.check_call([
                            'openssl', 'x509',
                            '-inform', 'PEM', '-outform', 'DER',
                            '-in', instance.cert_file('subsystem'),
                            '-out', der_file.name,
                        ])

                        with write_temp_file(
                            self.PKIDBUSER_LDIF_TEMPLATE
                                .format(dn=dbuser_dn, der_file=der_file.name)
                                .encode('utf-8')
                        ) as ldif_file:
                            # ldapmodify
                            cmd = ['ldapmodify'] + \
                                ldap_conn_args(ldap_url, use_ldapi, dm_pass_file) + \
                                ['-f', ldif_file]
                            subprocess.check_call(cmd)

            # 10. Bring up the server
            logger.info('Starting the instance with renewed certs')
            instance.start()

        except pki.server.PKIServerException as e:
            logger.error(str(e))
            sys.exit(1)
コード例 #28
0
ファイル: security_databases.py プロジェクト: tstellar/pki
    def spawn(self, deployer):

        if config.str2bool(deployer.mdict['pki_skip_installation']):
            logger.info('Skipping NSS database creation')
            return

        logger.info('Creating NSS database')

        instance = pki.server.instance.PKIInstance(
            deployer.mdict['pki_instance_name'])
        instance.load()

        subsystem = instance.get_subsystem(
            deployer.mdict['pki_subsystem'].lower())

        if config.str2bool(deployer.mdict['pki_hsm_enable']):
            hsm_token = deployer.mdict['pki_token_name']
            subsystem.config['preop.module.token'] = hsm_token

        # Since 'certutil' does NOT strip the 'token=' portion of
        # the 'token=password' entries, create a temporary server 'pfile'
        # which ONLY contains the 'password' for the purposes of
        # allowing 'certutil' to generate the security databases

        logger.info('Creating password file: %s',
                    deployer.mdict['pki_shared_pfile'])
        deployer.password.create_password_conf(
            deployer.mdict['pki_shared_pfile'],
            deployer.mdict['pki_server_database_password'],
            pin_sans_token=True)
        deployer.file.modify(deployer.mdict['pki_shared_password_conf'])

        if not os.path.isdir(deployer.mdict['pki_server_database_path']):
            instance.makedirs(deployer.mdict['pki_server_database_path'],
                              force=True)

        nssdb = pki.nssdb.NSSDatabase(
            directory=deployer.mdict['pki_server_database_path'],
            password_file=deployer.mdict['pki_shared_pfile'])

        try:
            if not nssdb.exists():
                nssdb.create()
        finally:
            nssdb.close()

        if not os.path.islink(deployer.mdict['pki_instance_database_link']):
            instance.symlink(deployer.mdict['pki_server_database_path'],
                             deployer.mdict['pki_instance_database_link'],
                             force=True)

        instance.symlink(deployer.mdict['pki_instance_database_link'],
                         deployer.mdict['pki_subsystem_database_link'],
                         force=True)

        if config.str2bool(deployer.mdict['pki_hsm_enable']) and \
                not nssdb.module_exists(deployer.mdict['pki_hsm_modulename']):
            nssdb.add_module(deployer.mdict['pki_hsm_modulename'],
                             deployer.mdict['pki_hsm_libfile'])

        pki.util.chown(deployer.mdict['pki_server_database_path'],
                       deployer.mdict['pki_uid'], deployer.mdict['pki_uid'])
        pki.util.chmod(
            deployer.mdict['pki_server_database_path'],
            config.PKI_DEPLOYMENT_DEFAULT_SECURITY_DATABASE_PERMISSIONS)
        os.chmod(deployer.mdict['pki_server_database_path'],
                 config.PKI_DEPLOYMENT_DEFAULT_DIR_PERMISSIONS)

        # import system certificates before starting the server

        pki_server_pkcs12_path = deployer.mdict['pki_server_pkcs12_path']
        if pki_server_pkcs12_path:

            pki_server_pkcs12_password = deployer.mdict[
                'pki_server_pkcs12_password']
            if not pki_server_pkcs12_password:
                raise Exception('Missing pki_server_pkcs12_password property.')

            nssdb = pki.nssdb.NSSDatabase(
                directory=deployer.mdict['pki_server_database_path'],
                password_file=deployer.mdict['pki_shared_pfile'])

            try:
                nssdb.import_pkcs12(pkcs12_file=pki_server_pkcs12_path,
                                    pkcs12_password=pki_server_pkcs12_password)
            finally:
                nssdb.close()

            # update external CA file (if needed)
            external_certs_path = deployer.mdict[
                'pki_server_external_certs_path']
            if external_certs_path is not None:
                self.update_external_certs_conf(external_certs_path, deployer)

        # import CA certificates from PKCS #12 file for cloning
        pki_clone_pkcs12_path = deployer.mdict['pki_clone_pkcs12_path']

        if pki_clone_pkcs12_path:

            pki_clone_pkcs12_password = deployer.mdict[
                'pki_clone_pkcs12_password']
            if not pki_clone_pkcs12_password:
                raise Exception('Missing pki_clone_pkcs12_password property.')

            nssdb = pki.nssdb.NSSDatabase(
                directory=deployer.mdict['pki_server_database_path'],
                password_file=deployer.mdict['pki_shared_pfile'])

            try:
                print('Importing certificates from %s:' %
                      pki_clone_pkcs12_path)

                # The PKCS12 class requires an NSS database to run. For simplicity
                # it uses the NSS database that has just been created.
                pkcs12 = pki.pkcs12.PKCS12(path=pki_clone_pkcs12_path,
                                           password=pki_clone_pkcs12_password,
                                           nssdb=nssdb)

                try:
                    pkcs12.show_certs()
                finally:
                    pkcs12.close()

                # Import certificates
                nssdb.import_pkcs12(pkcs12_file=pki_clone_pkcs12_path,
                                    pkcs12_password=pki_clone_pkcs12_password)

                # Set certificate trust flags
                if subsystem.type == 'CA':
                    nssdb.modify_cert(
                        nickname=deployer.mdict['pki_ca_signing_nickname'],
                        trust_attributes='CTu,Cu,Cu')

                nssdb.modify_cert(
                    nickname=deployer.mdict['pki_audit_signing_nickname'],
                    trust_attributes='u,u,Pu')

                print('Imported certificates into %s:' %
                      deployer.mdict['pki_server_database_path'])

                nssdb.show_certs()

            finally:
                nssdb.close()

        if len(deployer.instance.tomcat_instance_subsystems()) < 2:

            # Check to see if a secure connection is being used for the DS
            if config.str2bool(deployer.mdict['pki_ds_secure_connection']):
                # Check to see if a directory server CA certificate
                # using the same nickname already exists
                #
                # NOTE:  ALWAYS use the software DB regardless of whether
                #        the instance will utilize 'softokn' or an HSM
                #
                rv = deployer.certutil.verify_certificate_exists(
                    path=deployer.mdict['pki_server_database_path'],
                    token=deployer.mdict['pki_self_signed_token'],
                    nickname=deployer.
                    mdict['pki_ds_secure_connection_ca_nickname'],
                    password_file=deployer.mdict['pki_shared_pfile'])
                if not rv:
                    # Import the directory server CA certificate
                    rv = deployer.certutil.import_cert(
                        deployer.mdict['pki_ds_secure_connection_ca_nickname'],
                        deployer.
                        mdict['pki_ds_secure_connection_ca_trustargs'],
                        deployer.mdict['pki_ds_secure_connection_ca_pem_file'],
                        password_file=deployer.mdict['pki_shared_pfile'],
                        path=deployer.mdict['pki_server_database_path'],
                        token=deployer.mdict['pki_self_signed_token'])

        # Always delete the temporary 'pfile'
        deployer.file.delete(deployer.mdict['pki_shared_pfile'])

        # Store system cert parameters in installation step to guarantee the
        # parameters exist during configuration step and to allow customization.

        certs = subsystem.find_system_certs()
        for cert in certs:

            # get CS.cfg tag and pkispawn tag
            config_tag = cert['id']
            deploy_tag = config_tag

            if config_tag == 'signing':  # for CA and OCSP
                deploy_tag = subsystem.name + '_signing'

            # store nickname
            nickname = deployer.mdict['pki_%s_nickname' % deploy_tag]
            subsystem.config['%s.%s.nickname' %
                             (subsystem.name, config_tag)] = nickname
            subsystem.config['preop.cert.%s.nickname' % config_tag] = nickname

            # store tokenname
            tokenname = deployer.mdict['pki_%s_token' % deploy_tag]
            subsystem.config['%s.%s.tokenname' %
                             (subsystem.name, config_tag)] = tokenname

            fullname = nickname
            if pki.nssdb.normalize_token(tokenname):
                fullname = tokenname + ':' + nickname

            subsystem.config['%s.cert.%s.nickname' %
                             (subsystem.name, config_tag)] = fullname

            # store subject DN
            subject_dn = deployer.mdict['pki_%s_subject_dn' % deploy_tag]
            subsystem.config['preop.cert.%s.dn' % config_tag] = subject_dn

            keytype = deployer.mdict['pki_%s_key_type' % deploy_tag]
            subsystem.config['preop.cert.%s.keytype' % config_tag] = keytype

            keyalgorithm = deployer.mdict['pki_%s_key_algorithm' % deploy_tag]
            subsystem.config['preop.cert.%s.keyalgorithm' %
                             config_tag] = keyalgorithm

            signingalgorithm = deployer.mdict.get(
                'pki_%s_signing_algorithm' % deploy_tag, keyalgorithm)
            subsystem.config['preop.cert.%s.signingalgorithm' %
                             config_tag] = signingalgorithm

            if subsystem.name == 'ca':
                if config_tag == 'signing':
                    subsystem.config[
                        'ca.signing.defaultSigningAlgorithm'] = signingalgorithm
                    subsystem.config[
                        'ca.crl.MasterCRL.signingAlgorithm'] = signingalgorithm

                elif config_tag == 'ocsp_signing':
                    subsystem.config[
                        'ca.ocsp_signing.defaultSigningAlgorithm'] = signingalgorithm

            elif subsystem.name == 'ocsp':
                if config_tag == 'signing':
                    subsystem.config[
                        'ocsp.signing.defaultSigningAlgorithm'] = signingalgorithm

            elif subsystem.name == 'kra':
                if config_tag == 'transport':
                    subsystem.config[
                        'kra.transportUnit.signingAlgorithm'] = signingalgorithm

            # TODO: move more system cert params here

        admin_dn = deployer.mdict['pki_admin_subject_dn']
        subsystem.config['preop.cert.admin.dn'] = admin_dn

        # If specified in the deployment parameter, add generic CA signing cert
        # extension parameters into the CS.cfg. Generic extension for other
        # system certs can be added directly into CS.cfg after before the
        # configuration step.

        if subsystem.type == 'CA':

            signing_nickname = subsystem.config['ca.signing.nickname']
            subsystem.config['ca.signing.certnickname'] = signing_nickname
            subsystem.config['ca.signing.cacertnickname'] = signing_nickname

            ocsp_signing_nickname = subsystem.config[
                'ca.ocsp_signing.nickname']
            subsystem.config[
                'ca.ocsp_signing.certnickname'] = ocsp_signing_nickname
            subsystem.config[
                'ca.ocsp_signing.cacertnickname'] = ocsp_signing_nickname

            if deployer.configuration_file.add_req_ext:

                subsystem.config['preop.cert.signing.ext.oid'] = \
                    deployer.configuration_file.req_ext_oid
                subsystem.config['preop.cert.signing.ext.data'] = \
                    deployer.configuration_file.req_ext_data
                subsystem.config['preop.cert.signing.ext.critical'] = \
                    deployer.configuration_file.req_ext_critical.lower()

            if deployer.configuration_file.req_ski:
                subsystem.config['preop.cert.signing.subject_key_id'] = \
                    deployer.configuration_file.req_ski

        if subsystem.type == 'KRA':

            storage_nickname = subsystem.config['kra.storage.nickname']
            storage_token = subsystem.config['kra.storage.tokenname']

            if pki.nssdb.normalize_token(storage_token):
                subsystem.config['kra.storageUnit.hardware'] = storage_token
                subsystem.config['kra.storageUnit.nickName'] = \
                    storage_token + ':' + storage_nickname
            else:
                subsystem.config['kra.storageUnit.nickName'] = \
                    storage_nickname

            transport_nickname = subsystem.config['kra.transport.nickname']
            transport_token = subsystem.config['kra.transport.tokenname']

            if pki.nssdb.normalize_token(transport_token):
                subsystem.config['kra.transportUnit.nickName'] = \
                    transport_token + ':' + transport_nickname
            else:
                subsystem.config['kra.transportUnit.nickName'] = \
                    transport_nickname

        if subsystem.type == 'OCSP':

            signing_nickname = subsystem.config['ocsp.signing.nickname']
            subsystem.config['ocsp.signing.certnickname'] = signing_nickname
            subsystem.config['ocsp.signing.cacertnickname'] = signing_nickname

        audit_nickname = subsystem.config['%s.audit_signing.nickname' %
                                          subsystem.name]
        audit_token = subsystem.config['%s.audit_signing.tokenname' %
                                       subsystem.name]

        if pki.nssdb.normalize_token(audit_token):
            audit_nickname = audit_token + ':' + audit_nickname

        subsystem.config[
            'log.instance.SignedAudit.signedAuditCertNickname'] = audit_nickname

        subsystem.save()

        # Place 'slightly' less restrictive permissions on
        # the top-level client directory ONLY

        deployer.directory.create(
            deployer.mdict['pki_client_subsystem_dir'],
            uid=0,
            gid=0,
            perms=config.PKI_DEPLOYMENT_DEFAULT_CLIENT_DIR_PERMISSIONS)

        # Since 'certutil' does NOT strip the 'token=' portion of
        # the 'token=password' entries, create a client password file
        # which ONLY contains the 'password' for the purposes of
        # allowing 'certutil' to generate the security databases

        logger.info('Creating password file: %s',
                    deployer.mdict['pki_client_password_conf'])
        deployer.password.create_password_conf(
            deployer.mdict['pki_client_password_conf'],
            deployer.mdict['pki_client_database_password'],
            pin_sans_token=True)

        deployer.file.modify(deployer.mdict['pki_client_password_conf'],
                             uid=0,
                             gid=0)

        # Similarly, create a simple password file containing the
        # PKCS #12 password used when exporting the 'Admin Certificate'
        # into a PKCS #12 file

        deployer.password.create_client_pkcs12_password_conf(
            deployer.mdict['pki_client_pkcs12_password_conf'])

        deployer.file.modify(deployer.mdict['pki_client_pkcs12_password_conf'])

        pki.util.makedirs(deployer.mdict['pki_client_database_dir'],
                          force=True)

        nssdb = pki.nssdb.NSSDatabase(
            directory=deployer.mdict['pki_client_database_dir'],
            password_file=deployer.mdict['pki_client_password_conf'])

        try:
            if not nssdb.exists():
                nssdb.create()
        finally:
            nssdb.close()
コード例 #29
0
ファイル: cert.py プロジェクト: edewata/pki
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'

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

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('option %s not recognized', o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            logger.error('Missing cert ID.')
            self.print_help()
            sys.exit(1)

        cert_id = args[0]

        instance = pki.server.instance.PKIServerFactory.create(instance_name)

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem_name, cert_tag = pki.server.PKIServer.split_cert_id(cert_id)

        # If cert ID is instance specific, get it from first subsystem
        if not subsystem_name:
            subsystem_name = instance.get_subsystems()[0].name

        subsystem = instance.get_subsystem(subsystem_name)

        if not subsystem:
            logger.error(
                'No %s subsystem in instance %s.',
                subsystem_name, instance_name)
            sys.exit(1)

        subsystem_cert = subsystem.get_subsystem_cert(cert_tag)

        logger.info(
            'Retrieving certificate %s from %s',
            subsystem_cert['nickname'],
            subsystem_cert['token'])

        token = subsystem_cert['token']
        nssdb = instance.open_nssdb(token)

        # Get the cert data from NSS DB
        data = nssdb.get_cert(
            nickname=subsystem_cert['nickname'],
            output_format='base64')
        subsystem_cert['data'] = data

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

        # Get the cert request from LDAP database
        logger.info('Retrieving certificate request from CA database')

        # TODO: add support for remote CA
        ca = instance.get_subsystem('ca')
        if not ca:
            logger.error('No CA subsystem in instance %s.', instance_name)
            sys.exit(1)

        results = ca.find_cert_requests(cert=data)

        if results:
            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 = ''.join(lines)
            subsystem_cert['request'] = request

        else:
            logger.warning('Certificate request not found')

        instance.cert_update_config(cert_id, subsystem_cert)

        self.print_message('Updated "%s" system certificate' % cert_id)
コード例 #30
0
ファイル: subsystem.py プロジェクト: tiran/pki
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(
                argv, 'i:v',
                ['instance=', 'show-all', 'verbose', 'debug', 'help'])

        except getopt.GetoptError as e:
            logger.error(e)
            self.print_help()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        show_all = False

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

            elif o == '--show-all':
                show_all = True

            elif o == '--debug':
                logging.getLogger().setLevel(logging.DEBUG)

            elif o in ('-v', '--verbose'):
                logging.getLogger().setLevel(logging.INFO)

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

            else:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) != 1:
            logger.error('Missing subsystem ID')
            self.print_help()
            sys.exit(1)

        subsystem_name = args[0]

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

        if not instance.exists():
            logger.error('Invalid instance %s.', instance_name)
            sys.exit(1)

        instance.load()

        subsystem = instance.get_subsystem(subsystem_name)
        if not subsystem:
            logger.error('No %s subsystem in instance %s.', subsystem_name,
                         instance_name)
            sys.exit(1)

        certs = subsystem.get_cert_infos()

        self.print_message('%s entries matched' % len(certs))

        first = True
        for cert in certs:
            if first:
                first = False
            else:
                print()

            if cert['nickname']:
                cert_info = subsystem.get_nssdb_cert_info(cert['id'])
                if cert_info:
                    cert.update(cert_info)

            SubsystemCertCLI.print_subsystem_cert(cert, show_all)