#!/usr/bin/python -tu # Authors: # Matthew Harmsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright (C) 2011 Red Hat, Inc. # All rights reserved. # # System Imports from __future__ import absolute_import from __future__ import print_function import sys import signal if not hasattr(sys, "hexversion") or sys.hexversion < 0x020700f0: print("Python version %s.%s.%s is too old." % sys.version_info[:3]) print("Please upgrade to at least Python 2.7.0.") sys.exit(1) try: import ldap import os import requests import socket import struct import subprocess import time import traceback from time import strftime as date from pki.server.deployment import pkiconfig as config from pki.server.deployment.pkiparser import PKIConfigParser from pki.server.deployment import pkilogging from pki.server.deployment import pkimessages as log import pki.server.deployment.pkihelper as util except ImportError: print("""\ There was a problem importing one of the required Python modules. The error was: %s """ % sys.exc_info()[1], file=sys.stderr) sys.exit(1) # Handle the Keyboard Interrupt # pylint: disable=W0613 def interrupt_handler(event, frame): print() print('\nInstallation canceled.') sys.exit(1) # PKI Deployment Functions def main(argv): """main entry point""" config.pki_deployment_executable = os.path.basename(argv[0]) # Set the umask os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK) # Set installation time ticks = time.time() config.pki_install_time = time.asctime(time.localtime(ticks)) # Generate a timestamp config.pki_timestamp = date('%Y%m%d%H%M%S', time.localtime(ticks)) config.pki_certificate_timestamp = \ date('%Y-%m-%d %H:%M:%S', time.localtime(ticks)) # Obtain the architecture bit-size config.pki_architecture = struct.calcsize("P") * 8 # Retrieve hostname config.pki_hostname = socket.getfqdn() # Retrieve DNS domainname try: dnsdomainname = subprocess.check_output(["dnsdomainname"]) dnsdomainname = dnsdomainname.decode('ascii').rstrip('\n') config.pki_dns_domainname = dnsdomainname if not len(config.pki_dns_domainname): print(log.PKI_DNS_DOMAIN_NOT_SET) config.pki_dns_domainname = config.pki_hostname except subprocess.CalledProcessError as exc: print(log.PKI_SUBPROCESS_ERROR_1 % exc) sys.exit(1) # Read and process command-line arguments. parser = PKIConfigParser( 'PKI Instance Installation and Configuration', log.PKISPAWN_EPILOG) parser.optional.add_argument( '-f', dest='user_deployment_cfg', action='store', nargs=1, metavar='', help='configuration filename ' '(MUST specify complete path)') parser.optional.add_argument( '--precheck', dest='precheck', action='store_true', help='Execute pre-checks and exit') args = parser.process_command_line_arguments() config.default_deployment_cfg = \ config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE # -f if args.user_deployment_cfg is not None: config.user_deployment_cfg = str( args.user_deployment_cfg).strip('[\']') parser.validate() interactive = False if config.user_deployment_cfg is None: interactive = True parser.indent = 0 print(log.PKISPAWN_INTERACTIVE_INSTALLATION) # Only run this program as "root". if not os.geteuid() == 0: sys.exit("'%s' must be run as root!" % argv[0]) while True: # -s if args.pki_subsystem is None: interactive = True parser.indent = 0 config.pki_subsystem = parser.read_text( 'Subsystem (CA/KRA/OCSP/TKS/TPS)', options=['CA', 'KRA', 'OCSP', 'TKS', 'TPS'], default='CA', case_sensitive=False).upper() print() else: config.pki_subsystem = str(args.pki_subsystem).strip('[\']') parser.init_config() if config.user_deployment_cfg is None: if args.precheck: sys.exit( 'precheck mode is only valid for non-interactive installs') interactive = True parser.indent = 2 print("Tomcat:") instance_name = parser.read_text( 'Instance', 'DEFAULT', 'pki_instance_name') existing_data = parser.read_existing_deployment_data(instance_name) set_port(parser, 'pki_http_port', 'HTTP port', existing_data) set_port(parser, 'pki_https_port', 'Secure HTTP port', existing_data) set_port(parser, 'pki_ajp_port', 'AJP port', existing_data) set_port(parser, 'pki_tomcat_server_port', 'Management port', existing_data) print() print("Administrator:") parser.read_text('Username', config.pki_subsystem, 'pki_admin_uid') admin_password = parser.read_password( 'Password', config.pki_subsystem, 'pki_admin_password', verifyMessage='Verify password') parser.set_property(config.pki_subsystem, 'pki_backup_password', admin_password) parser.set_property(config.pki_subsystem, 'pki_client_database_password', admin_password) parser.set_property(config.pki_subsystem, 'pki_client_pkcs12_password', admin_password) if parser.mdict['pki_import_admin_cert'] == 'True': import_cert = 'Y' else: import_cert = 'N' import_cert = parser.read_text( 'Import certificate (Yes/No)', default=import_cert, options=['Yes', 'Y', 'No', 'N'], sign='?', case_sensitive=False).lower() if import_cert == 'y' or import_cert == 'yes': parser.set_property(config.pki_subsystem, 'pki_import_admin_cert', 'True') parser.read_text('Import certificate from', config.pki_subsystem, 'pki_admin_cert_file') else: parser.set_property(config.pki_subsystem, 'pki_import_admin_cert', 'False') parser.read_text('Export certificate to', config.pki_subsystem, 'pki_client_admin_cert') # if parser.mdict['pki_hsm_enable'] == 'True': # use_hsm = 'Y' # else: # use_hsm = 'N' # use_hsm = parser.read_text( # 'Using hardware security module (HSM) (Yes/No)', # default=use_hsm, options=['Yes', 'Y', 'No', 'N'], # sign='?', case_sensitive=False).lower() # if use_hsm == 'y' or use_hsm == 'yes': # # XXX: Suppress interactive HSM installation # print "Interactive HSM installation is currently unsupported." # sys.exit(0) # TBD: Interactive HSM installation # parser.set_property(config.pki_subsystem, # 'pki_hsm_enable', # 'True') # modulename = parser.read_text( # 'HSM Module Name (e. g. - nethsm)', allow_empty=False) # parser.set_property(config.pki_subsystem, # 'pki_hsm_modulename', # modulename) # libfile = parser.read_text( # 'HSM Lib File ' + # '(e. g. - /opt/nfast/toolkits/pkcs11/libcknfast.so)', # allow_empty=False) # parser.set_property(config.pki_subsystem, # 'pki_hsm_libfile', # libfile) # print print("Directory Server:") while True: parser.read_text('Hostname', config.pki_subsystem, 'pki_ds_hostname') if parser.mdict['pki_ds_secure_connection'] == 'True': secure = 'Y' else: secure = 'N' secure = parser.read_text( 'Use a secure LDAPS connection (Yes/No/Quit)', default=secure, options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'], sign='?', case_sensitive=False).lower() if secure == 'q' or secure == 'quit': print("Installation canceled.") sys.exit(0) if secure == 'y' or secure == 'yes': # Set secure DS connection to true parser.set_property(config.pki_subsystem, 'pki_ds_secure_connection', 'True') # Prompt for secure 'ldaps' port parser.read_text('Secure LDAPS Port', config.pki_subsystem, 'pki_ds_ldaps_port') # Specify complete path to a directory server # CA certificate pem file pem_file = parser.read_text( 'Directory Server CA certificate pem file', allow_empty=False) parser.set_property(config.pki_subsystem, 'pki_ds_secure_connection_ca_pem_file', pem_file) else: parser.read_text('LDAP Port', config.pki_subsystem, 'pki_ds_ldap_port') parser.read_text('Bind DN', config.pki_subsystem, 'pki_ds_bind_dn') parser.read_password('Password', config.pki_subsystem, 'pki_ds_password') try: parser.ds_verify_configuration() except ldap.LDAPError as e: parser.print_text('ERROR: ' + e.args[0]['desc']) continue parser.read_text('Base DN', config.pki_subsystem, 'pki_ds_base_dn') try: if not parser.ds_base_dn_exists(): break except ldap.LDAPError as e: parser.print_text('ERROR: ' + e.args[0]['desc']) continue remove = parser.read_text( 'Base DN already exists. Overwrite (Yes/No/Quit)', options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'], sign='?', allow_empty=False, case_sensitive=False).lower() if remove == 'q' or remove == 'quit': print("Installation canceled.") sys.exit(0) if remove == 'y' or remove == 'yes': break print() print("Security Domain:") if config.pki_subsystem == "CA": parser.read_text('Name', config.pki_subsystem, 'pki_security_domain_name') else: while True: parser.read_text('Hostname', config.pki_subsystem, 'pki_security_domain_hostname') parser.read_text('Secure HTTP port', config.pki_subsystem, 'pki_security_domain_https_port') try: parser.sd_connect() info = parser.sd_get_info() parser.print_text('Name: ' + info.name) parser.set_property(config.pki_subsystem, 'pki_security_domain_name', info.name) break except requests.exceptions.ConnectionError as e: parser.print_text('ERROR: ' + str(e)) while True: parser.read_text('Username', config.pki_subsystem, 'pki_security_domain_user') parser.read_password('Password', config.pki_subsystem, 'pki_security_domain_password') try: parser.sd_authenticate() break except requests.exceptions.HTTPError as e: parser.print_text('ERROR: ' + str(e)) print() if config.pki_subsystem == "TPS": print("External Servers:") while True: parser.read_text('CA URL', config.pki_subsystem, 'pki_ca_uri') try: status = parser.get_server_status('ca', 'pki_ca_uri') if status == 'running': break parser.print_text('ERROR: CA is not running') except requests.exceptions.ConnectionError as e: parser.print_text('ERROR: ' + str(e)) while True: parser.read_text('TKS URL', config.pki_subsystem, 'pki_tks_uri') try: status = parser.get_server_status('tks', 'pki_tks_uri') if status == 'running': break parser.print_text('ERROR: TKS is not running') except requests.exceptions.ConnectionError as e: parser.print_text('ERROR: ' + str(e)) while True: keygen = parser.read_text( 'Enable server side key generation (Yes/No)', options=['Yes', 'Y', 'No', 'N'], default='N', sign='?', case_sensitive=False).lower() if keygen == 'y' or keygen == 'yes': parser.set_property(config.pki_subsystem, 'pki_enable_server_side_keygen', 'True') parser.read_text('KRA URL', config.pki_subsystem, 'pki_kra_uri') try: status = parser.get_server_status( 'kra', 'pki_kra_uri') if status == 'running': break parser.print_text('ERROR: KRA is not running') except requests.exceptions.ConnectionError as e: parser.print_text('ERROR: ' + str(e)) else: parser.set_property(config.pki_subsystem, 'pki_enable_server_side_keygen', 'False') break print() print("Authentication Database:") while True: parser.read_text('Hostname', config.pki_subsystem, 'pki_authdb_hostname') parser.read_text('Port', config.pki_subsystem, 'pki_authdb_port') basedn = parser.read_text('Base DN', allow_empty=False) parser.set_property(config.pki_subsystem, 'pki_authdb_basedn', basedn) try: parser.authdb_connect() if parser.authdb_base_dn_exists(): break else: parser.print_text('ERROR: base DN does not exist') except ldap.LDAPError as e: parser.print_text('ERROR: ' + e.args[0]['desc']) print() if interactive: parser.indent = 0 begin = parser.read_text( 'Begin installation (Yes/No/Quit)', options=['Yes', 'Y', 'No', 'N', 'Quit', 'Q'], sign='?', allow_empty=False, case_sensitive=False).lower() print() if begin == 'q' or begin == 'quit': print("Installation canceled.") sys.exit(0) if begin == 'y' or begin == 'yes': break else: break if not os.path.exists(config.PKI_DEPLOYMENT_SOURCE_ROOT + "/" + config.pki_subsystem.lower()): print("ERROR: " + log.PKI_SUBSYSTEM_NOT_INSTALLED_1 % config.pki_subsystem.lower()) sys.exit(1) start_logging() create_master_dictionary(parser) if not interactive and \ not config.str2bool(parser.mdict['pki_skip_configuration']): check_ds(parser) check_security_domain(parser) if args.precheck: print('pre-checks completed successfully.') sys.exit(0) print("Installing " + config.pki_subsystem + " into " + parser.mdict['pki_instance_path'] + ".") # Process the various "scriptlets" to create the specified PKI subsystem. pki_subsystem_scriptlets = parser.mdict['spawn_scriplets'].split() deployer = util.PKIDeployer(parser.mdict, parser.slots_dict) try: for scriptlet_name in pki_subsystem_scriptlets: scriptlet_module = __import__( "pki.server.deployment.scriptlets." + scriptlet_name, fromlist=[scriptlet_name]) scriptlet = scriptlet_module.PkiScriptlet() scriptlet.spawn(deployer) # pylint: disable=W0703 except Exception as e: log_error_details() print() print("Installation failed: %s" % e) print() sys.exit(1) config.pki_log.debug(log.PKI_DICTIONARY_MASTER, extra=config.PKI_INDENTATION_LEVEL_0) config.pki_log.debug(pkilogging.log_format(parser.mdict), extra=config.PKI_INDENTATION_LEVEL_0) external = deployer.configuration_file.external step_one = deployer.configuration_file.external_step_one if external and step_one: external_csr_path = deployer.mdict['pki_external_csr_path'] if external_csr_path: print_external_ca_step_one_information(parser.mdict) else: print_existing_ca_step_one_information(parser.mdict) else: print_install_information(parser.mdict) def start_logging(): # Enable 'pkispawn' logging. config.pki_log_dir = config.pki_root_prefix + \ config.PKI_DEPLOYMENT_LOG_ROOT config.pki_log_name = "pki" + "-" + \ config.pki_subsystem.lower() + \ "-" + "spawn" + "." + \ config.pki_timestamp + "." + "log" print('Log file: %s/%s' % (config.pki_log_dir, config.pki_log_name)) rv = pkilogging.enable_pki_logger(config.pki_log_dir, config.pki_log_name, config.pki_log_level, config.pki_console_log_level, "pkispawn") if rv != OSError: config.pki_log = rv else: print(log.PKI_UNABLE_TO_CREATE_LOG_DIRECTORY_1 % config.pki_log_dir) sys.exit(1) def create_master_dictionary(parser): # Read the specified PKI configuration file. rv = parser.read_pki_configuration_file() if rv != 0: config.pki_log.error(log.PKI_UNABLE_TO_PARSE_1, rv, extra=config.PKI_INDENTATION_LEVEL_0) sys.exit(1) # Read in the PKI slots configuration file. parser.compose_pki_slots_dictionary() config.pki_log.debug(log.PKI_DICTIONARY_SLOTS, extra=config.PKI_INDENTATION_LEVEL_0) config.pki_log.debug(pkilogging.log_format(parser.slots_dict), extra=config.PKI_INDENTATION_LEVEL_0) # Combine the various sectional dictionaries into a PKI master dictionary parser.compose_pki_master_dictionary() parser.mdict['pki_spawn_log'] = \ config.pki_log_dir + "/" + config.pki_log_name config.pki_log.debug(log.PKI_DICTIONARY_MASTER, extra=config.PKI_INDENTATION_LEVEL_0) config.pki_log.debug(pkilogging.log_format(parser.mdict), extra=config.PKI_INDENTATION_LEVEL_0) def check_security_domain(parser): if parser.mdict['pki_security_domain_type'] != "new": try: # Verify existence of Security Domain Password if 'pki_security_domain_password' not in parser.mdict or \ not len(parser.mdict['pki_security_domain_password']): config.pki_log.error( log.PKIHELPER_UNDEFINED_CONFIGURATION_FILE_ENTRY_2, "pki_security_domain_password", parser.mdict['pki_user_deployment_cfg'], extra=config.PKI_INDENTATION_LEVEL_0) sys.exit(1) if not config.str2bool(parser.mdict['pki_skip_sd_verify']): parser.sd_connect() info = parser.sd_get_info() parser.set_property(config.pki_subsystem, 'pki_security_domain_name', info.name) parser.sd_authenticate() except requests.exceptions.ConnectionError as e: print(('ERROR: Unable to access security domain: ' + str(e))) sys.exit(1) except requests.exceptions.HTTPError as e: print(('ERROR: Unable to access security domain: ' + str(e))) sys.exit(1) def check_ds(parser): try: # Verify existence of Directory Server Password if 'pki_ds_password' not in parser.mdict or \ not len(parser.mdict['pki_ds_password']): config.pki_log.error( log.PKIHELPER_UNDEFINED_CONFIGURATION_FILE_ENTRY_2, "pki_ds_password", parser.mdict['pki_user_deployment_cfg'], extra=config.PKI_INDENTATION_LEVEL_0) sys.exit(1) if not config.str2bool(parser.mdict['pki_skip_ds_verify']): parser.ds_verify_configuration() if parser.ds_base_dn_exists() and not \ config.str2bool(parser.mdict['pki_ds_remove_data']): print('ERROR: Base DN already exists.') sys.exit(1) except ldap.LDAPError as e: print('ERROR: Unable to access directory server: ' + e.args[0]['desc']) sys.exit(1) def set_port(parser, tag, prompt, existing_data): if tag in existing_data: parser.set_property(config.pki_subsystem, tag, existing_data[tag]) else: parser.read_text(prompt, config.pki_subsystem, tag) def print_external_ca_step_one_information(mdict): print(log.PKI_SPAWN_INFORMATION_HEADER) print(" The %s subsystem of the '%s' instance is still incomplete." % (config.pki_subsystem, mdict['pki_instance_name'])) print() print(" A CSR for the CA certificate has been generated at:\n" " %s" % mdict['pki_external_csr_path']) print() print(" Submit the CSR to an external CA to generate a CA certificate\n" " for this subsystem. Import the CA certificate and the certificate\n" " chain, then continue the installation.") print(log.PKI_SPAWN_INFORMATION_FOOTER) def print_existing_ca_step_one_information(mdict): print(log.PKI_SPAWN_INFORMATION_HEADER) print(" The %s subsystem of the '%s' instance is still incomplete." % (config.pki_subsystem, mdict['pki_instance_name'])) print() print(" Import an existing CA certificate with the key and the CSR, and\n" " the certificate chain if available, then continue the installation.") print(log.PKI_SPAWN_INFORMATION_FOOTER) def print_install_information(mdict): skip_configuration = config.str2bool(mdict['pki_skip_configuration']) print(log.PKI_SPAWN_INFORMATION_HEADER) if skip_configuration: print(" The %s subsystem of the '%s' instance\n" " must still be configured!" % (config.pki_subsystem, mdict['pki_instance_name'])) else: print(" Administrator's username: %s" % mdict['pki_admin_uid']) if os.path.isfile(mdict['pki_client_admin_cert_p12']): print(" Administrator's PKCS #12 file:\n %s" % mdict['pki_client_admin_cert_p12']) if not config.str2bool(mdict['pki_client_database_purge']): print() print(" Administrator's certificate nickname:\n %s" % mdict['pki_admin_nickname']) if not config.str2bool(mdict['pki_clone']): print(" Administrator's certificate database:\n %s" % mdict['pki_client_database_dir']) else: print() print(" This %s subsystem of the '%s' instance\n" " is a clone." % (config.pki_subsystem, mdict['pki_instance_name'])) print(log.PKI_CHECK_STATUS_MESSAGE % mdict['pki_instance_name']) print(log.PKI_INSTANCE_RESTART_MESSAGE % mdict['pki_instance_name']) if (((config.pki_subsystem == "KRA" or config.pki_subsystem == "OCSP") and config.str2bool(mdict['pki_standalone'])) and not config.str2bool(mdict['pki_external_step_two'])): # Stand-alone PKI KRA/OCSP (External CA Step 1) print(log.PKI_CONFIGURATION_STANDALONE_1 % config.pki_subsystem) else: print(log.PKI_ACCESS_URL % (mdict['pki_hostname'], mdict['pki_https_port'], config.pki_subsystem.lower())) if not config.str2bool(mdict['pki_enable_on_system_boot']): print(log.PKI_SYSTEM_BOOT_STATUS_MESSAGE % "disabled") else: print(log.PKI_SYSTEM_BOOT_STATUS_MESSAGE % "enabled") print(log.PKI_SPAWN_INFORMATION_FOOTER) def log_error_details(): e_type, e_value, e_stacktrace = sys.exc_info() config.pki_log.debug( "Error Type: " + e_type.__name__, extra=config.PKI_INDENTATION_LEVEL_2) config.pki_log.debug( "Error Message: " + str(e_value), extra=config.PKI_INDENTATION_LEVEL_2) stacktrace_list = traceback.format_list(traceback.extract_tb(e_stacktrace)) e_stacktrace = "" for l in stacktrace_list: e_stacktrace += l config.pki_log.debug(e_stacktrace, extra=config.PKI_INDENTATION_LEVEL_2) del e_type, e_value, e_stacktrace # PKI Deployment Entry Point if __name__ == "__main__": signal.signal(signal.SIGINT, interrupt_handler) main(sys.argv)