Пример #1
0
    def migrate_nssdb(self, instance):

        if not os.path.exists(instance.nssdb_dir):
            return

        logger.info('Migrating %s instance to NSS SQL database', instance.name)

        nssdb = instance.open_nssdb()

        try:
            # Only attempt to convert if target format is sql and DB is dbm
            if nssdb.needs_conversion():
                nssdb.convert_db()
        finally:
            nssdb.close()

        ca_path = os.path.join(instance.nssdb_dir, 'ca.crt')
        token = pki.nssdb.INTERNAL_TOKEN_NAME
        nickname = instance.get_sslserver_cert_nickname()
        if ':' in nickname:
            token = nickname.split(':', 1)[0]

        # Re-open NSS DB with correct token name
        nssdb = instance.open_nssdb(token=token)

        try:
            nssdb.extract_ca_cert(ca_path, nickname)
        finally:
            nssdb.close()
Пример #2
0
    def migrate_nssdb(self, instance):

        if not os.path.exists(instance.nssdb_dir):
            return

        logger.info('Migrating %s instance to NSS SQL database', instance.name)

        nssdb = instance.open_nssdb()

        try:
            # Only attempt to convert if target format is sql and DB is dbm
            if nssdb.needs_conversion():
                nssdb.convert_db()

            ca_path = os.path.join(instance.nssdb_dir, 'ca.crt')
            nickname = instance.get_sslserver_cert_nickname()
            nssdb.extract_ca_cert(ca_path, nickname)
        finally:
            nssdb.close()
Пример #3
0
    def migrate_server_xml_to_tomcat85(self, instance, document):

        self.migrate_server_xml_to_tomcat80(instance, document)

        server = document.getroot()

        services = server.findall('Service')
        for service in services:

            children = list(service)
            for child in children:
                if isinstance(child, etree._Comment):  # pylint: disable=protected-access
                    if 'Java HTTP Connector: /docs/config/http.html' in child.text:
                        child.text = child.text.replace(
                            ' (blocking & non-blocking)', '')
                    elif 'Shared Ports:  Agent, EE, and Admin Secure Port Connector' in child.text:
                        service.remove(child)
                    elif 'DO NOT REMOVE - Begin define PKI secure port' in child.text:
                        service.remove(child)
                    elif 'DO NOT REMOVE - End define PKI secure port' in child.text:
                        service.remove(child)
                    elif 'protocol="AJP/1.3"' in child.text:
                        child.text = re.sub(r'^ *([^ ]+)=',
                                            r'               \g<1>=',
                                            child.text,
                                            flags=re.MULTILINE)

        logger.debug('* adding SSLHostConfig')

        connectors = server.findall('Service/Connector')
        for connector in connectors:

            if connector.get('secure') != 'true':
                continue

            connector.set('sslImplementationName',
                          'org.dogtagpki.tomcat.JSSImplementation')
            connector.attrib.pop('sslProtocol', None)
            connector.attrib.pop('clientAuth', None)
            connector.attrib.pop('keystoreType', None)
            connector.attrib.pop('keystoreProvider', None)
            connector.attrib.pop('keyAlias', None)
            connector.attrib.pop('trustManagerClassName', None)

            sslHostConfigs = connector.findall('SSLHostConfig')
            if len(sslHostConfigs) > 0:
                sslHostConfig = sslHostConfigs[0]
            else:
                sslHostConfig = etree.SubElement(connector, 'SSLHostConfig')

            sslHostConfig.set('sslProtocol', 'SSL')
            sslHostConfig.set('certificateVerification', 'optional')
            sslHostConfig.attrib.pop('trustManagerClassName', None)

            certificates = sslHostConfig.findall('Certificate')
            if len(certificates) > 0:
                certificate = certificates[0]
            else:
                certificate = etree.SubElement(sslHostConfig, 'Certificate')

            certificate.set('certificateKeystoreType', 'pkcs11')
            certificate.set('certificateKeystoreProvider', 'Mozilla-JSS')

            full_name = instance.get_sslserver_cert_nickname()
            certificate.set('certificateKeyAlias', full_name)
Пример #4
0
    def migrate_server_xml_to_tomcat80(self, instance, document):
        server = document.getroot()

        version_logger_listener = etree.Element('Listener')
        version_logger_listener.set(
            'className', 'org.apache.catalina.startup.VersionLoggerListener')

        security_listener_comment = etree.Comment(
            ''' Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  ''')

        jre_memory_leak_prevention_listener = etree.Element('Listener')
        jre_memory_leak_prevention_listener.set(
            'className',
            'org.apache.catalina.core.JreMemoryLeakPreventionListener')

        global_resources_lifecycle_listener = None

        thread_local_leak_prevention_listener = etree.Element('Listener')
        thread_local_leak_prevention_listener.set(
            'className',
            'org.apache.catalina.core.ThreadLocalLeakPreventionListener')

        prevent_comment = etree.Comment(
            ' Prevent memory leaks due to use of particular java/javax APIs')

        children = list(server)
        for child in children:
            if isinstance(child, etree._Comment):  # pylint: disable=protected-access
                if 'org.apache.catalina.security.SecurityListener' in child.text:
                    security_listener_comment = None
                elif 'Initialize Jasper prior to webapps are loaded.' in child.text:
                    server.remove(child)
                elif 'JMX Support for the Tomcat server.' in child.text:
                    server.remove(child)
                elif 'The following class has been commented out because it' in child.text:
                    server.remove(child)
                elif 'has been EXCLUDED from the Tomcat 7 \'tomcat-lib\' RPM!' in child.text:
                    server.remove(child)
                elif 'org.apache.catalina.mbeans.ServerLifecycleListener' in child.text:
                    server.remove(child)
                elif 'Prevent memory leaks due to use of particular java/javax APIs' in child.text:
                    prevent_comment = None

            elif child.tag == 'Listener':
                class_name = child.get('className')

                if class_name == 'org.apache.catalina.core.JasperListener'\
                        or class_name == 'org.apache.catalina.mbeans.ServerLifecycleListener':
                    logger.debug('* removing %s', class_name)
                    server.remove(child)
                elif class_name == 'org.apache.catalina.startup.VersionLoggerListener':
                    version_logger_listener = None
                elif class_name == 'org.apache.catalina.core.JreMemoryLeakPreventionListener':
                    jre_memory_leak_prevention_listener = None
                elif class_name == 'org.apache.catalina.mbeans.GlobalResourcesLifecycleListener':
                    global_resources_lifecycle_listener = child
                elif class_name == 'org.apache.catalina.core.ThreadLocalLeakPreventionListener':
                    thread_local_leak_prevention_listener = None

        # add at the top
        index = 0

        if version_logger_listener is not None:
            logger.debug('* adding VersionLoggerListener')
            server.insert(index, version_logger_listener)
            index += 1

        if security_listener_comment is not None:
            server.insert(index, security_listener_comment)
            index += 1

        # add before GlobalResourcesLifecycleListener if exists
        if global_resources_lifecycle_listener is not None:
            index = list(server).index(global_resources_lifecycle_listener)

        if prevent_comment is not None:
            server.insert(index, prevent_comment)
            index += 1

        if jre_memory_leak_prevention_listener is not None:
            logger.debug('* adding JreMemoryLeakPreventionListener')
            server.insert(index, jre_memory_leak_prevention_listener)
            index += 1

        # add after GlobalResourcesLifecycleListener if exists
        if global_resources_lifecycle_listener is not None:
            index = list(server).index(global_resources_lifecycle_listener) + 1

        if thread_local_leak_prevention_listener is not None:
            logger.debug('* adding ThreadLocalLeakPreventionListener')
            server.insert(index, thread_local_leak_prevention_listener)
            index += 1

        logger.debug('* updating secure Connector')

        connectors = server.findall('Service/Connector')
        for connector in connectors:

            if connector.get('secure') != 'true':
                continue

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

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

            connector.set('keystoreType', 'pkcs11')
            connector.set('keystoreProvider', 'Mozilla-JSS')
            connector.attrib.pop('keystoreFile', None)
            connector.attrib.pop('keystorePassFile', None)

            full_name = instance.get_sslserver_cert_nickname()
            connector.set('keyAlias', full_name)

            connector.set('trustManagerClassName',
                          'org.dogtagpki.tomcat.PKITrustManager')

        logger.debug('* updating AccessLogValve')

        valves = server.findall('Service/Engine/Host/Valve')
        for valve in valves:

            if valve.get('className'
                         ) == 'org.apache.catalina.valves.AccessLogValve':
                valve.set('prefix', 'localhost_access_log')
Пример #5
0
Файл: cert.py Проект: tiran/pki
    def execute(self, argv):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        cert_id = args[0]

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

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

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

        instance.load()

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

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

        subsystem = instance.get_subsystem(subsystem_name)

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

        cert = subsystem.get_subsystem_cert(cert_tag)

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

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

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

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

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

        nssdb = instance.open_nssdb(token)

        try:
            if cert_file:

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

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

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

            if csr_file:

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

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

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

            if pkcs12_file:

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

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

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

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

        finally:
            nssdb.close()