Пример #1
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        password = None

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

            elif o == '--password':
                password = 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:
                print('ERROR: Unknown option: %s' % o)
                self.print_help()
                sys.exit(1)

        if len(args) < 1:
            raise Exception('Missing password ID')

        name = args[0]

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

        if not instance.exists():
            raise Exception('Invalid instance: %s' % instance_name)

        instance.load()

        if name in instance.passwords:
            raise Exception('Password already exists: %s' % name)

        instance.passwords[name] = password
        instance.store_passwords()
Пример #2
0
    def spawn(self, deployer):

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

        logger.info('Preparing %s instance', deployer.mdict['pki_instance_name'])

        instance = self.instance
        instance.load()

        instance_conf_path = deployer.mdict['pki_instance_configuration_path']

        logger.info('Creating %s', instance_conf_path)
        instance.makedirs(instance_conf_path, force=True)

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

        # Configuring internal token password

        internal_token = deployer.mdict['pki_self_signed_token']
        if not pki.nssdb.normalize_token(internal_token):
            internal_token = pki.nssdb.INTERNAL_TOKEN_NAME

        # If instance already exists and has password, reuse the password
        if internal_token in instance.passwords:
            logger.info('Reusing server NSS database password')
            deployer.mdict['pki_server_database_password'] = instance.passwords.get(internal_token)

        # Otherwise, use user-provided password if specified
        elif deployer.mdict['pki_server_database_password']:
            logger.info('Using specified server NSS database password')

        # Otherwise, use user-provided pin if specified
        elif deployer.mdict['pki_pin']:
            logger.info('Using specified PIN as server NSS database password')
            deployer.mdict['pki_server_database_password'] = deployer.mdict['pki_pin']

        # Otherwise, generate a random password
        else:
            logger.info('Generating random server NSS database password')
            deployer.mdict['pki_server_database_password'] = pki.generate_password()

        instance.passwords[internal_token] = deployer.mdict['pki_server_database_password']

        # Configuring HSM password

        if config.str2bool(deployer.mdict['pki_hsm_enable']):
            hsm_token = deployer.mdict['pki_token_name']
            instance.passwords['hardware-%s' % hsm_token] = deployer.mdict['pki_token_password']

        # Configuring internal database password

        if 'internaldb' in instance.passwords:
            logger.info('Reusing internal database password')
            deployer.mdict['pki_ds_password'] = instance.passwords.get('internaldb')

        else:
            logger.info('Using specified internal database password')

        instance.passwords['internaldb'] = deployer.mdict['pki_ds_password']

        # Configuring replication manager password
        # Bug #430745 Create separate password for replication manager
        # Use user-provided password if specified

        if 'replicationdb' in instance.passwords:
            logger.info('Reusing replication manager password')

        elif deployer.mdict['pki_replication_password']:
            logger.info('Using specified replication manager password')
            instance.passwords['replicationdb'] = deployer.mdict['pki_replication_password']

        else:
            logger.info('Generating random replication manager password')
            instance.passwords['replicationdb'] = pki.generate_password()

        instance.store_passwords()

        # if this is not the first subsystem, skip
        if len(deployer.instance.tomcat_instance_subsystems()) != 1:
            logger.info('Installing %s instance', deployer.mdict['pki_instance_name'])
            return

        deployer.directory.create(deployer.mdict['pki_instance_log_path'])

        shared_conf_path = deployer.mdict['pki_source_server_path']

        # Copy /usr/share/pki/server/conf/tomcat.conf to
        # /var/lib/pki/<instance>/conf/tomcat.conf.
        deployer.file.copy_with_slot_substitution(
            os.path.join(shared_conf_path, 'tomcat.conf'),
            os.path.join(instance_conf_path, 'tomcat.conf'))

        # Copy /usr/share/pki/server/conf/server.xml
        # to /etc/pki/<instance>/server.xml.
        deployer.file.copy_with_slot_substitution(
            deployer.mdict['pki_source_server_xml'],
            deployer.mdict['pki_target_server_xml'],
            overwrite_flag=True)

        # Link /etc/pki/<instance>/catalina.properties
        # to /usr/share/pki/server/conf/catalina.properties.
        logger.info('Creating %s', os.path.join(instance_conf_path, 'catalina.properties'))
        instance.symlink(
            os.path.join(shared_conf_path, 'catalina.properties'),
            os.path.join(instance_conf_path, 'catalina.properties'),
            force=True)

        # Link /etc/pki/<instance>/context.xml
        # to /usr/share/tomcat/conf/context.xml.
        logger.info('Creating %s', instance.context_xml)
        context_xml = os.path.join(pki.server.Tomcat.CONF_DIR, 'context.xml')
        instance.symlink(context_xml, instance.context_xml, force=True)

        # Link /etc/pki/<instance>/logging.properties
        # to /usr/share/pki/server/conf/logging.properties.
        logger.info('Creating %s', os.path.join(instance_conf_path, 'logging.properties'))
        instance.symlink(
            os.path.join(shared_conf_path, 'logging.properties'),
            os.path.join(instance_conf_path, 'logging.properties'),
            force=True)

        # create /etc/sysconfig/<instance>
        deployer.file.copy_with_slot_substitution(
            deployer.mdict['pki_source_tomcat_conf'],
            deployer.mdict['pki_target_tomcat_conf_instance_id'],
            overwrite_flag=True)

        # create /var/lib/pki/<instance>/conf/tomcat.conf
        deployer.file.copy_with_slot_substitution(
            deployer.mdict['pki_source_tomcat_conf'],
            deployer.mdict['pki_target_tomcat_conf'],
            overwrite_flag=True)

        # Link /etc/pki/<instance>/web.xml
        # to /usr/share/tomcat/conf/web.xml.
        logger.info('Creating %s', instance.web_xml)
        web_xml = os.path.join(pki.server.Tomcat.CONF_DIR, 'web.xml')
        instance.symlink(web_xml, instance.web_xml, force=True)

        catalina_dir = os.path.join(instance_conf_path, 'Catalina')
        logger.info('Creating %s', catalina_dir)
        instance.makedirs(catalina_dir, force=True)

        localhost_dir = os.path.join(catalina_dir, 'localhost')
        logger.info('Creating %s', localhost_dir)
        instance.makedirs(localhost_dir, force=True)

        logger.info('Deploying ROOT web application')
        instance.deploy_webapp(
            "ROOT",
            os.path.join(
                shared_conf_path,
                "Catalina",
                "localhost",
                "ROOT.xml"))

        logger.info('Deploying /pki web application')
        # Deploy pki web application which includes themes,
        # admin templates, and JS libraries
        instance.deploy_webapp(
            "pki",
            os.path.join(
                shared_conf_path,
                "Catalina",
                "localhost",
                "pki.xml"))

        instance.with_maven_deps = deployer.with_maven_deps
        instance.create_libs(force=True)

        deployer.directory.create(deployer.mdict['pki_tomcat_tmpdir_path'])

        deployer.directory.create(deployer.mdict['pki_tomcat_work_path'])
        deployer.directory.create(deployer.mdict['pki_tomcat_work_catalina_path'])
        deployer.directory.create(deployer.mdict['pki_tomcat_work_catalina_host_path'])
        deployer.directory.create(deployer.mdict['pki_tomcat_work_catalina_host_run_path'])
        deployer.directory.create(deployer.mdict['pki_tomcat_work_catalina_host_subsystem_path'])

        # establish Tomcat instance logs
        # establish Tomcat instance registry
        # establish Tomcat instance convenience symbolic links

        deployer.symlink.create(
            deployer.mdict['pki_tomcat_bin_path'],
            deployer.mdict['pki_tomcat_bin_link'])

        # create systemd links
        deployer.symlink.create(
            deployer.mdict['pki_tomcat_systemd'],
            deployer.mdict['pki_instance_systemd_link'],
            uid=0, gid=0)

        user = deployer.mdict['pki_user']
        group = deployer.mdict['pki_group']
        if user != 'pkiuser' or group != 'pkiuser':
            deployer.systemd.set_override(
                'Service', 'User', user, 'user.conf')
            deployer.systemd.set_override(
                'Service', 'Group', group, 'user.conf')
        deployer.systemd.write_overrides()
        deployer.systemd.daemon_reload()

        deployer.symlink.create(
            instance_conf_path,
            deployer.mdict['pki_instance_conf_link'])

        deployer.symlink.create(
            deployer.mdict['pki_instance_log_path'],
            deployer.mdict['pki_instance_logs_link'])

        # create Tomcat instance systemd service link
        deployer.symlink.create(deployer.mdict['pki_systemd_service'],
                                deployer.mdict['pki_systemd_service_link'])

        # create instance registry
        deployer.file.copy_with_slot_substitution(
            deployer.mdict['pki_source_registry'],
            os.path.join(deployer.mdict['pki_instance_registry_path'],
                         deployer.mdict['pki_instance_name']),
            overwrite_flag=True)
Пример #3
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        no_password = False
        password = None
        password_file = None
        force = False

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

            elif o == '--no-password':
                no_password = True

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

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

            elif o == '--force':
                force = True

            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:
                print('ERROR: unknown option: %s' % o)
                self.print_help()
                sys.exit(1)

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

        if not instance.exists():
            raise Exception('Invalid instance: %s' % instance_name)

        instance.load()

        if no_password:
            password = ''

        elif password is not None:
            pass

        elif password_file is not None:
            with open(password_file) as f:
                password = f.read().splitlines()[0]

        else:
            password = getpass.getpass(
                prompt='Enter password for NSS database: ')

        instance.passwords['internal'] = password
        instance.store_passwords()

        instance.create_nssdb(force=force)
Пример #4
0
Файл: cert.py Проект: tiran/pki
def ldap_password_authn(
        instance, subsystems, bind_dn, ldap_url, use_ldapi, dm_pass_file):
    """LDAP password authentication context.

    This context manager switches the server to password
    authentication, runs the block, then restores the original
    subsystem configuration.

    Specifically:

    - if we are already using BasicAuth, force port 389 and no TLS/STARTTLS
      but leave everything else alone.

    - if using TLS client cert auth, switch to BasicAuth, using pkidbuser
      account, and using a randomly generated password.  The DM credential
      is required to set that password.

    This context manager yields the pkidbuser DN, so that the new
    subsystem certificate (if it was one of the renewal targets) can
    be added to the entry.  It is only yielded if the server was
    already using TLS client cert authn, otherwise the yielded value
    is ``None``.

    """
    logger.info('Configuring LDAP password authentication')
    orig = {}
    try:
        password = instance.passwords['internaldb']
    except KeyError:
        # generate a new password and write it to file
        password = gen_random_password()
        instance.passwords['internaldb'] = password
        instance.store_passwords()
        generated_password = True
    else:
        generated_password = False

    # We don't perform ldappasswd unless we need to (and only once).
    ldappasswd_performed = False

    for subsystem in subsystems:
        cfg = subsystem.get_db_config()
        orig[subsystem] = cfg.copy()  # copy because dict is mutable

        authtype = cfg['internaldb.ldapauth.authtype']
        if authtype == 'SslClientAuth':
            # switch to BasicAuth
            cfg['internaldb.ldapauth.authtype'] = 'BasicAuth'
            cfg['internaldb.ldapconn.port'] = '389'
            cfg['internaldb.ldapconn.secureConn'] = 'false'
            cfg['internaldb.ldapauth.bindDN'] = bind_dn

            # _now_ we can perform ldappasswd
            if not ldappasswd_performed:
                logger.info('Setting pkidbuser password via ldappasswd')
                with write_temp_file(password.encode('utf8')) as pwdfile:
                    ldappasswd(ldap_url, use_ldapi, dm_pass_file, bind_dn, pwdfile)
                ldappasswd_performed = True

        elif authtype == 'BasicAuth':
            # force port 389, no TLS / STARTTLS.  Leave other settings alone.
            cfg['internaldb.ldapconn.port'] = '389'
            cfg['internaldb.ldapconn.secureConn'] = 'false'

        subsystem.set_db_config(cfg)
        subsystem.save()

    try:
        yield

    finally:
        logger.info('Restoring previous LDAP configuration')

        for subsystem, cfg in orig.items():
            subsystem.set_db_config(cfg)
            subsystem.save()

        if generated_password:
            del instance.passwords['internaldb']
            instance.store_passwords()