Exemplo n.º 1
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        issuer_type = None
        props = {}

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

            elif o == '--type':
                issuer_type = a
                if issuer_type not in ISSUER_TYPES.values():
                    raise Exception('Invalid issuer type: {0}'.format(issuer_type))

            elif o == '-D':
                parts = a.split('=', 1)
                name = parts[0]
                value = parts[1]
                props[name] = value

            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 = {}

        if issuer_type:
            # if --type is specified, load the issuer.conf template
            source = '/usr/share/pki/acme/issuer/{0}/issuer.conf'.format(issuer_type)
        else:
            # otherwise, load the issuer.conf from the instance
            source = issuer_conf

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

        # if --type or -D is specified, use silent mode
        if issuer_type or props:

            logger.info('Setting properties:')
            for name, value in props.items():
                logger.info('- %s: %s', name, value)
                pki.util.set_property(config, name, value)

            instance.store_properties(issuer_conf, config)
            return

        # otherwise, use interactive mode

        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)
        orig_issuer_type = issuer_type

        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 orig_issuer_type != issuer_type:
            source = '/usr/share/pki/acme/issuer/{0}/issuer.conf'.format(issuer_type)
            logger.info('Loading %s', source)
            pki.util.load_properties(source, config)

        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 '
                  '(e.g. https://localhost.localdomain:8443).')
            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 '
                  '(e.g. acmeServerCert).')
            profile = config.get('profile')
            profile = pki.util.read_text('  Certificate Profile', default=profile, required=True)
            pki.util.set_property(config, 'profile', profile)

        instance.store_properties(issuer_conf, config)
Exemplo n.º 2
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:
            logger.error(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:
                logger.error('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

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

        connector_name = args[0]

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

        hostname = args[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()

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

        if connector is None:
            logger.error('Connector not found: %s', connector_name)
            sys.exit(1)

        sslhost = server_config.get_sslhost(connector, hostname)

        if connector is None:
            logger.error('SSL host not found: %s', hostname)
            sys.exit(1)

        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)
Exemplo n.º 3
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        show_all = False

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

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

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

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

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

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

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

        subsystem_name = args[0]

        instance = pki.server.instance.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,
                         instance_name)
            sys.exit(1)

        certs = subsystem.get_cert_infos()

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

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

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

            SubsystemCertCLI.print_subsystem_cert(cert, show_all)
Exemplo n.º 4
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()

        connector = server_config.get_connector(name)

        if connector is not None:
            raise Exception('Connector already exists: %s' % name)

        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)
Exemplo n.º 5
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 is None:
            raise KeyError('Connector not found: %s' % 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)
Exemplo n.º 6
0
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(
                argv,
                'i:D:w:x:g:v',
                ['instance=', 'bind-dn=', 'bind-password='******'generate-ldif=',
                 'verbose', 'debug', 'help']
            )

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

        instance_name = 'pki-tomcat'
        bind_dn = '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.exists():
            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)
Exemplo n.º 7
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'

        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 connector ID')
            self.print_help()
            sys.exit(1)

        connector_name = args[0]

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

        hostname = args[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()

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

        if connector is None:
            logger.error('Connector not found: %s', connector_name)

        sslhost = server_config.get_sslhost(connector, hostname)

        if connector is None:
            logger.error('SSL host not found: %s', hostname)
            sys.exit(1)

        SSLHostCLI.print_sslhost(sslhost)
Exemplo n.º 8
0
    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)
Exemplo n.º 9
0
Arquivo: audit.py Projeto: zdzichu/pki
    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(argv, 'i:v', [
                'instance=',
                'enabled=',
                'logFile=', 'bufferSize=', 'flushInterval=',
                'maxFileSize=', 'rolloverInterval=', 'expirationTime=',
                'logSigning=', 'signingCert=',
                'verbose', 'debug', 'help'])

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        instance.load()

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

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

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

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

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

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

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

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

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

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

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

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

        subsystem.save()

        AuditCLI.print_audit_config(subsystem)
Exemplo n.º 10
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        database_type = None
        props = {}

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

            elif o == '--type':
                database_type = a
                if database_type not in DATABASE_TYPES.values():
                    raise Exception('Invalid database type: {0}'.format(database_type))

            elif o == '-D':
                parts = a.split('=', 1)
                name = parts[0]
                value = parts[1]
                props[name] = value

            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 = {}

        if database_type:
            # if --type is specified, load the database.conf template
            source = '/usr/share/pki/acme/database/{0}/database.conf'.format(database_type)
        else:
            # otherwise, load the database.conf from the instance
            source = database_conf

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

        # if --type or -D is specified, use silent mode
        if database_type or props:

            logger.info('Setting properties:')
            for name, value in props.items():
                logger.info('- %s: %s', name, value)
                pki.util.set_property(config, name, value)

            instance.store_properties(database_conf, config)
            return

        # otherwise, use interactive mode

        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)
        orig_database_type = database_type

        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 orig_database_type != database_type:
            source = '/usr/share/pki/acme/database/{0}/database.conf'.format(database_type)
            logger.info('Loading %s', source)
            pki.util.load_properties(source, config)

        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 location of the LDAP server '
                  '(e.g. ldap://localhost.localdomain:389).')
            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 authentication type. Available types: BasicAuth, SslClientAuth.')
            auth_type = config.get('authType')
            auth_type = pki.util.read_text(
                '  Authentication Type',
                options=['BasicAuth', 'SslClientAuth'],
                default=auth_type,
                required=True)
            pki.util.set_property(config, 'authType', auth_type)

            if auth_type == 'BasicAuth':

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

                print()
                print('Enter the bind password.')
                password = config.get('bindPassword')
                password = pki.util.read_text(
                    '  Bind Password',
                    default=password,
                    password=True,
                    required=True)
                pki.util.set_property(config, 'bindPassword', password)

            elif auth_type == 'SslClientAuth':

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

            print()
            print('Enter the base DN for the ACME subtree.')

            base_dn = config.pop('basedn', None)
            if not base_dn:
                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 database '
                  '(e.g. jdbc:postgresql://localhost.localdomain:5432/acme).')
            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)

        instance.store_properties(database_conf, config)
Exemplo n.º 11
0
    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')

        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)
Exemplo n.º 12
0
    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':

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

            auth_type = config.get('authType')
            if auth_type:
                print('  Authentication Type: %s' % auth_type)

            if auth_type == 'BasicAuth':

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

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

            elif auth_type == 'SslClientAuth':

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

            base_dn = config.get('basedn')
            if base_dn:
                logger.warning('The basedn parameter has been deprecated. Use baseDN instead.')
            else:
                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: ********')
Exemplo n.º 13
0
    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 = {}

        if not os.path.exists(metadata_conf):
            source = '/usr/share/pki/acme/conf/metadata.conf'
        else:
            source = metadata_conf

        logger.info('Loading %s', source)
        pki.util.load_properties(source, 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)

        instance.store_properties(metadata_conf, config)
Exemplo n.º 14
0
    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 = {}

        if not os.path.exists(metadata_conf):
            source = '/usr/share/pki/acme/conf/metadata.conf'
        else:
            source = metadata_conf

        logger.info('Loading %s', source)
        pki.util.load_properties(source, 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)
Exemplo n.º 15
0
    def execute(self, argv):

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

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

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

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

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

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

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

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

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

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

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

        instance.load()

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

        request = subsystem.get_cert_requests(request_id)

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

        else:
            CACertRequestCLI.print_request(request, details=True)
Exemplo n.º 16
0
Arquivo: audit.py Projeto: zdzichu/pki
    def execute(self, argv):

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

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

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

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

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

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

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

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

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

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

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

        instance.load()

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

        events = subsystem.find_audit_event_configs(enabled, enabled_by_default)

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

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

            print('  Event Name: %s' % event.get('name'))
            print('  Enabled: %s' % event.get('enabled'))
            print('  Filter: %s' % event.get('filter'))
Exemplo n.º 17
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.exists():
            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)
Exemplo n.º 18
0
Arquivo: audit.py Projeto: zdzichu/pki
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        event_filter = None

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

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

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

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

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

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

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

        event_name = args[0]

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

        instance.load()

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

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

        event = subsystem.get_audit_event_config(event_name)
        AuditCLI.print_audit_event_config(event)
Exemplo n.º 19
0
    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:
            logger.error(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('kra')
        if not subsystem:
            logger.error('No KRA 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(
                'transport', pkcs12_file, pkcs12_password_file, no_key=no_key, append=True)
            subsystem.export_system_cert(
                'storage', pkcs12_file, pkcs12_password_file, no_key=no_key, append=True)
            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)
Exemplo n.º 20
0
Arquivo: audit.py Projeto: zdzichu/pki
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'

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

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

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

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

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

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

        event_name = args[0]

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

        instance.load()

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

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

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

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

        event = subsystem.get_audit_event_config(event_name)
        AuditCLI.print_audit_event_config(event)
Exemplo n.º 21
0
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'connector=', 'sslHost=', 'certFile=',
                'keyAlias=', 'keyFile=', 'keystoreType=', 'keystoreProvider=',
                'keystoreFile=', 'keystorePassword='******'verbose', 'debug',
                'help'
            ])

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

        instance_name = 'pki-tomcat'
        connector_name = 'Secure'
        hostname = '_default_'
        certFile = None
        keyAlias = None
        keyFile = None
        keystoreType = None
        keystoreProvider = None
        keystoreFile = None
        keystorePassword = None

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

            elif o == '--connector':
                connector_name = a

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

            elif o == '--certFile':
                certFile = a

            elif o == '--keyAlias':
                keyAlias = a

            elif o == '--keyFile':
                keyFile = a

            elif o == '--keystoreType':
                keystoreType = a

            elif o == '--keystoreProvider':
                keystoreProvider = a

            elif o == '--keystoreFile':
                keystoreFile = a

            elif o == '--keystorePassword':
                keystorePassword = 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:
            certType = 'UNDEFINED'
        else:
            certType = 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(connector_name)

        if connector is None:
            raise KeyError('Connector not found: %s' % connector_name)

        sslhost = server_config.get_sslhost(connector, hostname)

        try:
            server_config.get_sslcert(sslhost, certType)
            raise Exception('SSL certificate already exists: %s' % certType)
        except KeyError:
            pass

        sslcert = server_config.create_sslcert(sslhost, certType)

        HTTPConnectorCLI.set_param(sslcert, 'certificateFile', certFile)
        HTTPConnectorCLI.set_param(sslcert, 'certificateKeyAlias', keyAlias)
        HTTPConnectorCLI.set_param(sslcert, 'certificateKeyFile', keyFile)
        HTTPConnectorCLI.set_param(sslcert, 'certificateKeystoreType',
                                   keystoreType)
        HTTPConnectorCLI.set_param(sslcert, 'certificateKeystoreProvider',
                                   keystoreProvider)
        HTTPConnectorCLI.set_param(sslcert, 'certificateKeystoreFile',
                                   keystoreFile)
        HTTPConnectorCLI.set_param(sslcert, 'certificateKeystorePassword',
                                   keystorePassword)

        server_config.save()

        SSLCertCLI.print_sslcert(sslcert)
Exemplo n.º 22
0
Arquivo: audit.py Projeto: zdzichu/pki
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'

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

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

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

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

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

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

        instance.load()

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

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

        tmpdir = tempfile.mkdtemp()

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

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

            cmd = ['AuditVerify']

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

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

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

            subprocess.call(cmd)

        finally:
            shutil.rmtree(tmpdir)
Exemplo n.º 23
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        connector_name = 'Secure'
        hostname = '_default_'

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

            elif o == '--connector':
                connector_name = a

            elif o == '--sslHost':
                hostname = 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:
            certType = 'UNDEFINED'
        else:
            certType = 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(connector_name)

        if connector is None:
            raise KeyError('Connector not found: %s' % connector_name)

        sslhost = server_config.get_sslhost(connector, hostname)

        server_config.remove_sslcert(sslhost, certType)

        server_config.save()
Exemplo n.º 24
0
Arquivo: sd.py Projeto: zdzichu/pki
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'hostname=', 'unsecure-port=', 'secure-port=',
                'domain-manager', 'clone',
                'verbose', 'debug', 'help'])

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

        instance_name = 'pki-tomcat'
        hostname = None
        unsecure_port = '8080'
        secure_port = '8443'
        domain_manager = False
        clone = False

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

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

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

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

            elif o == '--domain-manager':
                domain_manager = True

            elif o == '--clone':
                clone = 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('Invalid option: %s', o)
                self.print_help()
                sys.exit(1)

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

        host_id = args[0]

        if not hostname:
            logger.error('Missing hostname')
            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('ca')
        if not subsystem:
            logger.error('No CA subsystem in instance %s', instance_name)
            sys.exit(1)

        subsystem.add_security_domain_host(
            host_id,
            hostname,
            unsecure_port=unsecure_port,
            secure_port=secure_port,
            domain_manager=domain_manager,
            clone=clone)
Exemplo n.º 25
0
    def execute(self, argv):

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

        except getopt.GetoptError as e:
            print('ERROR: %s' % 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:
                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]

        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)

        if connector is None:
            raise KeyError('Connector not found: %s' % connector_name)

        sslhosts = server_config.get_sslhosts(connector)

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

        first = True
        for sslhost in sslhosts:

            if first:
                first = False
            else:
                print()

            SSLHostCLI.print_sslhost(sslhost)
Exemplo n.º 26
0
    def execute(self, argv):

        try:
            opts, args = getopt.gnu_getopt(argv, 'i:v', [
                'instance=', 'wait', 'max-wait=', 'timeout=', 'descriptor=',
                'doc-base=', 'verbose', 'debug', 'help'
            ])

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

        instance_name = 'pki-tomcat'
        descriptor = None
        doc_base = None
        wait = False
        max_wait = 60
        timeout = None

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

            elif o == '--descriptor':
                descriptor = a

            elif o == '--doc-base':
                doc_base = a

            elif o == '--wait':
                wait = True

            elif o == '--max-wait':
                max_wait = int(a)

            elif o == '--timeout':
                timeout = int(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 Webapp ID')

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

        webapp_id = args[0]

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

        instance.deploy_webapp(webapp_id,
                               descriptor,
                               doc_base,
                               wait=wait,
                               max_wait=max_wait,
                               timeout=timeout)
Exemplo n.º 27
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        all_subsystems = False

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

            elif o == '--all':
                all_subsystems = True

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

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

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

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

        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 all_subsystems:
            for subsystem in instance.get_subsystems():
                if subsystem.is_enabled():
                    subsystem.disable()

            self.print_message('Disabled all subsystems')

            return

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

        subsystem_name = args[0]

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

        if not subsystem.is_enabled():
            self.print_message('Subsystem "%s" is already '
                               'disabled' % subsystem_name)
        else:
            subsystem.disable()
            self.print_message('Disabled "%s" subsystem' % subsystem_name)

        SubsystemCLI.print_subsystem(subsystem)
Exemplo n.º 28
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        cert = None

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

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

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

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

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

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

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

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

        instance.load()

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

        results = subsystem.find_cert_requests(cert=cert)

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

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

            CACertRequestCLI.print_request(request)
Exemplo n.º 29
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        show_all = False

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

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

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

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

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

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

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

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

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

        instance = pki.server.instance.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('ERROR: No %s subsystem in instance %s.',
                         subsystem_name, instance_name)
            sys.exit(1)
        cert = subsystem.get_subsystem_cert(cert_id)
        self.print_message('"{}" subsystem "{}" certificate'.format(
            subsystem_name, cert_id))
        SubsystemCertCLI.print_subsystem_cert(cert, show_all)
Exemplo n.º 30
0
    def execute(self, argv):

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

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

        instance_name = 'pki-tomcat'
        cert_file = None

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

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

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

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

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

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

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

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

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

        instance = pki.server.instance.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, instance_name)
            sys.exit(1)
        system_cert = subsystem.get_subsystem_cert(cert_id)

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

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

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

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

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

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

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

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

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

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

        results = ca.find_cert_requests(cert=data)

        if results:
            cert_request = results[-1]
            request = cert_request['request']

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

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

        # store cert data and request in CS.cfg
        subsystem.update_system_cert(system_cert)
        subsystem.save()

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