コード例 #1
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)
コード例 #2
0
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'type=', 'nss-database-dir=',
                'nss-password-file=', 'keystore-file=',
                'keystore-password-file=', 'server-cert-nickname-file=',
                'port=', 'protocol=', 'scheme=', 'secure=', 'sslEnabled=',
                'sslImpl=', 'verbose', 'debug', 'help'
            ])

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

        instance_name = 'pki-tomcat'
        connector_type = None
        nss_database_dir = None
        nss_password_file = None
        keystore_file = None
        keystore_password_file = None
        server_cert_nickname_file = None
        port = None
        protocol = None
        scheme = None
        secure = None
        sslEnabled = None
        sslImpl = None

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

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

            elif o == '--nss-database-dir':
                nss_database_dir = a

            elif o == '--nss-password-file':
                nss_password_file = a

            elif o == '--keystore-file':
                keystore_file = a

            elif o == '--keystore-password-file':
                keystore_password_file = a

            elif o == '--server-cert-nickname-file':
                server_cert_nickname_file = a

            elif o == '--port':
                port = a

            elif o == '--protocol':
                protocol = a

            elif o == '--scheme':
                scheme = a

            elif o == '--secure':
                secure = a

            elif o == '--sslEnabled':
                sslEnabled = a

            elif o == '--sslImpl':
                sslImpl = 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:
            print('ERROR: Missing connector ID')
            self.print_help()
            sys.exit(1)

        name = args[0]

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

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

        instance.load()

        server_config = instance.get_server_config()
        connector = server_config.get_connector(name)

        if connector_type == 'JSS':

            connector.set('protocol',
                          'org.apache.coyote.http11.Http11Protocol')

            connector.set('sslImplementationName',
                          'org.apache.tomcat.util.net.jss.JSSImplementation')

            connector.attrib.pop('keystoreType', None)
            connector.attrib.pop('keystoreFile', None)
            connector.attrib.pop('keystorePassFile', None)
            connector.attrib.pop('keyAlias', None)

            connector.attrib.pop('trustManagerClassName', None)

            HTTPConnectorCLI.set_param(connector, 'certdbDir',
                                       nss_database_dir)
            HTTPConnectorCLI.set_param(
                connector, 'passwordClass',
                'org.apache.tomcat.util.net.jss.PlainPasswordFile')
            HTTPConnectorCLI.set_param(connector, 'passwordFile',
                                       nss_password_file)
            HTTPConnectorCLI.set_param(connector, 'serverCertNickFile',
                                       server_cert_nickname_file)

        elif connector_type == 'JSSE':

            connector.set('protocol', 'org.dogtagpki.tomcat.Http11NioProtocol')

            connector.attrib.pop('sslImplementationName', None)

            HTTPConnectorCLI.set_param(connector, 'keystoreType', 'pkcs12')
            HTTPConnectorCLI.set_param(connector, 'keystoreFile',
                                       keystore_file)
            HTTPConnectorCLI.set_param(connector, 'keystorePassFile',
                                       keystore_password_file)
            HTTPConnectorCLI.set_param(connector, 'keyAlias', 'sslserver')

            HTTPConnectorCLI.set_param(connector, 'trustManagerClassName',
                                       'org.dogtagpki.tomcat.PKITrustManager')

            HTTPConnectorCLI.set_param(connector, 'certdbDir',
                                       nss_database_dir)
            HTTPConnectorCLI.set_param(
                connector, 'passwordClass',
                'org.apache.tomcat.util.net.jss.PlainPasswordFile')
            HTTPConnectorCLI.set_param(connector, 'passwordFile',
                                       nss_password_file)
            HTTPConnectorCLI.set_param(connector, 'serverCertNickFile',
                                       server_cert_nickname_file)

        else:

            HTTPConnectorCLI.set_param(connector, 'port', port)
            HTTPConnectorCLI.set_param(connector, 'protocol', protocol)
            HTTPConnectorCLI.set_param(connector, 'scheme', scheme)
            HTTPConnectorCLI.set_param(connector, 'secure', secure)
            HTTPConnectorCLI.set_param(connector, 'SSLEnabled', sslEnabled)
            HTTPConnectorCLI.set_param(connector, 'sslImplementationName',
                                       sslImpl)

        server_config.save()

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

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

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

        name = 'acme'
        instance_name = 'pki-tomcat'
        force = False

        for o, a in opts:
            if o in ('-i', '--instance'):
                instance_name = 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:
                logger.error('Unknown option: %s', o)
                self.print_help()
                sys.exit(1)

        if len(args) > 0:
            name = args[0]

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

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

        instance.load()

        acme_conf_dir = os.path.join(instance.conf_dir, name)
        logger.info('Creating %s', acme_conf_dir)
        instance.makedirs(acme_conf_dir, force=force)

        acme_share_dir = os.path.join(pki.server.PKIServer.SHARE_DIR, 'acme')

        metadata_template = os.path.join(acme_share_dir, 'conf',
                                         'metadata.conf')
        metadata_conf = os.path.join(acme_conf_dir, 'metadata.conf')
        logger.info('Creating %s', metadata_conf)
        instance.copy(metadata_template, metadata_conf, force=force)

        database_template = os.path.join(acme_share_dir, 'conf',
                                         'database.conf')
        database_conf = os.path.join(acme_conf_dir, 'database.conf')
        logger.info('Creating %s', database_conf)
        instance.copy(database_template, database_conf, force=force)

        issuer_template = os.path.join(acme_share_dir, 'conf', 'issuer.conf')
        issuer_conf = os.path.join(acme_conf_dir, 'issuer.conf')
        logger.info('Creating %s', issuer_conf)
        instance.copy(issuer_template, issuer_conf, force=force)
コード例 #5
0
ファイル: acme.py プロジェクト: tiran/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 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('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()

        acme_conf_dir = os.path.join(instance.conf_dir, 'acme')
        issuer_conf = os.path.join(acme_conf_dir, 'issuer.conf')
        config = {}

        logger.info('Loading %s', issuer_conf)
        pki.util.load_properties(issuer_conf, config)

        print('The current value is displayed in the square brackets.')
        print('To keep the current value, simply press Enter.')
        print('To change the current value, enter the new value.')
        print('To remove the current value, enter a blank space.')

        issuer_class = config.get('class')

        print()
        print('Enter the type of the certificate issuer. '
              'Available types: %s.' % ', '.join(ISSUER_TYPES.values()))
        issuer_type = ISSUER_TYPES.get(issuer_class)
        issuer_type = pki.util.read_text('  Issuer Type',
                                         options=ISSUER_TYPES.values(),
                                         default=issuer_type,
                                         required=True)
        pki.util.set_property(config, 'class', ISSUER_CLASSES.get(issuer_type))

        if issuer_type == 'nss':

            print()
            print('Enter the nickname of the signing certificate.')
            nickname = config.get('nickname')
            nickname = pki.util.read_text('  Signing Certificate',
                                          default=nickname)
            pki.util.set_property(config, 'nickname', nickname)

            print()
            print('Enter the certificate extension configuration.')
            extensions = config.get('extensions')
            extensions = pki.util.read_text('  Certificate Extensions',
                                            default=extensions)
            pki.util.set_property(config, 'extensions', extensions)

        elif issuer_type == 'pki':

            print()
            print('Enter the location of the PKI server.')
            url = config.get('url')
            url = pki.util.read_text('  Server URL',
                                     default=url,
                                     required=True)
            pki.util.set_property(config, 'url', url)

            print()
            print('Enter the certificate nickname for client authentication.')
            print('This might be the CA agent certificate.')
            print('Enter blank to use basic authentication.')
            nickname = config.get('nickname')
            nickname = pki.util.read_text('  Client Certificate',
                                          default=nickname)
            pki.util.set_property(config, 'nickname', nickname)

            print()
            print(
                'Enter the username of the CA agent for basic authentication.')
            print(
                'Enter blank if a CA agent certificate is used for client authentication.'
            )
            username = config.get('username')
            username = pki.util.read_text('  Agent Username', default=username)
            pki.util.set_property(config, 'username', username)

            print()
            print('Enter the CA agent password for basic authentication.')
            print(
                'Enter blank if the password is already stored in a separate property file'
            )
            print(
                'or if a CA agent certificate is used for client authentication.'
            )
            password = config.get('password')
            password = pki.util.read_text('  Agent Password',
                                          default=password,
                                          password=True)
            pki.util.set_property(config, 'password', password)

            if password:
                config.pop('passwordFile', None)
            else:
                print()
                print(
                    'Enter the property file that stores the CA agent password.'
                )
                print(
                    'The password must be stored under acmeUserPassword property.'
                )
                password_file = config.get('passwordFile')
                password_file = pki.util.read_text('  Password File',
                                                   default=password_file)
                pki.util.set_property(config, 'passwordFile', password_file)

            print()
            print(
                'Enter the certificate profile for issuing ACME certificates.')
            profile = config.get('profile')
            profile = pki.util.read_text('  Certificate Profile',
                                         default=profile,
                                         required=True)
            pki.util.set_property(config, 'profile', profile)

        pki.util.store_properties(issuer_conf, config)
コード例 #6
0
ファイル: acme.py プロジェクト: tiran/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 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('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()

        acme_conf_dir = os.path.join(instance.conf_dir, 'acme')
        metadata_conf = os.path.join(acme_conf_dir, 'metadata.conf')
        config = {}

        logger.info('Loading %s', metadata_conf)
        pki.util.load_properties(metadata_conf, config)

        terms_of_service = config.get('termsOfService')
        if terms_of_service:
            print('  Terms of Service: %s' % terms_of_service)

        website = config.get('website')
        if website:
            print('  Website: %s' % website)

        caa_identities = config.get('caaIdentities')
        if caa_identities:
            print('  CAA Identities: %s' % caa_identities)

        external_account_required = config.get('externalAccountRequired')
        if external_account_required:
            print('  External Account Required: %s' %
                  external_account_required)
コード例 #7
0
ファイル: acme.py プロジェクト: tiran/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 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('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()

        acme_conf_dir = os.path.join(instance.conf_dir, 'acme')
        database_conf = os.path.join(acme_conf_dir, 'database.conf')
        config = {}

        logger.info('Loading %s', database_conf)
        pki.util.load_properties(database_conf, config)

        database_class = config.get('class')

        database_type = DATABASE_TYPES.get(database_class)
        print('  Database Type: %s' % database_type)

        if database_type == 'ldap':

            hostname = config.get('internaldb.ldapconn.host')
            if hostname:
                print('  Hostname: %s' % hostname)

            port = config.get('internaldb.ldapconn.port')
            if port:
                print('  Port: %s' % port)

            secure_connection = config.get('internaldb.ldapconn.secureConn')
            if secure_connection:
                print('  Secure Connection: %s' % secure_connection)

            auth_type = config.get('internaldb.ldapauth.authtype')
            if auth_type:
                print('  Authentication Type: %s' % auth_type)

            if auth_type == 'BasicAuth':

                bind_dn = config.get('internaldb.ldapauth.bindDN')
                if bind_dn:
                    print('  Bind DN: %s' % bind_dn)

                password_name = config.get('internaldb.ldapauth.bindPWPrompt')
                if password_name:
                    print('  Password Name: %s' % password_name)

                password = config.get('password.%s' % password_name)
                if password:
                    print('  Password for %s: ********' % password_name)

            elif auth_type == 'SslClientAuth':

                nickname = config.get('internaldb.ldapauth.clientCertNickname')
                if nickname:
                    print('  Client Certificate: %s' % nickname)

            base_dn = config.get('basedn')
            if base_dn:
                print('  Base DN: %s' % base_dn)

        elif database_type == 'postgresql':

            url = config.get('url')
            if url:
                print('  Server URL: %s' % url)

            username = config.get('user')
            if username:
                print('  Username: %s' % username)

            password = config.get('password')
            if password:
                print('  Password: ********')
コード例 #8
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)
コード例 #9
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)
コード例 #10
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'))
コード例 #11
0
ファイル: banner.py プロジェクト: zdzichu/pki
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        banner_file = None
        silent = False

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

            elif o == '--file':
                banner_file = a

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

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

            elif o == '--silent':
                silent = True

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

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

        try:
            if banner_file:
                # load banner from file
                with io.open(banner_file) as f:
                    banner = f.read().strip()
            else:

                # load banner from instance
                instance = pki.server.instance.PKIServerFactory.create(
                    instance_name)

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

                instance.load()

                if not instance.banner_installed():
                    if not silent:
                        self.print_message('Banner is not installed')
                    return

                banner = instance.get_banner()

        except UnicodeDecodeError as e:
            if logger.isEnabledFor(logging.DEBUG):
                logger.exception('Banner contains invalid character(s): %s', e)
            else:
                logger.error('Banner contains invalid character(s): %s', e)
            sys.exit(1)

        if not banner:
            logger.error('Banner is empty')
            sys.exit(1)

        if not silent:
            self.print_message('Banner is valid')
コード例 #12
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)
コード例 #13
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()
コード例 #14
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        sslProtocol = None
        certVerification = None
        trustManager = None

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

            elif o == '--sslProtocol':
                sslProtocol = a

            elif o == '--certVerification':
                certVerification = a

            elif o == '--trustManager':
                trustManager = 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 connector ID')

        connector_name = args[0]

        if len(args) < 2:
            raise Exception('Missing hostname')

        hostname = args[1]

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

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

        instance.load()

        server_config = instance.get_server_config()
        connector = server_config.get_connector(connector_name)

        try:
            server_config.get_sslhost(connector, hostname)
            raise Exception('SSL host already exists: %s' % hostname)
        except KeyError:
            pass

        sslhost = server_config.create_sslhost(connector, hostname)

        HTTPConnectorCLI.set_param(sslhost, 'sslProtocol', sslProtocol)
        HTTPConnectorCLI.set_param(sslhost, 'certificateVerification',
                                   certVerification)
        HTTPConnectorCLI.set_param(sslhost, 'trustManagerClassName',
                                   trustManager)

        server_config.save()

        SSLHostCLI.print_sslhost(sslhost)
コード例 #15
0
ファイル: db.py プロジェクト: edewata/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:D:w:v', [
                'instance=', 'bind-dn=', 'bind-password='******'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 ('-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()

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

        if not bind_password:
            bind_password = getpass.getpass(prompt='Enter password: '******'Unable to update schema: %s', e)
            raise e

        self.print_message('Upgrade complete')
コード例 #16
0
ファイル: instance.py プロジェクト: edewata/pki
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', '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)

        nicknames = args

        instance_name = 'pki-tomcat'
        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 == '--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 not pkcs12_file:
            logger.error('missing output file')
            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()

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

        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()
コード例 #17
0
ファイル: instance_layout.py プロジェクト: tstellar/pki
    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 = pki.server.instance.PKIInstance(deployer.mdict['pki_instance_name'])
        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 password config %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

        # establish instance logs
        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'))

        logger.info('Creating %s', deployer.mdict['pki_target_server_xml'])
        # 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.
        instance.symlink(
            os.path.join(shared_conf_path, 'catalina.properties'),
            os.path.join(instance_conf_path, 'catalina.properties'),
            force=True)

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

        # Link /etc/pki/<instance>/context.xml
        # to /usr/share/tomcat/conf/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.
        instance.symlink(
            os.path.join(shared_conf_path, 'logging.properties'),
            os.path.join(instance_conf_path, 'logging.properties'),
            force=True)

        logger.info('Creating %s', deployer.mdict['pki_target_tomcat_conf_instance_id'])
        # 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)

        logger.info('Creating %s', deployer.mdict['pki_target_tomcat_conf'])
        # 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.
        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'])

        logger.info('Creating %s', deployer.mdict['pki_instance_systemd_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)
コード例 #18
0
ファイル: instance.py プロジェクト: edewata/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'cert-file=', 'trust-args=', 'nickname=',
                'token=', 'verbose', 'debug', 'help'
            ])

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

        instance_name = 'pki-tomcat'
        cert_file = None
        trust_args = '\",,\"'
        nickname = None
        token = pki.nssdb.INTERNAL_TOKEN_NAME

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

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

            elif o == '--trust-args':
                trust_args = a

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

            elif o == '--token':
                token = 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 not cert_file:
            logger.error('Missing input file containing certificate')
            self.print_help()
            sys.exit(1)

        if not nickname:
            logger.error('Missing nickname')
            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()

        if instance.external_cert_exists(nickname, token):
            logger.error('Certificate already imported for instance %s.',
                         instance_name)
            sys.exit(1)

        nicks = self.import_certs(instance, cert_file, nickname, token,
                                  trust_args)
        self.update_instance_config(instance, nicks, token)

        self.print_message('Certificate imported for instance %s.' %
                           instance_name)
コード例 #19
0
ファイル: acme.py プロジェクト: tiran/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 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('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()

        acme_conf_dir = os.path.join(instance.conf_dir, 'acme')
        metadata_conf = os.path.join(acme_conf_dir, 'metadata.conf')
        config = {}

        logger.info('Loading %s', metadata_conf)
        pki.util.load_properties(metadata_conf, config)

        print('The current value is displayed in the square brackets.')
        print('To keep the current value, simply press Enter.')
        print('To change the current value, enter the new value.')
        print('To remove the current value, enter a blank space.')

        print()
        print('Enter the location of the terms of service.')
        terms_of_service = config.get('termsOfService')
        terms_of_service = pki.util.read_text('  Terms of Service',
                                              default=terms_of_service)
        pki.util.set_property(config, 'termsOfService', terms_of_service)

        print()
        print('Enter the location of the website.')
        website = config.get('website')
        website = pki.util.read_text('  Website', default=website)
        pki.util.set_property(config, 'website', website)

        print()
        print('Enter the CAA identities.')
        caa_identities = config.get('caaIdentities')
        caa_identities = pki.util.read_text('  CAA Identities',
                                            default=caa_identities)
        pki.util.set_property(config, 'caaIdentities', caa_identities)

        print()
        print('Enter true/false whether an external account is required.')
        external_account_required = config.get('externalAccountRequired')
        external_account_required = pki.util.read_text(
            '  External Account Required', default=external_account_required)
        pki.util.set_property(config, 'externalAccountRequired',
                              external_account_required)

        pki.util.store_properties(metadata_conf, config)
コード例 #20
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()
コード例 #21
0
ファイル: acme.py プロジェクト: tiran/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 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('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()

        acme_conf_dir = os.path.join(instance.conf_dir, 'acme')
        database_conf = os.path.join(acme_conf_dir, 'database.conf')
        config = {}

        logger.info('Loading %s', database_conf)
        pki.util.load_properties(database_conf, config)

        print('The current value is displayed in the square brackets.')
        print('To keep the current value, simply press Enter.')
        print('To change the current value, enter the new value.')
        print('To remove the current value, enter a blank space.')

        database_class = config.get('class')

        print()
        print('Enter the type of the database. '
              'Available types: %s.' % ', '.join(DATABASE_TYPES.values()))
        database_type = DATABASE_TYPES.get(database_class)
        database_type = pki.util.read_text('  Database Type',
                                           options=DATABASE_TYPES.values(),
                                           default=database_type,
                                           required=True)
        pki.util.set_property(config, 'class',
                              DATABASE_CLASSES.get(database_type))

        if database_type == 'in-memory':
            config.pop('url', None)
            config.pop('user', None)
            config.pop('password', None)

        elif database_type == 'ldap':

            print()
            print('Enter the server hostname.')
            hostname = config.get('internaldb.ldapconn.host')
            hostname = pki.util.read_text('  Hostname',
                                          default=hostname,
                                          required=True)
            pki.util.set_property(config, 'internaldb.ldapconn.host', hostname)

            print()
            print('Enter the server port.')
            port = config.get('internaldb.ldapconn.port')
            port = pki.util.read_text('  Port', default=port, required=True)
            pki.util.set_property(config, 'internaldb.ldapconn.port', port)

            print()
            print('Enter true for secure connection, and false otherwise.')
            secure_connection = config.get('internaldb.ldapconn.secureConn')
            secure_connection = pki.util.read_text('  Secure Connection',
                                                   options=['true', 'false'],
                                                   default=secure_connection,
                                                   required=True)
            pki.util.set_property(config, 'internaldb.ldapconn.secureConn',
                                  secure_connection)

            print()
            print(
                'Enter the authentication type. Available types: BasicAuth, SslClientAuth.'
            )
            auth_type = config.get('internaldb.ldapauth.authtype')
            auth_type = pki.util.read_text(
                '  Authentication Type',
                options=['BasicAuth', 'SslClientAuth'],
                default=auth_type,
                required=True)
            pki.util.set_property(config, 'internaldb.ldapauth.authtype',
                                  auth_type)

            if auth_type == 'BasicAuth':

                print()
                print('Enter the bind DN.')
                bind_dn = config.get('internaldb.ldapauth.bindDN')
                bind_dn = pki.util.read_text('  Bind DN',
                                             default=bind_dn,
                                             required=True)
                pki.util.set_property(config, 'internaldb.ldapauth.bindDN',
                                      bind_dn)

                print()
                print('Enter the password name.')
                password_name = config.get('internaldb.ldapauth.bindPWPrompt')
                password_name = pki.util.read_text('  Password Name',
                                                   default=password_name,
                                                   required=True)
                pki.util.set_property(config,
                                      'internaldb.ldapauth.bindPWPrompt',
                                      password_name)

                print()
                print('Enter the password for %s.' % password_name)
                password = config.get('password.%s' % password_name)
                password = pki.util.read_text('  Password for %s' %
                                              password_name,
                                              default=password,
                                              password=True,
                                              required=True)
                pki.util.set_property(config, 'password.%s' % password_name,
                                      password)

            elif auth_type == 'SslClientAuth':

                print()
                print('Enter the client certificate.')
                nickname = config.get('internaldb.ldapauth.clientCertNickname')
                nickname = pki.util.read_text('  Client Certificate',
                                              default=nickname,
                                              required=True)
                pki.util.set_property(
                    config, 'internaldb.ldapauth.clientCertNickname', nickname)

            print()
            print('Enter the base DN for the ACME subtree.')
            base_dn = config.get('basedn')
            base_dn = pki.util.read_text('  Base DN',
                                         default=base_dn,
                                         required=True)
            pki.util.set_property(config, 'basedn', base_dn)

        elif database_type == 'postgresql':

            print()
            print('Enter the location of the PostgreSQL server.')
            url = config.get('url')
            url = pki.util.read_text('  Server URL',
                                     default=url,
                                     required=True)
            pki.util.set_property(config, 'url', url)

            print()
            print('Enter the username for basic authentication.')
            username = config.get('user')
            username = pki.util.read_text('  Username',
                                          default=username,
                                          required=True)
            pki.util.set_property(config, 'user', username)

            print()
            print('Enter the password for basic authentication.')
            password = config.get('password')
            password = pki.util.read_text('  Password',
                                          default=password,
                                          password=True,
                                          required=True)
            pki.util.set_property(config, 'password', password)

        pki.util.store_properties(database_conf, config)
コード例 #22
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))
コード例 #23
0
ファイル: acme.py プロジェクト: tiran/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 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('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()

        acme_conf_dir = os.path.join(instance.conf_dir, 'acme')
        issuer_conf = os.path.join(acme_conf_dir, 'issuer.conf')
        config = {}

        logger.info('Loading %s', issuer_conf)
        pki.util.load_properties(issuer_conf, config)

        issuer_class = config.get('class')

        issuer_type = ISSUER_TYPES.get(issuer_class)
        print('  Issuer Type: %s' % issuer_type)

        if issuer_type == 'nss':

            nickname = config.get('nickname')
            if nickname:
                print('  Signing Certificate: %s' % nickname)

            extensions = config.get('extensions')
            if extensions:
                print('  Certificate Extensions: %s' % extensions)

        elif issuer_type == 'pki':

            url = config.get('url')
            if url:
                print('  Server URL: %s' % url)

            nickname = config.get('nickname')
            if nickname:
                print('  Client Certificate: %s' % nickname)

            username = config.get('username')
            if username:
                print('  Agent Username: %s' % username)

            password = config.get('password')
            if password:
                print('  Agent Password: ********')

            password_file = config.get('passwordFile')
            if password_file:
                print('  Password file: %s' % password_file)

            profile = config.get('profile')
            if profile:
                print('  Certificate Profile: %s' % profile)
コード例 #24
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)
コード例 #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
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'port=', 'protocol=', 'scheme=', 'secure=',
                'sslEnabled=', 'sslImpl=', 'sslProtocol=', 'certVerification=',
                'trustManager=', 'verbose', 'debug', 'help'
            ])

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

        instance_name = 'pki-tomcat'
        port = None
        protocol = None
        scheme = None
        secure = None
        sslEnabled = None
        sslImpl = None
        sslProtocol = None
        certVerification = None
        trustManager = None

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

            elif o == '--port':
                port = a

            elif o == '--protocol':
                protocol = a

            elif o == '--scheme':
                scheme = a

            elif o == '--secure':
                secure = a

            elif o == '--sslEnabled':
                sslEnabled = a

            elif o == '--sslImpl':
                sslImpl = a

            elif o == '--sslProtocol':
                sslProtocol = a

            elif o == '--certVerification':
                certVerification = a

            elif o == '--trustManager':
                trustManager = 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 connector ID')

        if port is None:
            raise Exception('Missing port number')

        name = args[0]

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

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

        instance.load()

        server_config = instance.get_server_config()

        try:
            server_config.get_connector(name)
            raise Exception('Connector already exists: %s' % name)
        except KeyError:
            pass

        connector = server_config.create_connector(name)

        HTTPConnectorCLI.set_param(connector, 'port', port)
        HTTPConnectorCLI.set_param(connector, 'protocol', protocol)
        HTTPConnectorCLI.set_param(connector, 'scheme', scheme)
        HTTPConnectorCLI.set_param(connector, 'secure', secure)
        HTTPConnectorCLI.set_param(connector, 'SSLEnabled', sslEnabled)
        HTTPConnectorCLI.set_param(connector, 'sslImplementationName', sslImpl)

        sslhost = server_config.create_sslhost(connector)

        HTTPConnectorCLI.set_param(sslhost, 'sslProtocol', sslProtocol)
        HTTPConnectorCLI.set_param(sslhost, 'certificateVerification',
                                   certVerification)
        HTTPConnectorCLI.set_param(sslhost, 'trustManagerClassName',
                                   trustManager)

        server_config.save()

        HTTPConnectorCLI.print_connector(connector)