Exemplo n.º 1
0
def main(argv):
    """main entry point"""

    config.pki_deployment_executable = os.path.basename(argv[0])

    # Set the umask
    os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK)

    # Read and process command-line arguments.
    parser = PKIConfigParser('PKI Instance Removal',
                             log.PKIDESTROY_EPILOG,
                             deployer=deployer)

    parser.optional.add_argument('-i',
                                 dest='pki_deployed_instance_name',
                                 action='store',
                                 nargs=1,
                                 metavar='<instance>',
                                 help='FORMAT:  ${pki_instance_name}')

    parser.optional.add_argument('-u',
                                 dest='pki_secdomain_user',
                                 action='store',
                                 nargs=1,
                                 metavar='<security domain user>',
                                 help='security domain user')

    parser.optional.add_argument('-W',
                                 dest='pki_secdomain_pass_file',
                                 action='store',
                                 nargs=1,
                                 metavar='<security domain password file>',
                                 help='security domain password file path')

    parser.optional.add_argument('--force',
                                 dest='pki_force_destroy',
                                 action='store_true',
                                 help='force removal of subsystem')

    parser.optional.add_argument('--remove-logs',
                                 dest='pki_remove_logs',
                                 action='store_true',
                                 help='remove subsystem logs')

    args = parser.process_command_line_arguments()

    interactive = False

    # Only run this program as "root".
    if not os.geteuid() == 0:
        sys.exit("'%s' must be run as root!" % argv[0])

    while True:

        # -s <subsystem>
        if args.pki_subsystem is None:
            interactive = True
            deployer.subsystem_name = parser.read_text(
                'Subsystem (CA/KRA/OCSP/TKS/TPS)',
                options=['CA', 'KRA', 'OCSP', 'TKS', 'TPS'],
                default='CA',
                case_sensitive=False).upper()
        else:
            deployer.subsystem_name = str(args.pki_subsystem).strip('[\']')

        # -i <instance name>
        if args.pki_deployed_instance_name is None:
            interactive = True
            config.pki_deployed_instance_name = \
                parser.read_text('Instance', default='pki-tomcat')
        else:
            config.pki_deployed_instance_name = \
                str(args.pki_deployed_instance_name).strip('[\']')

        if interactive:
            print()
            parser.indent = 0

            begin = parser.read_text(
                'Begin uninstallation (Yes/No/Quit)',
                options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                sign='?',
                allow_empty=False,
                case_sensitive=False).lower()

            print()

            if begin == 'q' or begin == 'quit':
                print("Uninstallation canceled.")
                sys.exit(0)

            elif begin == 'y' or begin == 'yes':
                break

        else:
            break

    #    '-u'
    if args.pki_secdomain_user:
        config.pki_secdomain_user = str(args.pki_secdomain_user).strip('[\']')

    #    '-W' password file
    if args.pki_secdomain_pass_file:
        with open(str(args.pki_secdomain_pass_file).strip('[\']'), 'r') as \
                pwd_file:
            config.pki_secdomain_pass = pwd_file.readline().strip('\n')

    #   '--force'
    force_destroy = args.pki_force_destroy

    #   '--remove-logs'
    remove_logs = args.pki_remove_logs

    # verify that previously deployed instance exists
    deployed_pki_instance_path = os.path.join(
        config.PKI_DEPLOYMENT_BASE_ROOT, config.pki_deployed_instance_name)
    if not os.path.exists(deployed_pki_instance_path) and not force_destroy:
        print("ERROR:  " +
              log.PKI_INSTANCE_DOES_NOT_EXIST_1 % deployed_pki_instance_path)
        print()
        parser.arg_parser.exit(-1)

    # verify that previously deployed subsystem for this instance exists
    deployed_pki_subsystem_path = os.path.join(deployed_pki_instance_path,
                                               deployer.subsystem_name.lower())

    if not os.path.exists(deployed_pki_subsystem_path) and not force_destroy:
        print("ERROR:  " + log.PKI_SUBSYSTEM_DOES_NOT_EXIST_2 %
              (deployer.subsystem_name, deployed_pki_instance_path))
        print()
        parser.arg_parser.exit(-1)

    config.default_deployment_cfg = \
        config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE

    # establish complete path to previously deployed configuration file
    config.user_deployment_cfg = os.path.join(
        deployed_pki_subsystem_path, "registry",
        deployer.subsystem_name.lower(), config.USER_DEPLOYMENT_CONFIGURATION)

    if force_destroy and not os.path.exists(config.user_deployment_cfg):
        # During force destroy, try to load the file. If file doesn't exist, we ignore it
        config.user_deployment_cfg = None

    parser.validate()
    parser.init_config(pki_instance_name=config.pki_deployed_instance_name)

    if args.pki_verbosity > 1:
        logger.warning(
            'The -%s option has been deprecated. Use --debug instead.',
            'v' * args.pki_verbosity)

    # Read the specified PKI configuration file.
    rv = parser.read_pki_configuration_file()
    if rv != 0:
        logger.error(log.PKI_UNABLE_TO_PARSE_1, rv)
        sys.exit(1)

    # Combine the various sectional dictionaries into a PKI master dictionary
    parser.compose_pki_master_dictionary()
    deployer.init()

    instance = pki.server.instance.PKIInstance(
        deployer.mdict['pki_instance_name'],
        user=deployer.mdict['pki_user'],
        group=deployer.mdict['pki_group'])

    log_dir = config.PKI_DEPLOYMENT_LOG_ROOT
    log_name = "pki" + "-" +\
               deployer.subsystem_name.lower() +\
               "-" + "destroy" + "." +\
               deployer.log_timestamp + "." + "log"
    log_file = os.path.join(log_dir, log_name)
    print('Uninstallation log: %s' % log_file)

    pkilogging.enable_pki_logger(log_file)

    # Add force_destroy to master dictionary
    parser.mdict['pki_force_destroy'] = force_destroy

    # Add remove logs to master dictionary
    parser.mdict['pki_remove_logs'] = remove_logs

    logger.debug(log.PKI_DICTIONARY_MASTER)
    logger.debug(pkilogging.log_format(parser.mdict))

    print("Uninstalling " + deployer.subsystem_name + " from " +
          deployed_pki_instance_path + ".")

    # Process the various "scriptlets" to remove the specified PKI subsystem.
    pki_subsystem_scriptlets = parser.mdict['destroy_scriplets'].split()

    try:
        for scriptlet_name in pki_subsystem_scriptlets:

            scriptlet_module = __import__("pki.server.deployment.scriptlets." +
                                          scriptlet_name,
                                          fromlist=[scriptlet_name])

            scriptlet = scriptlet_module.PkiScriptlet()
            scriptlet.deployer = deployer
            scriptlet.instance = instance
            scriptlet.destroy(deployer)

    except subprocess.CalledProcessError as e:
        log_error_details()
        print()
        print("Uninstallation failed: Command failed: %s" % ' '.join(e.cmd))
        if e.output:
            print(e.output)
        print()
        sys.exit(1)

    except Exception as e:  # pylint: disable=broad-except
        log_error_details()
        print()
        print("Uninstallation failed: %s" % e)
        print()
        sys.exit(1)

    print()
    print("Uninstallation complete.")
Exemplo n.º 2
0
def main(argv):
    """main entry point"""

    config.pki_deployment_executable = os.path.basename(argv[0])

    # Set the umask
    os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK)

    # Read and process command-line arguments.
    parser = PKIConfigParser('PKI Instance Installation and Configuration',
                             log.PKISPAWN_EPILOG,
                             deployer=deployer)

    parser.optional.add_argument('-f',
                                 dest='user_deployment_cfg',
                                 action='store',
                                 nargs=1,
                                 metavar='<file>',
                                 help='configuration filename '
                                 '(MUST specify complete path)')

    parser.optional.add_argument('--precheck',
                                 dest='precheck',
                                 action='store_true',
                                 help='Execute pre-checks and exit')

    parser.optional.add_argument('--skip-configuration',
                                 dest='skip_configuration',
                                 action='store_true',
                                 help='skip configuration step')

    parser.optional.add_argument('--skip-installation',
                                 dest='skip_installation',
                                 action='store_true',
                                 help='skip installation step')

    args = parser.process_command_line_arguments()

    config.default_deployment_cfg = \
        config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE

    # -f <user deployment config>
    if args.user_deployment_cfg is not None:
        config.user_deployment_cfg = str(
            args.user_deployment_cfg).strip('[\']')

    parser.validate()
    interactive = False

    if config.user_deployment_cfg is None:
        interactive = True
        parser.indent = 0
        print(log.PKISPAWN_INTERACTIVE_INSTALLATION)
    else:
        sanitize_user_deployment_cfg(config.user_deployment_cfg)

    # Only run this program as "root".
    if not os.geteuid() == 0:
        sys.exit("'%s' must be run as root!" % argv[0])

    while True:
        # -s <subsystem>
        if args.pki_subsystem is None:
            interactive = True
            parser.indent = 0

            deployer.subsystem_name = parser.read_text(
                'Subsystem (CA/KRA/OCSP/TKS/TPS)',
                options=['CA', 'KRA', 'OCSP', 'TKS', 'TPS'],
                default='CA',
                case_sensitive=False).upper()
            print()
        else:
            deployer.subsystem_name = str(args.pki_subsystem).strip('[\']')

        parser.init_config()

        if config.user_deployment_cfg is None:
            if args.precheck:
                sys.exit(
                    'precheck mode is only valid for non-interactive installs')
            interactive = True
            parser.indent = 2

            print("Tomcat:")
            instance_name = parser.read_text('Instance', 'DEFAULT',
                                             'pki_instance_name')
            existing_data = parser.read_existing_deployment_data(instance_name)

            set_port(parser, 'pki_http_port', 'HTTP port', existing_data)

            set_port(parser, 'pki_https_port', 'Secure HTTP port',
                     existing_data)

            set_port(parser, 'pki_ajp_port', 'AJP port', existing_data)

            set_port(parser, 'pki_tomcat_server_port', 'Management port',
                     existing_data)

            print()

            print("Administrator:")
            parser.read_text('Username', deployer.subsystem_name,
                             'pki_admin_uid')

            admin_password = parser.read_password(
                'Password',
                deployer.subsystem_name,
                'pki_admin_password',
                verifyMessage='Verify password')

            parser.set_property(deployer.subsystem_name, 'pki_backup_password',
                                admin_password)
            parser.set_property(deployer.subsystem_name,
                                'pki_client_database_password', admin_password)
            parser.set_property(deployer.subsystem_name,
                                'pki_client_pkcs12_password', admin_password)

            if parser.mdict['pki_import_admin_cert'] == 'True':
                import_cert = 'Y'
            else:
                import_cert = 'N'

            import_cert = parser.read_text('Import certificate (Yes/No)',
                                           default=import_cert,
                                           options=['Yes', 'Y', 'No', 'N'],
                                           sign='?',
                                           case_sensitive=False).lower()

            if import_cert == 'y' or import_cert == 'yes':
                parser.set_property(deployer.subsystem_name,
                                    'pki_import_admin_cert', 'True')
                parser.read_text('Import certificate from',
                                 deployer.subsystem_name,
                                 'pki_admin_cert_file')
            else:
                parser.set_property(deployer.subsystem_name,
                                    'pki_import_admin_cert', 'False')

                parser.read_text('Export certificate to',
                                 deployer.subsystem_name,
                                 'pki_client_admin_cert')

            # if parser.mdict['pki_hsm_enable'] == 'True':
            #     use_hsm = 'Y'
            # else:
            #     use_hsm = 'N'

            # use_hsm = parser.read_text(
            #     'Using hardware security module (HSM) (Yes/No)',
            #     default=use_hsm, options=['Yes', 'Y', 'No', 'N'],
            #     sign='?', case_sensitive=False).lower()

            # if use_hsm == 'y' or use_hsm == 'yes':
            #     # XXX:  Suppress interactive HSM installation
            #     print "Interactive HSM installation is currently unsupported."
            #     sys.exit(0)

            # TBD:  Interactive HSM installation
            # parser.set_property(deployer.subsystem_name,
            #                     'pki_hsm_enable',
            #                     'True')
            # modulename = parser.read_text(
            #     'HSM Module Name (e. g. - nethsm)', allow_empty=False)
            # parser.set_property(deployer.subsystem_name,
            #                     'pki_hsm_modulename',
            #                     modulename)
            # libfile = parser.read_text(
            #     'HSM Lib File ' +
            #     '(e. g. - /opt/nfast/toolkits/pkcs11/libcknfast.so)',
            #     allow_empty=False)
            # parser.set_property(deployer.subsystem_name,
            #                     'pki_hsm_libfile',
            #                     libfile)
            print()

            print("Directory Server:")
            while True:
                parser.read_text('Hostname', deployer.subsystem_name,
                                 'pki_ds_hostname')

                if parser.mdict['pki_ds_secure_connection'] == 'True':
                    secure = 'Y'
                else:
                    secure = 'N'

                secure = parser.read_text(
                    'Use a secure LDAPS connection (Yes/No/Quit)',
                    default=secure,
                    options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                    sign='?',
                    case_sensitive=False).lower()

                if secure == 'q' or secure == 'quit':
                    print("Installation canceled.")
                    sys.exit(0)

                if secure == 'y' or secure == 'yes':
                    # Set secure DS connection to true
                    parser.set_property(deployer.subsystem_name,
                                        'pki_ds_secure_connection', 'True')
                    # Prompt for secure 'ldaps' port
                    parser.read_text('Secure LDAPS Port',
                                     deployer.subsystem_name,
                                     'pki_ds_ldaps_port')
                    # Specify complete path to a directory server
                    # CA certificate pem file
                    pem_file = parser.read_text(
                        'Directory Server CA certificate pem file',
                        allow_empty=False)
                    parser.set_property(
                        deployer.subsystem_name,
                        'pki_ds_secure_connection_ca_pem_file', pem_file)
                else:
                    parser.read_text('LDAP Port', deployer.subsystem_name,
                                     'pki_ds_ldap_port')

                parser.read_text('Bind DN', deployer.subsystem_name,
                                 'pki_ds_bind_dn')
                parser.read_password('Password', deployer.subsystem_name,
                                     'pki_ds_password')

                try:
                    parser.ds_verify_configuration()

                except ldap.LDAPError as e:
                    parser.print_text('ERROR: ' + e.args[0]['desc'])
                    continue

                parser.read_text('Base DN', deployer.subsystem_name,
                                 'pki_ds_base_dn')
                try:
                    if not parser.ds_base_dn_exists():
                        break

                except ldap.LDAPError as e:
                    parser.print_text('ERROR: ' + e.args[0]['desc'])
                    continue

                remove = parser.read_text(
                    'Base DN already exists. Overwrite (Yes/No/Quit)',
                    options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                    sign='?',
                    allow_empty=False,
                    case_sensitive=False).lower()

                if remove == 'q' or remove == 'quit':
                    print("Installation canceled.")
                    sys.exit(0)

                if remove == 'y' or remove == 'yes':
                    break

            print()

            print("Security Domain:")

            if deployer.subsystem_name == "CA":
                parser.read_text('Name', deployer.subsystem_name,
                                 'pki_security_domain_name')

            else:
                while True:
                    parser.read_text('Hostname', deployer.subsystem_name,
                                     'pki_security_domain_hostname')

                    parser.read_text('Secure HTTP port',
                                     deployer.subsystem_name,
                                     'pki_security_domain_https_port')

                    try:
                        parser.sd_connect()
                        info = parser.sd_get_info()
                        parser.print_text('Name: ' + info.name)
                        parser.set_property(deployer.subsystem_name,
                                            'pki_security_domain_name',
                                            info.name)
                        break
                    except requests.exceptions.ConnectionError as e:
                        parser.print_text('ERROR: ' + str(e))

                while True:
                    parser.read_text('Username', deployer.subsystem_name,
                                     'pki_security_domain_user')
                    parser.read_password('Password', deployer.subsystem_name,
                                         'pki_security_domain_password')

                    try:
                        parser.sd_authenticate()
                        break
                    except requests.exceptions.HTTPError as e:
                        parser.print_text('ERROR: ' + str(e))

            print()

            if deployer.subsystem_name == "TPS":
                print("External Servers:")

                while True:
                    parser.read_text('CA URL', deployer.subsystem_name,
                                     'pki_ca_uri')
                    try:
                        status = parser.get_server_status('ca', 'pki_ca_uri')
                        if status == 'running':
                            break
                        parser.print_text('ERROR: CA is not running')
                    except requests.exceptions.ConnectionError as e:
                        parser.print_text('ERROR: ' + str(e))

                while True:
                    parser.read_text('TKS URL', deployer.subsystem_name,
                                     'pki_tks_uri')
                    try:
                        status = parser.get_server_status('tks', 'pki_tks_uri')
                        if status == 'running':
                            break
                        parser.print_text('ERROR: TKS is not running')
                    except requests.exceptions.ConnectionError as e:
                        parser.print_text('ERROR: ' + str(e))

                while True:
                    keygen = parser.read_text(
                        'Enable server side key generation (Yes/No)',
                        options=['Yes', 'Y', 'No', 'N'],
                        default='N',
                        sign='?',
                        case_sensitive=False).lower()

                    if keygen == 'y' or keygen == 'yes':
                        parser.set_property(deployer.subsystem_name,
                                            'pki_enable_server_side_keygen',
                                            'True')

                        parser.read_text('KRA URL', deployer.subsystem_name,
                                         'pki_kra_uri')
                        try:
                            status = parser.get_server_status(
                                'kra', 'pki_kra_uri')
                            if status == 'running':
                                break
                            parser.print_text('ERROR: KRA is not running')
                        except requests.exceptions.ConnectionError as e:
                            parser.print_text('ERROR: ' + str(e))
                    else:
                        parser.set_property(deployer.subsystem_name,
                                            'pki_enable_server_side_keygen',
                                            'False')
                        break

                print()

                print("Authentication Database:")

                while True:
                    parser.read_text('Hostname', deployer.subsystem_name,
                                     'pki_authdb_hostname')
                    parser.read_text('Port', deployer.subsystem_name,
                                     'pki_authdb_port')
                    basedn = parser.read_text('Base DN', allow_empty=False)
                    parser.set_property(deployer.subsystem_name,
                                        'pki_authdb_basedn', basedn)

                    try:
                        parser.authdb_connect()
                        if parser.authdb_base_dn_exists():
                            break
                        else:
                            parser.print_text('ERROR: base DN does not exist')

                    except ldap.LDAPError as e:
                        parser.print_text('ERROR: ' + e.args[0]['desc'])

                print()

        if interactive:
            parser.indent = 0

            begin = parser.read_text(
                'Begin installation (Yes/No/Quit)',
                options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                sign='?',
                allow_empty=False,
                case_sensitive=False).lower()
            print()

            if begin == 'q' or begin == 'quit':
                print("Installation canceled.")
                sys.exit(0)

            if begin == 'y' or begin == 'yes':
                break

        else:
            break

    if not os.path.exists(config.PKI_DEPLOYMENT_SOURCE_ROOT + "/" +
                          deployer.subsystem_name.lower()):
        print("ERROR:  " + log.PKI_SUBSYSTEM_NOT_INSTALLED_1 %
              deployer.subsystem_name.lower())
        sys.exit(1)

    start_logging()

    # Read the specified PKI configuration file.
    rv = parser.read_pki_configuration_file()
    if rv != 0:
        config.pki_log.error(log.PKI_UNABLE_TO_PARSE_1,
                             rv,
                             extra=config.PKI_INDENTATION_LEVEL_0)
        sys.exit(1)

    # --skip-configuration
    if args.skip_configuration:
        parser.set_property(deployer.subsystem_name, 'pki_skip_configuration',
                            'True')

    # --skip-installation
    if args.skip_installation:
        parser.set_property(deployer.subsystem_name, 'pki_skip_installation',
                            'True')

    create_master_dictionary(parser)

    if not interactive and \
            not config.str2bool(parser.mdict['pki_skip_configuration']):
        check_ds(parser)
        check_security_domain(parser)

    if args.precheck:
        print('pre-checks completed successfully.')
        sys.exit(0)

    print("Installing " + deployer.subsystem_name + " into " +
          parser.mdict['pki_instance_path'] + ".")

    # Process the various "scriptlets" to create the specified PKI subsystem.
    pki_subsystem_scriptlets = parser.mdict['spawn_scriplets'].split()
    deployer.init(parser)

    try:
        for scriptlet_name in pki_subsystem_scriptlets:

            scriptlet_module = __import__("pki.server.deployment.scriptlets." +
                                          scriptlet_name,
                                          fromlist=[scriptlet_name])

            scriptlet = scriptlet_module.PkiScriptlet()

            scriptlet.spawn(deployer)

    except subprocess.CalledProcessError as e:
        log_error_details()
        print()
        print("Installation failed: Command failed: %s" % ' '.join(e.cmd))
        print()
        print('Please check pkispawn logs in %s/%s' %
              (config.pki_log_dir, config.pki_log_name))
        sys.exit(1)

    except requests.HTTPError as e:
        r = e.response
        print()

        print('Installation failed:')
        if r.headers['content-type'] == 'application/json':
            data = r.json()
            print('%s: %s' % (data['ClassName'], data['Message']))
        else:
            print(r.text)

        print()
        print('Please check the %s logs in %s.' %
              (deployer.subsystem_name,
               deployer.mdict['pki_subsystem_log_path']))

        sys.exit(1)

    except Exception as e:  # pylint: disable=broad-except
        log_error_details()
        print()
        print("Installation failed: %s" % e)
        print()
        sys.exit(1)

    # ALWAYS archive configuration file and manifest file

    config.pki_log.info(
        log.PKI_ARCHIVE_CONFIG_MESSAGE_1,
        deployer.mdict['pki_user_deployment_cfg_spawn_archive'],
        extra=config.PKI_INDENTATION_LEVEL_1)

    # For debugging/auditing purposes, save a timestamped copy of
    # this configuration file in the subsystem archive
    deployer.file.copy(deployer.mdict['pki_user_deployment_cfg_replica'],
                       deployer.mdict['pki_user_deployment_cfg_spawn_archive'])

    config.pki_log.info(log.PKI_ARCHIVE_MANIFEST_MESSAGE_1,
                        deployer.mdict['pki_manifest_spawn_archive'],
                        extra=config.PKI_INDENTATION_LEVEL_1)

    # for record in manifest.database:
    #     print tuple(record)

    manifest_file = manifest.File(deployer.manifest_db)
    manifest_file.register(deployer.mdict['pki_manifest'])
    manifest_file.write()

    deployer.file.modify(deployer.mdict['pki_manifest'], silent=True)

    # Also, for debugging/auditing purposes, save a timestamped copy of
    # this installation manifest file
    deployer.file.copy(deployer.mdict['pki_manifest'],
                       deployer.mdict['pki_manifest_spawn_archive'])

    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 skip_configuration:
        print_skip_configuration_information(parser.mdict)

    elif (external or standalone) and step_one:
        if deployer.subsystem_name == 'CA':
            print_external_ca_step_one_information(parser.mdict)

        elif deployer.subsystem_name == 'KRA':
            print_kra_step_one_information(parser.mdict)

        else:  # OCSP
            print_ocsp_step_one_information(parser.mdict)

    else:
        print_final_install_information(parser.mdict)
Exemplo n.º 3
0
def main(argv):
    """main entry point"""

    config.pki_deployment_executable = os.path.basename(argv[0])

    # Set the umask
    os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK)

    # Read and process command-line arguments.
    parser = PKIConfigParser('PKI Instance Removal',
                             log.PKIDESTROY_EPILOG,
                             deployer=deployer)

    parser.optional.add_argument('-i',
                                 dest='pki_deployed_instance_name',
                                 action='store',
                                 nargs=1,
                                 metavar='<instance>',
                                 help='FORMAT:  ${pki_instance_name}')

    parser.optional.add_argument('-u',
                                 dest='pki_secdomain_user',
                                 action='store',
                                 nargs=1,
                                 metavar='<security domain user>',
                                 help='security domain user')

    parser.optional.add_argument('-W',
                                 dest='pki_secdomain_pass_file',
                                 action='store',
                                 nargs=1,
                                 metavar='<security domain password file>',
                                 help='security domain password file path')

    args = parser.process_command_line_arguments()

    interactive = False

    # Only run this program as "root".
    if not os.geteuid() == 0:
        sys.exit("'%s' must be run as root!" % argv[0])

    while True:

        # -s <subsystem>
        if args.pki_subsystem is None:
            interactive = True
            deployer.subsystem_name = parser.read_text(
                'Subsystem (CA/KRA/OCSP/TKS/TPS)',
                options=['CA', 'KRA', 'OCSP', 'TKS', 'TPS'],
                default='CA',
                case_sensitive=False).upper()
        else:
            deployer.subsystem_name = str(args.pki_subsystem).strip('[\']')

        # -i <instance name>
        if args.pki_deployed_instance_name is None:
            interactive = True
            config.pki_deployed_instance_name = \
                parser.read_text('Instance', default='pki-tomcat')
        else:
            config.pki_deployed_instance_name = \
                str(args.pki_deployed_instance_name).strip('[\']')

        if interactive:
            print()
            parser.indent = 0

            begin = parser.read_text(
                'Begin uninstallation (Yes/No/Quit)',
                options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                sign='?',
                allow_empty=False,
                case_sensitive=False).lower()

            print()

            if begin == 'q' or begin == 'quit':
                print("Uninstallation canceled.")
                sys.exit(0)

            elif begin == 'y' or begin == 'yes':
                break

        else:
            break

    #    '-u'
    if args.pki_secdomain_user:
        config.pki_secdomain_user = str(args.pki_secdomain_user).strip('[\']')

    #    '-W' password file
    if args.pki_secdomain_pass_file:
        with open(str(args.pki_secdomain_pass_file).strip('[\']'), 'r') as \
                pwd_file:
            config.pki_secdomain_pass = pwd_file.readline().strip('\n')

    # verify that previously deployed instance exists
    deployed_pki_instance_path = \
        config.pki_root_prefix + config.PKI_DEPLOYMENT_BASE_ROOT + "/" + \
        config.pki_deployed_instance_name
    if not os.path.exists(deployed_pki_instance_path):
        print("ERROR:  " +
              log.PKI_INSTANCE_DOES_NOT_EXIST_1 % deployed_pki_instance_path)
        print()
        parser.arg_parser.exit(-1)

    # verify that previously deployed subsystem for this instance exists
    deployed_pki_subsystem_path = \
        deployed_pki_instance_path + "/" + deployer.subsystem_name.lower()
    if not os.path.exists(deployed_pki_subsystem_path):
        print("ERROR:  " + log.PKI_SUBSYSTEM_DOES_NOT_EXIST_2 %
              (deployer.subsystem_name, deployed_pki_instance_path))
        print()
        parser.arg_parser.exit(-1)

    config.default_deployment_cfg = \
        config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE

    # establish complete path to previously deployed configuration file
    config.user_deployment_cfg =\
        deployed_pki_subsystem_path + "/" +\
        "registry" + "/" +\
        deployer.subsystem_name.lower() + "/" +\
        config.USER_DEPLOYMENT_CONFIGURATION

    parser.validate()
    parser.init_config()

    # Enable 'pkidestroy' logging.
    config.pki_log_dir = \
        config.pki_root_prefix + config.PKI_DEPLOYMENT_LOG_ROOT
    config.pki_log_name = "pki" + "-" +\
                          deployer.subsystem_name.lower() +\
                          "-" + "destroy" + "." +\
                          deployer.log_timestamp + "." + "log"
    print('Log file: %s/%s' % (config.pki_log_dir, config.pki_log_name))

    rv = pkilogging.enable_pki_logger(config.pki_log_dir, config.pki_log_name,
                                      config.pki_log_level,
                                      config.pki_console_log_level,
                                      "pkidestroy")
    if rv != OSError:
        config.pki_log = rv
    else:
        print(log.PKI_UNABLE_TO_CREATE_LOG_DIRECTORY_1 % config.pki_log_dir)
        sys.exit(1)

    # Read the specified PKI configuration file.
    rv = parser.read_pki_configuration_file()
    if rv != 0:
        config.pki_log.error(log.PKI_UNABLE_TO_PARSE_1,
                             rv,
                             extra=config.PKI_INDENTATION_LEVEL_0)
        sys.exit(1)

    # Combine the various sectional dictionaries into a PKI master dictionary
    parser.compose_pki_master_dictionary()
    parser.mdict['pki_destroy_log'] = \
        config.pki_log_dir + "/" + config.pki_log_name
    config.pki_log.debug(log.PKI_DICTIONARY_MASTER,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.log_format(parser.mdict),
                         extra=config.PKI_INDENTATION_LEVEL_0)

    print("Uninstalling " + deployer.subsystem_name + " from " +
          deployed_pki_instance_path + ".")

    # Process the various "scriptlets" to remove the specified PKI subsystem.
    pki_subsystem_scriptlets = parser.mdict['destroy_scriplets'].split()
    deployer.init(parser)

    try:
        for scriptlet_name in pki_subsystem_scriptlets:

            scriptlet_module = __import__("pki.server.deployment.scriptlets." +
                                          scriptlet_name,
                                          fromlist=[scriptlet_name])

            scriptlet = scriptlet_module.PkiScriptlet()

            scriptlet.destroy(deployer)

    # pylint: disable=W0703
    except Exception as e:
        log_error_details()
        print()
        print("Uninstallation failed: %s" % e)
        print()
        sys.exit(1)

    print()
    print("Uninstallation complete.")
Exemplo n.º 4
0
def main(argv):
    """main entry point"""

    config.pki_deployment_executable = os.path.basename(argv[0])

    # Set the umask
    os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK)

    # Read and process command-line arguments.
    parser = PKIConfigParser(
        'PKI Instance Installation and Configuration',
        log.PKISPAWN_EPILOG,
        deployer=deployer)

    parser.optional.add_argument(
        '-f',
        dest='user_deployment_cfg', action='store',
        nargs=1, metavar='<file>',
        help='configuration filename '
        '(MUST specify complete path)')

    parser.optional.add_argument(
        '--precheck',
        dest='precheck', action='store_true',
        help='Execute pre-checks and exit')

    parser.optional.add_argument(
        '--skip-configuration',
        dest='skip_configuration',
        action='store_true',
        help='skip configuration step')

    parser.optional.add_argument(
        '--skip-installation',
        dest='skip_installation',
        action='store_true',
        help='skip installation step')

    parser.optional.add_argument(
        '--enforce-hostname',
        dest='enforce_hostname',
        action='store_true',
        help='enforce strict hostname/FQDN checks')

    args = parser.process_command_line_arguments()

    config.default_deployment_cfg = \
        config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE

    # -f <user deployment config>
    if args.user_deployment_cfg is not None:
        config.user_deployment_cfg = str(
            args.user_deployment_cfg).strip('[\']')

    parser.validate()

    # Currently the only logic in deployer's validation is the
    # hostname check; at some point this might need to be updated.
    if args.enforce_hostname:
        deployer.validate()

    interactive = False

    if config.user_deployment_cfg is None:
        interactive = True
        parser.indent = 0
        print(log.PKISPAWN_INTERACTIVE_INSTALLATION)
    else:
        sanitize_user_deployment_cfg(config.user_deployment_cfg)

    # Only run this program as "root".
    if not os.geteuid() == 0:
        sys.exit("'%s' must be run as root!" % argv[0])

    while True:
        # -s <subsystem>
        if args.pki_subsystem is None:
            interactive = True
            parser.indent = 0

            deployer.subsystem_name = parser.read_text(
                'Subsystem (CA/KRA/OCSP/TKS/TPS)',
                options=['CA', 'KRA', 'OCSP', 'TKS', 'TPS'],
                default='CA', case_sensitive=False).upper()
            print()
        else:
            deployer.subsystem_name = str(args.pki_subsystem).strip('[\']')

        parser.init_config()

        if config.user_deployment_cfg is None:
            if args.precheck:
                sys.exit(
                    'precheck mode is only valid for non-interactive installs')
            interactive = True
            parser.indent = 2

            print("Tomcat:")
            instance_name = parser.read_text(
                'Instance', 'DEFAULT', 'pki_instance_name')
            existing_data = parser.read_existing_deployment_data(instance_name)

            set_port(parser,
                     'pki_http_port',
                     'HTTP port',
                     existing_data)

            set_port(parser,
                     'pki_https_port',
                     'Secure HTTP port',
                     existing_data)

            set_port(parser,
                     'pki_ajp_port',
                     'AJP port',
                     existing_data)

            set_port(parser,
                     'pki_tomcat_server_port',
                     'Management port',
                     existing_data)

            print()

            print("Administrator:")
            parser.read_text('Username', deployer.subsystem_name, 'pki_admin_uid')

            admin_password = parser.read_password(
                'Password', deployer.subsystem_name, 'pki_admin_password',
                verifyMessage='Verify password')

            parser.set_property(deployer.subsystem_name, 'pki_backup_password',
                                admin_password)
            parser.set_property(deployer.subsystem_name,
                                'pki_client_database_password',
                                admin_password)
            parser.set_property(deployer.subsystem_name,
                                'pki_client_pkcs12_password',
                                admin_password)

            if parser.mdict['pki_import_admin_cert'] == 'True':
                import_cert = 'Y'
            else:
                import_cert = 'N'

            import_cert = parser.read_text(
                'Import certificate (Yes/No)',
                default=import_cert, options=['Yes', 'Y', 'No', 'N'],
                sign='?', case_sensitive=False).lower()

            if import_cert == 'y' or import_cert == 'yes':
                parser.set_property(deployer.subsystem_name,
                                    'pki_import_admin_cert',
                                    'True')
                parser.read_text('Import certificate from',
                                 deployer.subsystem_name,
                                 'pki_admin_cert_file')
            else:
                parser.set_property(deployer.subsystem_name,
                                    'pki_import_admin_cert',
                                    'False')

                parser.read_text('Export certificate to',
                                 deployer.subsystem_name,
                                 'pki_client_admin_cert')

            # if parser.mdict['pki_hsm_enable'] == 'True':
            #     use_hsm = 'Y'
            # else:
            #     use_hsm = 'N'

            # use_hsm = parser.read_text(
            #     'Using hardware security module (HSM) (Yes/No)',
            #     default=use_hsm, options=['Yes', 'Y', 'No', 'N'],
            #     sign='?', case_sensitive=False).lower()

            # if use_hsm == 'y' or use_hsm == 'yes':
            #     # XXX:  Suppress interactive HSM installation
            #     print "Interactive HSM installation is currently unsupported."
            #     sys.exit(0)

            # TBD:  Interactive HSM installation
            # parser.set_property(deployer.subsystem_name,
            #                     'pki_hsm_enable',
            #                     'True')
            # modulename = parser.read_text(
            #     'HSM Module Name (e. g. - nethsm)', allow_empty=False)
            # parser.set_property(deployer.subsystem_name,
            #                     'pki_hsm_modulename',
            #                     modulename)
            # libfile = parser.read_text(
            #     'HSM Lib File ' +
            #     '(e. g. - /opt/nfast/toolkits/pkcs11/libcknfast.so)',
            #     allow_empty=False)
            # parser.set_property(deployer.subsystem_name,
            #                     'pki_hsm_libfile',
            #                     libfile)
            print()

            print("Directory Server:")
            while True:
                parser.read_text('Hostname',
                                 deployer.subsystem_name,
                                 'pki_ds_hostname')

                if parser.mdict['pki_ds_secure_connection'] == 'True':
                    secure = 'Y'
                else:
                    secure = 'N'

                secure = parser.read_text(
                    'Use a secure LDAPS connection (Yes/No/Quit)',
                    default=secure,
                    options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                    sign='?', case_sensitive=False).lower()

                if secure == 'q' or secure == 'quit':
                    print("Installation canceled.")
                    sys.exit(0)

                if secure == 'y' or secure == 'yes':
                    # Set secure DS connection to true
                    parser.set_property(deployer.subsystem_name,
                                        'pki_ds_secure_connection',
                                        'True')
                    # Prompt for secure 'ldaps' port
                    parser.read_text('Secure LDAPS Port',
                                     deployer.subsystem_name,
                                     'pki_ds_ldaps_port')
                    # Specify complete path to a directory server
                    # CA certificate pem file
                    pem_file = parser.read_text(
                        'Directory Server CA certificate pem file',
                        allow_empty=False)
                    parser.set_property(deployer.subsystem_name,
                                        'pki_ds_secure_connection_ca_pem_file',
                                        pem_file)
                else:
                    parser.read_text('LDAP Port',
                                     deployer.subsystem_name,
                                     'pki_ds_ldap_port')

                parser.read_text('Bind DN',
                                 deployer.subsystem_name,
                                 'pki_ds_bind_dn')
                parser.read_password('Password',
                                     deployer.subsystem_name,
                                     'pki_ds_password')

                try:
                    parser.ds_verify_configuration()

                except ldap.LDAPError as e:
                    parser.print_text('ERROR: ' + e.args[0]['desc'])
                    continue

                parser.read_text('Base DN',
                                 deployer.subsystem_name,
                                 'pki_ds_base_dn')
                try:
                    if not parser.ds_base_dn_exists():
                        break

                except ldap.LDAPError as e:
                    parser.print_text('ERROR: ' + e.args[0]['desc'])
                    continue

                remove = parser.read_text(
                    'Base DN already exists. Overwrite (Yes/No/Quit)',
                    options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                    sign='?', allow_empty=False, case_sensitive=False).lower()

                if remove == 'q' or remove == 'quit':
                    print("Installation canceled.")
                    sys.exit(0)

                if remove == 'y' or remove == 'yes':
                    break

            print()

            print("Security Domain:")

            if deployer.subsystem_name == "CA":
                parser.read_text('Name',
                                 deployer.subsystem_name,
                                 'pki_security_domain_name')

            else:
                while True:
                    parser.read_text('Hostname',
                                     deployer.subsystem_name,
                                     'pki_security_domain_hostname')

                    parser.read_text('Secure HTTP port',
                                     deployer.subsystem_name,
                                     'pki_security_domain_https_port')

                    try:
                        parser.sd_connect()
                        info = parser.sd_get_info()
                        parser.print_text('Name: ' + info.name)
                        parser.set_property(deployer.subsystem_name,
                                            'pki_security_domain_name',
                                            info.name)
                        break
                    except RETRYABLE_EXCEPTIONS as e:
                        parser.print_text('ERROR: ' + str(e))

                while True:
                    parser.read_text('Username',
                                     deployer.subsystem_name,
                                     'pki_security_domain_user')
                    parser.read_password('Password',
                                         deployer.subsystem_name,
                                         'pki_security_domain_password')

                    try:
                        parser.sd_authenticate()
                        break
                    except requests.exceptions.HTTPError as e:
                        parser.print_text('ERROR: ' + str(e))

            print()

            if deployer.subsystem_name == "TPS":
                print("External Servers:")

                while True:
                    parser.read_text('CA URL',
                                     deployer.subsystem_name,
                                     'pki_ca_uri')
                    try:
                        status = parser.get_server_status('ca', 'pki_ca_uri')
                        if status == 'running':
                            break
                        parser.print_text('ERROR: CA is not running')
                    except RETRYABLE_EXCEPTIONS as e:
                        parser.print_text('ERROR: ' + str(e))

                while True:
                    parser.read_text('TKS URL',
                                     deployer.subsystem_name,
                                     'pki_tks_uri')
                    try:
                        status = parser.get_server_status('tks', 'pki_tks_uri')
                        if status == 'running':
                            break
                        parser.print_text('ERROR: TKS is not running')
                    except RETRYABLE_EXCEPTIONS as e:
                        parser.print_text('ERROR: ' + str(e))

                while True:
                    keygen = parser.read_text(
                        'Enable server side key generation (Yes/No)',
                        options=['Yes', 'Y', 'No', 'N'], default='N',
                        sign='?', case_sensitive=False).lower()

                    if keygen == 'y' or keygen == 'yes':
                        parser.set_property(deployer.subsystem_name,
                                            'pki_enable_server_side_keygen',
                                            'True')

                        parser.read_text('KRA URL',
                                         deployer.subsystem_name,
                                         'pki_kra_uri')
                        try:
                            status = parser.get_server_status(
                                'kra', 'pki_kra_uri')
                            if status == 'running':
                                break
                            parser.print_text('ERROR: KRA is not running')
                        except RETRYABLE_EXCEPTIONS as e:
                            parser.print_text('ERROR: ' + str(e))
                    else:
                        parser.set_property(deployer.subsystem_name,
                                            'pki_enable_server_side_keygen',
                                            'False')
                        break

                print()

                print("Authentication Database:")

                while True:
                    parser.read_text('Hostname',
                                     deployer.subsystem_name,
                                     'pki_authdb_hostname')
                    parser.read_text('Port',
                                     deployer.subsystem_name,
                                     'pki_authdb_port')
                    basedn = parser.read_text('Base DN', allow_empty=False)
                    parser.set_property(deployer.subsystem_name,
                                        'pki_authdb_basedn',
                                        basedn)

                    try:
                        parser.authdb_connect()
                        if parser.authdb_base_dn_exists():
                            break
                        else:
                            parser.print_text('ERROR: base DN does not exist')

                    except ldap.LDAPError as e:
                        parser.print_text('ERROR: ' + e.args[0]['desc'])

                print()

        if interactive:
            parser.indent = 0

            begin = parser.read_text(
                'Begin installation (Yes/No/Quit)',
                options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                sign='?', allow_empty=False, case_sensitive=False).lower()
            print()

            if begin == 'q' or begin == 'quit':
                print("Installation canceled.")
                sys.exit(0)

            if begin == 'y' or begin == 'yes':
                break

        else:
            break

    if not os.path.exists(config.PKI_DEPLOYMENT_SOURCE_ROOT +
                          "/" + deployer.subsystem_name.lower()):
        print("ERROR:  " + log.PKI_SUBSYSTEM_NOT_INSTALLED_1 %
              deployer.subsystem_name.lower())
        sys.exit(1)

    start_logging()

    # Read the specified PKI configuration file.
    rv = parser.read_pki_configuration_file()
    if rv != 0:
        config.pki_log.error(log.PKI_UNABLE_TO_PARSE_1, rv,
                             extra=config.PKI_INDENTATION_LEVEL_0)
        sys.exit(1)

    # --skip-configuration
    if args.skip_configuration:
        parser.set_property(deployer.subsystem_name,
                            'pki_skip_configuration', 'True')

    # --skip-installation
    if args.skip_installation:
        parser.set_property(deployer.subsystem_name,
                            'pki_skip_installation', 'True')

    create_master_dictionary(parser)

    if not interactive and \
            not config.str2bool(parser.mdict['pki_skip_configuration']):
        check_ds(parser)
        check_security_domain(parser)

    if args.precheck:
        print('pre-checks completed successfully.')
        sys.exit(0)

    print("Installing " + deployer.subsystem_name + " into " +
          parser.mdict['pki_instance_path'] + ".")

    # Process the various "scriptlets" to create the specified PKI subsystem.
    pki_subsystem_scriptlets = parser.mdict['spawn_scriplets'].split()
    deployer.init(parser)

    try:
        for scriptlet_name in pki_subsystem_scriptlets:

            scriptlet_module = __import__(
                "pki.server.deployment.scriptlets." + scriptlet_name,
                fromlist=[scriptlet_name])

            scriptlet = scriptlet_module.PkiScriptlet()

            scriptlet.spawn(deployer)

    except subprocess.CalledProcessError as e:
        log_error_details()
        print()
        print("Installation failed: Command failed: %s" % ' '.join(e.cmd))
        if e.output:
            print(e.output)
        print()
        print('Please check pkispawn logs in %s/%s' % (config.pki_log_dir, config.pki_log_name))
        sys.exit(1)

    except requests.HTTPError as e:
        r = e.response
        print()

        print('Installation failed:')
        if r.headers['content-type'] == 'application/json':
            data = r.json()
            print('%s: %s' % (data['ClassName'], data['Message']))
        else:
            print(r.text)

        print()
        print('Please check the %s logs in %s.' %
              (deployer.subsystem_name, deployer.mdict['pki_subsystem_log_path']))

        sys.exit(1)

    except Exception as e:  # pylint: disable=broad-except
        log_error_details()
        print()
        print("Installation failed: %s" % e)
        print()
        sys.exit(1)

    # ALWAYS archive configuration file and manifest file

    config.pki_log.info(
        log.PKI_ARCHIVE_CONFIG_MESSAGE_1,
        deployer.mdict['pki_user_deployment_cfg_spawn_archive'],
        extra=config.PKI_INDENTATION_LEVEL_1)

    # For debugging/auditing purposes, save a timestamped copy of
    # this configuration file in the subsystem archive
    deployer.file.copy(
        deployer.mdict['pki_user_deployment_cfg_replica'],
        deployer.mdict['pki_user_deployment_cfg_spawn_archive'])

    config.pki_log.info(
        log.PKI_ARCHIVE_MANIFEST_MESSAGE_1,
        deployer.mdict['pki_manifest_spawn_archive'],
        extra=config.PKI_INDENTATION_LEVEL_1)

    # for record in manifest.database:
    #     print tuple(record)

    manifest_file = manifest.File(deployer.manifest_db)
    manifest_file.register(deployer.mdict['pki_manifest'])
    manifest_file.write()

    deployer.file.modify(deployer.mdict['pki_manifest'], silent=True)

    # Also, for debugging/auditing purposes, save a timestamped copy of
    # this installation manifest file
    deployer.file.copy(
        deployer.mdict['pki_manifest'],
        deployer.mdict['pki_manifest_spawn_archive'])

    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 skip_configuration:
        print_skip_configuration_information(parser.mdict)

    elif (external or standalone) and step_one:
        if deployer.subsystem_name == 'CA':
            print_external_ca_step_one_information(parser.mdict)

        elif deployer.subsystem_name == 'KRA':
            print_kra_step_one_information(parser.mdict)

        else:  # OCSP
            print_ocsp_step_one_information(parser.mdict)

    else:
        print_final_install_information(parser.mdict)
Exemplo n.º 5
0
def main(argv):
    """main entry point"""

    config.pki_deployment_executable = os.path.basename(argv[0])

    # Set the umask
    os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK)

    # Read and process command-line arguments.
    parser = PKIConfigParser(
        'PKI Instance Removal',
        log.PKIDESTROY_EPILOG,
        deployer=deployer)

    parser.optional.add_argument(
        '-i',
        dest='pki_deployed_instance_name',
        action='store',
        nargs=1, metavar='<instance>',
        help='FORMAT:  ${pki_instance_name}')

    parser.optional.add_argument(
        '-u',
        dest='pki_secdomain_user',
        action='store',
        nargs=1, metavar='<security domain user>',
        help='security domain user')

    parser.optional.add_argument(
        '-W',
        dest='pki_secdomain_pass_file',
        action='store',
        nargs=1, metavar='<security domain password file>',
        help='security domain password file path')

    args = parser.process_command_line_arguments()

    interactive = False

    # Only run this program as "root".
    if not os.geteuid() == 0:
        sys.exit("'%s' must be run as root!" % argv[0])

    while True:

        # -s <subsystem>
        if args.pki_subsystem is None:
            interactive = True
            deployer.subsystem_name = parser.read_text(
                'Subsystem (CA/KRA/OCSP/TKS/TPS)',
                options=['CA', 'KRA', 'OCSP', 'TKS', 'TPS'],
                default='CA', case_sensitive=False).upper()
        else:
            deployer.subsystem_name = str(args.pki_subsystem).strip('[\']')

        # -i <instance name>
        if args.pki_deployed_instance_name is None:
            interactive = True
            config.pki_deployed_instance_name = \
                parser.read_text('Instance', default='pki-tomcat')
        else:
            config.pki_deployed_instance_name = \
                str(args.pki_deployed_instance_name).strip('[\']')

        if interactive:
            print()
            parser.indent = 0

            begin = parser.read_text(
                'Begin uninstallation (Yes/No/Quit)',
                options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'],
                sign='?', allow_empty=False, case_sensitive=False).lower()

            print()

            if begin == 'q' or begin == 'quit':
                print("Uninstallation canceled.")
                sys.exit(0)

            elif begin == 'y' or begin == 'yes':
                break

        else:
            break

    #    '-u'
    if args.pki_secdomain_user:
        config.pki_secdomain_user = str(args.pki_secdomain_user).strip('[\']')

    #    '-W' password file
    if args.pki_secdomain_pass_file:
        with open(str(args.pki_secdomain_pass_file).strip('[\']'), 'r') as \
                pwd_file:
            config.pki_secdomain_pass = pwd_file.readline().strip('\n')

    # verify that previously deployed instance exists
    deployed_pki_instance_path = os.path.join(
        config.PKI_DEPLOYMENT_BASE_ROOT, config.pki_deployed_instance_name
    )
    if not os.path.exists(deployed_pki_instance_path):
        print("ERROR:  " + log.PKI_INSTANCE_DOES_NOT_EXIST_1 %
              deployed_pki_instance_path)
        print()
        parser.arg_parser.exit(-1)

    # verify that previously deployed subsystem for this instance exists
    deployed_pki_subsystem_path = \
        deployed_pki_instance_path + "/" + deployer.subsystem_name.lower()
    if not os.path.exists(deployed_pki_subsystem_path):
        print("ERROR:  " + log.PKI_SUBSYSTEM_DOES_NOT_EXIST_2 %
              (deployer.subsystem_name, deployed_pki_instance_path))
        print()
        parser.arg_parser.exit(-1)

    config.default_deployment_cfg = \
        config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE

    # establish complete path to previously deployed configuration file
    config.user_deployment_cfg =\
        deployed_pki_subsystem_path + "/" +\
        "registry" + "/" +\
        deployer.subsystem_name.lower() + "/" +\
        config.USER_DEPLOYMENT_CONFIGURATION

    parser.validate()
    parser.init_config()

    # Enable 'pkidestroy' logging.
    config.pki_log_dir = config.PKI_DEPLOYMENT_LOG_ROOT
    config.pki_log_name = "pki" + "-" +\
                          deployer.subsystem_name.lower() +\
                          "-" + "destroy" + "." +\
                          deployer.log_timestamp + "." + "log"
    print('Log file: %s/%s' % (config.pki_log_dir, config.pki_log_name))

    pkilogging.enable_pki_logger(config.pki_log_dir,
                                 config.pki_log_name,
                                 config.pki_log_level,
                                 config.pki_console_log_level,
                                 "pkidestroy")

    # Read the specified PKI configuration file.
    rv = parser.read_pki_configuration_file()
    if rv != 0:
        config.pki_log.error(log.PKI_UNABLE_TO_PARSE_1, rv,
                             extra=config.PKI_INDENTATION_LEVEL_0)
        sys.exit(1)

    # Combine the various sectional dictionaries into a PKI master dictionary
    parser.compose_pki_master_dictionary()
    parser.mdict['pki_destroy_log'] = \
        config.pki_log_dir + "/" + config.pki_log_name
    config.pki_log.debug(log.PKI_DICTIONARY_MASTER,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.log_format(parser.mdict),
                         extra=config.PKI_INDENTATION_LEVEL_0)

    print("Uninstalling " + deployer.subsystem_name + " from " +
          deployed_pki_instance_path + ".")

    # Process the various "scriptlets" to remove the specified PKI subsystem.
    pki_subsystem_scriptlets = parser.mdict['destroy_scriplets'].split()
    deployer.init(parser)

    try:
        for scriptlet_name in pki_subsystem_scriptlets:

            scriptlet_module = __import__(
                "pki.server.deployment.scriptlets." + scriptlet_name,
                fromlist=[scriptlet_name])

            scriptlet = scriptlet_module.PkiScriptlet()

            scriptlet.destroy(deployer)

    except subprocess.CalledProcessError as e:
        log_error_details()
        print()
        print("Uninstallation failed: Command failed: %s" % ' '.join(e.cmd))
        if e.output:
            print(e.output)
        print()
        sys.exit(1)

    except Exception as e:  # pylint: disable=broad-except
        log_error_details()
        print()
        print("Uninstallation failed: %s" % e)
        print()
        sys.exit(1)

    print()
    print("Uninstallation complete.")