Example #1
0
def get_truststore_password(properties):
  truststore_password = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  isSecure = get_is_secure(properties)
  if truststore_password:
    if isSecure:
      truststore_password = decrypt_password_for_alias(properties, SSL_TRUSTSTORE_PASSWORD_ALIAS)
  else:
    truststore_password = read_password("", ".*", "Password for TrustStore:", "Invalid characters in password")
    if truststore_password:
      encrypted_password = get_encrypted_password(SSL_TRUSTSTORE_PASSWORD_ALIAS, truststore_password, properties)
      properties.process_pair(SSL_TRUSTSTORE_PASSWORD_PROPERTY, encrypted_password)

  return truststore_password
Example #2
0
def get_and_persist_truststore_password(properties):
  truststore_password = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  isSecure = get_is_secure(properties)
  if truststore_password:
    if isSecure:
      truststore_password = decrypt_password_for_alias(properties, SSL_TRUSTSTORE_PASSWORD_ALIAS)
  else:
    truststore_password = read_password("", ".*", "Password for TrustStore:", "Invalid characters in password")
    if truststore_password:
      encrypted_password = get_encrypted_password(SSL_TRUSTSTORE_PASSWORD_ALIAS, truststore_password, properties)
      properties.process_pair(SSL_TRUSTSTORE_PASSWORD_PROPERTY, encrypted_password)

  return truststore_password
Example #3
0
def generate_env(options, ambari_user, current_user):
    properties = get_ambari_properties()
    isSecure = get_is_secure(properties)
    (isPersisted, masterKeyFile) = get_is_persisted(properties)
    environ = os.environ.copy()
    # Need to handle master key not persisted scenario
    if isSecure and not masterKeyFile:
        prompt = False
        masterKey = environ.get(SECURITY_KEY_ENV_VAR_NAME)

        if masterKey is not None and masterKey != "":
            pass
        else:
            keyLocation = environ.get(SECURITY_MASTER_KEY_LOCATION)

            if keyLocation is not None:
                try:
                    # Verify master key can be read by the java process
                    with open(keyLocation, 'r'):
                        pass
                except IOError:
                    print_warning_msg(
                        "Cannot read Master key from path specified in "
                        "environemnt.")
                    prompt = True
            else:
                # Key not provided in the environment
                prompt = True

        if prompt:
            import pwd

            masterKey = get_original_master_key(properties)
            environ[SECURITY_KEY_ENV_VAR_NAME] = masterKey
            tempDir = tempfile.gettempdir()
            tempFilePath = tempDir + os.sep + "masterkey"
            save_master_key(options, masterKey, tempFilePath, True)
            if ambari_user != current_user:
                uid = pwd.getpwnam(ambari_user).pw_uid
                gid = pwd.getpwnam(ambari_user).pw_gid
                os.chown(tempFilePath, uid, gid)
            else:
                os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)

            if tempFilePath is not None:
                environ[SECURITY_MASTER_KEY_LOCATION] = tempFilePath

    return environ
Example #4
0
def verify_setup_allowed():
    if get_silent():
        properties = get_ambari_properties()
        if properties == -1:
            print_error_msg("Error getting ambari properties")
            return -1

        isSecure = get_is_secure(properties)
        if isSecure:
            (isPersisted, masterKeyFile) = get_is_persisted(properties)
            if not isPersisted:
                print "ERROR: Cannot run silent 'setup' with password encryption enabled " \
                      "and Master Key not persisted."
                print "Ambari Server 'setup' exiting."
                return 1
    return 0
Example #5
0
def verify_setup_allowed():
  if get_silent():
    properties = get_ambari_properties()
    if properties == -1:
      print_error_msg("Error getting tbds properties")
      return -1

    isSecure = get_is_secure(properties)
    if isSecure:
      (isPersisted, masterKeyFile) = get_is_persisted(properties)
      if not isPersisted:
        print "ERROR: Cannot run silent 'setup' with password encryption enabled " \
              "and Master Key not persisted."
        print "TBDS Server 'setup' exiting."
        return 1
  return 0
Example #6
0
def generate_env(ambari_user, current_user):
  properties = get_ambari_properties()
  isSecure = get_is_secure(properties)
  (isPersisted, masterKeyFile) = get_is_persisted(properties)
  environ = os.environ.copy()
  # Need to handle master key not persisted scenario
  if isSecure and not masterKeyFile:
    prompt = False
    masterKey = environ.get(SECURITY_KEY_ENV_VAR_NAME)

    if masterKey is not None and masterKey != "":
      pass
    else:
      keyLocation = environ.get(SECURITY_MASTER_KEY_LOCATION)

      if keyLocation is not None:
        try:
          # Verify master key can be read by the java process
          with open(keyLocation, 'r'):
            pass
        except IOError:
          print_warning_msg("Cannot read Master key from path specified in "
                            "environemnt.")
          prompt = True
      else:
        # Key not provided in the environment
        prompt = True

    if prompt:
      import pwd

      masterKey = get_original_master_key(properties)
      tempDir = tempfile.gettempdir()
      tempFilePath = tempDir + os.sep + "masterkey"
      save_master_key(masterKey, tempFilePath, True)
      if ambari_user != current_user:
        uid = pwd.getpwnam(ambari_user).pw_uid
        gid = pwd.getpwnam(ambari_user).pw_gid
        os.chown(tempFilePath, uid, gid)
      else:
        os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)

      if tempFilePath is not None:
        environ[SECURITY_MASTER_KEY_LOCATION] = tempFilePath

  return environ
Example #7
0
def verify_setup_allowed(options):
  if get_silent():
    properties = get_ambari_properties()
    if properties == -1:
      print_error_msg("Error getting ambari properties")
      return -1

    isSecure = get_is_secure(properties)
    if isSecure:
      (isPersisted, masterKeyFile) = get_is_persisted(properties)
      if not isPersisted:
        print "ERROR: Cannot run silent 'setup' with password encryption enabled " \
              "and Master Key not persisted."
        print "Ambari Server 'setup' exiting."
        return 1

    factory = DBMSConfigFactory()
    default_dbms = factory.get_default_dbms_name()
    if default_dbms:
      valid = True
      if options.dbms is not None \
        and options.database_host is not None \
        and options.database_port is not None \
        and options.database_name is not None \
        and options.database_username is not None \
        and options.database_password is not None:

        if default_dbms == "sqlanywhere" and options.sqla_server_name is None:
          valid = False

      else:
        valid = False

      if not valid:
        print "ERROR: Cannot run silent setup without database connection properties provided."
        print "Ambari Server 'setup' exiting."
        return 2

  return 0
  def __init__(self, options, properties, storage_type):
    """
    #Just load the defaults. The derived classes will be able to modify them later
    """
    self.persistence_type = storage_type
    self.dbms = ""
    self.driver_class_name = ""
    self.driver_file_name = ""
    self.driver_symlink_name = ""
    self.database_host = ""
    self.database_port = ""
    self.database_name = ""
    self.database_username = ""

    self.db_title = AMBARI_DATABASE_TITLE

    self.must_set_database_options = DBMSConfig._init_member_with_default(options, "must_set_database_options", False)

    self.JDBC_DRIVER_INSTALL_MSG = 'Before starting Ambari Server, you must install the JDBC driver.'

    self.isSecure = get_is_secure(properties)
    pass
Example #9
0
  def __init__(self, options, properties, storage_type):
    """
    #Just load the defaults. The derived classes will be able to modify them later
    """
    self.persistence_type = storage_type
    self.dbms = ""
    self.driver_class_name = ""
    self.driver_file_name = ""
    self.driver_symlink_name = ""
    self.database_host = ""
    self.database_port = ""
    self.database_name = ""
    self.database_username = ""

    self.db_title = AMBARI_DATABASE_TITLE

    self.must_set_database_options = DBMSConfig._init_member_with_default(options, "must_set_database_options", False)

    self.JDBC_DRIVER_INSTALL_MSG = 'Before starting Ambari Server, you must install the JDBC driver.'

    self.isSecure = get_is_secure(properties)
    pass
Example #10
0
def setup_ldap():
  if not is_root():
    err = 'Ambari-server setup-ldap should be run with ' \
          'root-level privileges'
    raise FatalException(4, err)

  properties = get_ambari_properties()
  isSecure = get_is_secure(properties)

  ldap_property_list_reqd = init_ldap_properties_list_reqd(properties)

  ldap_property_list_opt = ["authentication.ldap.managerDn",
                            LDAP_MGR_PASSWORD_PROPERTY,
                            SSL_TRUSTSTORE_TYPE_PROPERTY,
                            SSL_TRUSTSTORE_PATH_PROPERTY,
                            SSL_TRUSTSTORE_PASSWORD_PROPERTY]

  ldap_property_list_truststore=[SSL_TRUSTSTORE_TYPE_PROPERTY,
                                 SSL_TRUSTSTORE_PATH_PROPERTY,
                                 SSL_TRUSTSTORE_PASSWORD_PROPERTY]

  ldap_property_list_passwords=[LDAP_MGR_PASSWORD_PROPERTY,
                                SSL_TRUSTSTORE_PASSWORD_PROPERTY]

  LDAP_MGR_DN_DEFAULT = get_value_from_properties(properties, ldap_property_list_opt[0])

  SSL_TRUSTSTORE_TYPE_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_TYPE_PROPERTY, "jks")
  SSL_TRUSTSTORE_PATH_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_PATH_PROPERTY)


  ldap_property_value_map = {}
  for ldap_prop in ldap_property_list_reqd:
    input = get_validated_string_input(ldap_prop.ldap_prop_val_prompt, ldap_prop.ldap_prop_name, ldap_prop.prompt_regex,
                                       "Invalid characters in the input!", False, ldap_prop.allow_empty_prompt)
    if input is not None and input != "":
      ldap_property_value_map[ldap_prop.prop_name] = input

  bindAnonymously = ldap_property_value_map["authentication.ldap.bindAnonymously"]
  anonymous = (bindAnonymously and bindAnonymously.lower() == 'true')
  mgr_password = None
  # Ask for manager credentials only if bindAnonymously is false
  if not anonymous:
    username = get_validated_string_input("Manager DN* {0}: ".format(
      get_prompt_default(LDAP_MGR_DN_DEFAULT)), LDAP_MGR_DN_DEFAULT, ".*",
                                          "Invalid characters in the input!", False, False)
    ldap_property_value_map[LDAP_MGR_USERNAME_PROPERTY] = username
    mgr_password = configure_ldap_password()
    ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = mgr_password

  useSSL = ldap_property_value_map["authentication.ldap.useSSL"]
  ldaps = (useSSL and useSSL.lower() == 'true')
  ts_password = None

  if ldaps:
    truststore_default = "n"
    truststore_set = bool(SSL_TRUSTSTORE_PATH_DEFAULT)
    if truststore_set:
      truststore_default = "y"
    custom_trust_store = get_YN_input("Do you want to provide custom TrustStore for Ambari [y/n] ({0})?".
                                      format(truststore_default),
                                      truststore_set)
    if custom_trust_store:
      ts_type = get_validated_string_input(
        "TrustStore type [jks/jceks/pkcs12] {0}:".format(get_prompt_default(SSL_TRUSTSTORE_TYPE_DEFAULT)),
        SSL_TRUSTSTORE_TYPE_DEFAULT,
        "^(jks|jceks|pkcs12)?$", "Wrong type", False)
      ts_path = None
      while True:
        ts_path = get_validated_string_input(
          "Path to TrustStore file {0}:".format(get_prompt_default(SSL_TRUSTSTORE_PATH_DEFAULT)),
          SSL_TRUSTSTORE_PATH_DEFAULT,
          ".*", False, False)
        if os.path.exists(ts_path):
          break
        else:
          print 'File not found.'

      ts_password = read_password("", ".*", "Password for TrustStore:", "Invalid characters in password")

      ldap_property_value_map[SSL_TRUSTSTORE_TYPE_PROPERTY] = ts_type
      ldap_property_value_map[SSL_TRUSTSTORE_PATH_PROPERTY] = ts_path
      ldap_property_value_map[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = ts_password
      pass
    else:
      properties.removeOldProp(SSL_TRUSTSTORE_TYPE_PROPERTY)
      properties.removeOldProp(SSL_TRUSTSTORE_PATH_PROPERTY)
      properties.removeOldProp(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
    pass
  pass

  print '=' * 20
  print 'Review Settings'
  print '=' * 20
  for property in ldap_property_list_reqd:
    if property in ldap_property_value_map:
      print("%s: %s" % (property, ldap_property_value_map[property]))

  for property in ldap_property_list_opt:
    if ldap_property_value_map.has_key(property):
      if property not in ldap_property_list_passwords:
        print("%s: %s" % (property, ldap_property_value_map[property]))
      else:
        print("%s: %s" % (property, BLIND_PASSWORD))

  save_settings = get_YN_input("Save settings [y/n] (y)? ", True)

  if save_settings:
    ldap_property_value_map[CLIENT_SECURITY_KEY] = 'ldap'
    if isSecure:
      if mgr_password:
        encrypted_passwd = encrypt_password(LDAP_MGR_PASSWORD_ALIAS, mgr_password)
        if mgr_password != encrypted_passwd:
          ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = encrypted_passwd
      pass
      if ts_password:
        encrypted_passwd = encrypt_password(SSL_TRUSTSTORE_PASSWORD_ALIAS, ts_password)
        if ts_password != encrypted_passwd:
          ldap_property_value_map[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = encrypted_passwd
      pass
    pass

    # Persisting values
    ldap_property_value_map[IS_LDAP_CONFIGURED] = "true"
    if mgr_password:
      ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = store_password_file(mgr_password, LDAP_MGR_PASSWORD_FILENAME)
    update_properties_2(properties, ldap_property_value_map)
    print 'Saving...done'

  return 0
Example #11
0
def setup_master_key():
  if not is_root():
    err = 'Ambari-server setup should be run with ' \
          'root-level privileges'
    raise FatalException(4, err)

  properties = get_ambari_properties()
  if properties == -1:
    raise FatalException(1, "Failed to read properties file.")

  db_windows_auth_prop = properties.get_property(JDBC_USE_INTEGRATED_AUTH_PROPERTY)
  db_sql_auth = False if db_windows_auth_prop and db_windows_auth_prop.lower() == 'true' else True
  db_password = properties.get_property(JDBC_PASSWORD_PROPERTY)
  # Encrypt passwords cannot be called before setup
  if db_sql_auth and not db_password:
    print 'Please call "setup" before "encrypt-passwords". Exiting...'
    return 1

  # Check configuration for location of master key
  isSecure = get_is_secure(properties)
  (isPersisted, masterKeyFile) = get_is_persisted(properties)

  # Read clear text DB password from file
  if db_sql_auth and not is_alias_string(db_password) and os.path.isfile(db_password):
    with open(db_password, 'r') as passwdfile:
      db_password = passwdfile.read()

  ldap_password = properties.get_property(LDAP_MGR_PASSWORD_PROPERTY)
  if ldap_password:
    # Read clear text LDAP password from file
    if not is_alias_string(ldap_password) and os.path.isfile(ldap_password):
      with open(ldap_password, 'r') as passwdfile:
        ldap_password = passwdfile.read()

  ts_password = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  resetKey = False
  masterKey = None

  if isSecure:
    print "Password encryption is enabled."
    resetKey = get_YN_input("Do you want to reset Master Key? [y/n] (n): ", False)

  # For encrypting of only unencrypted passwords without resetting the key ask
  # for master key if not persisted.
  if isSecure and not isPersisted and not resetKey:
    print "Master Key not persisted."
    masterKey = get_original_master_key(properties)
  pass

  # Make sure both passwords are clear-text if master key is lost
  if resetKey:
    if not isPersisted:
      print "Master Key not persisted."
      masterKey = get_original_master_key(properties)
      # Unable get the right master key or skipped question <enter>
      if not masterKey:
        print "To disable encryption, do the following:"
        print "- Edit " + find_properties_file() + \
              " and set " + SECURITY_IS_ENCRYPTION_ENABLED + " = " + "false."
        err = "{0} is already encrypted. Please call {1} to store unencrypted" \
              " password and call 'encrypt-passwords' again."
        if db_sql_auth and db_password and is_alias_string(db_password):
          print err.format('- Database password', "'" + SETUP_ACTION + "'")
        if ldap_password and is_alias_string(ldap_password):
          print err.format('- LDAP manager password', "'" + LDAP_SETUP_ACTION + "'")
        if ts_password and is_alias_string(ts_password):
          print err.format('TrustStore password', "'" + LDAP_SETUP_ACTION + "'")

        return 1
      pass
    pass
  pass

  # Read back any encrypted passwords
  if db_sql_auth  and db_password and is_alias_string(db_password):
    db_password = read_passwd_for_alias(JDBC_RCA_PASSWORD_ALIAS, masterKey)
  if ldap_password and is_alias_string(ldap_password):
    ldap_password = read_passwd_for_alias(LDAP_MGR_PASSWORD_ALIAS, masterKey)
  if ts_password and is_alias_string(ts_password):
    ts_password = read_passwd_for_alias(SSL_TRUSTSTORE_PASSWORD_ALIAS, masterKey)
  # Read master key, if non-secure or reset is true
  if resetKey or not isSecure:
    masterKey = read_master_key(resetKey)
    persist = get_YN_input("Do you want to persist master key. If you choose " \
                           "not to persist, you need to provide the Master " \
                           "Key while starting the ambari server as an env " \
                           "variable named " + SECURITY_KEY_ENV_VAR_NAME + \
                           " or the start will prompt for the master key."
                           " Persist [y/n] (y)? ", True)
    if persist:
      save_master_key(masterKey, get_master_key_location(properties) + os.sep +
                      SECURITY_MASTER_KEY_FILENAME, persist)
    elif not persist and masterKeyFile:
      try:
        os.remove(masterKeyFile)
        print_info_msg("Deleting master key file at location: " + str(
          masterKeyFile))
      except Exception, e:
        print 'ERROR: Could not remove master key file. %s' % e
    # Blow up the credential store made with previous key, if any
    store_file = get_credential_store_location(properties)
    if os.path.exists(store_file):
      try:
        os.remove(store_file)
      except:
        print_warning_msg("Failed to remove credential store file.")
      pass
    pass
Example #12
0
def generate_child_process_param_list(ambari_user, current_user, java_exe,
                                      class_path, debug_start, suspend_mode):
    from ambari_commons.os_linux import ULIMIT_CMD

    properties = get_ambari_properties()

    isSecure = get_is_secure(properties)
    (isPersisted, masterKeyFile) = get_is_persisted(properties)
    environ = os.environ.copy()
    # Need to handle master key not persisted scenario
    if isSecure and not masterKeyFile:
        prompt = False
        masterKey = environ.get(SECURITY_KEY_ENV_VAR_NAME)

        if masterKey is not None and masterKey != "":
            pass
        else:
            keyLocation = environ.get(SECURITY_MASTER_KEY_LOCATION)

            if keyLocation is not None:
                try:
                    # Verify master key can be read by the java process
                    with open(keyLocation, 'r'):
                        pass
                except IOError:
                    print_warning_msg(
                        "Cannot read Master key from path specified in "
                        "environemnt.")
                    prompt = True
            else:
                # Key not provided in the environment
                prompt = True

        if prompt:
            import pwd

            masterKey = get_original_master_key(properties)
            tempDir = tempfile.gettempdir()
            tempFilePath = tempDir + os.sep + "masterkey"
            save_master_key(masterKey, tempFilePath, True)
            if ambari_user != current_user:
                uid = pwd.getpwnam(ambari_user).pw_uid
                gid = pwd.getpwnam(ambari_user).pw_gid
                os.chown(tempFilePath, uid, gid)
            else:
                os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)

            if tempFilePath is not None:
                environ[SECURITY_MASTER_KEY_LOCATION] = tempFilePath

    command_base = SERVER_START_CMD_DEBUG if debug_start else SERVER_START_CMD

    ulimit_cmd = "%s %s" % (ULIMIT_CMD, str(get_ulimit_open_files(properties)))
    command = command_base.format(
        java_exe, ambari_provider_module_option, jvm_args, class_path,
        configDefaults.SERVER_OUT_FILE,
        os.path.join(configDefaults.PID_DIR, EXITCODE_NAME), suspend_mode)

    # required to start properly server instance
    os.chdir(configDefaults.ROOT_FS_PATH)

    #For properly daemonization server should be started using shell as parent
    param_list = [locate_file('sh', '/bin'), "-c"]
    if is_root() and ambari_user != "root":
        # To inherit exported environment variables (especially AMBARI_PASSPHRASE),
        # from subprocess, we have to skip --login option of su command. That's why
        # we change dir to / (otherwise subprocess can face with 'permission denied'
        # errors while trying to list current directory
        cmd = "{ulimit_cmd} ; {su} {ambari_user} -s {sh_shell} -c '{command}'".format(
            ulimit_cmd=ulimit_cmd,
            su=locate_file('su', '/bin'),
            ambari_user=ambari_user,
            sh_shell=locate_file('sh', '/bin'),
            command=command)
    else:
        cmd = "{ulimit_cmd} ; {command}".format(ulimit_cmd=ulimit_cmd,
                                                command=command)

    param_list.append(cmd)
    return (param_list, environ)
def generate_child_process_param_list(ambari_user, current_user, java_exe, class_path, debug_start, suspend_mode):
  from ambari_commons.os_linux import ULIMIT_CMD

  properties = get_ambari_properties()

  isSecure = get_is_secure(properties)
  (isPersisted, masterKeyFile) = get_is_persisted(properties)
  environ = os.environ.copy()
  # Need to handle master key not persisted scenario
  if isSecure and not masterKeyFile:
    prompt = False
    masterKey = environ.get(SECURITY_KEY_ENV_VAR_NAME)

    if masterKey is not None and masterKey != "":
      pass
    else:
      keyLocation = environ.get(SECURITY_MASTER_KEY_LOCATION)

      if keyLocation is not None:
        try:
          # Verify master key can be read by the java process
          with open(keyLocation, 'r'):
            pass
        except IOError:
          print_warning_msg("Cannot read Master key from path specified in "
                            "environemnt.")
          prompt = True
      else:
        # Key not provided in the environment
        prompt = True

    if prompt:
      import pwd

      masterKey = get_original_master_key(properties)
      tempDir = tempfile.gettempdir()
      tempFilePath = tempDir + os.sep + "masterkey"
      save_master_key(masterKey, tempFilePath, True)
      if ambari_user != current_user:
        uid = pwd.getpwnam(ambari_user).pw_uid
        gid = pwd.getpwnam(ambari_user).pw_gid
        os.chown(tempFilePath, uid, gid)
      else:
        os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)

      if tempFilePath is not None:
        environ[SECURITY_MASTER_KEY_LOCATION] = tempFilePath

  command_base = SERVER_START_CMD_DEBUG if debug_start else SERVER_START_CMD

  ulimit_cmd = "%s %s" % (ULIMIT_CMD, str(get_ulimit_open_files(properties)))
  command = command_base.format(java_exe,
          ambari_provider_module_option,
          jvm_args,
          class_path,
          configDefaults.SERVER_OUT_FILE,
          os.path.join(configDefaults.PID_DIR, EXITCODE_NAME),
          suspend_mode)

  # required to start properly server instance
  os.chdir(configDefaults.ROOT_FS_PATH)

  #For properly daemonization server should be started using shell as parent
  param_list = [locate_file('sh', '/bin'), "-c"]
  if is_root() and ambari_user != "root":
    # To inherit exported environment variables (especially AMBARI_PASSPHRASE),
    # from subprocess, we have to skip --login option of su command. That's why
    # we change dir to / (otherwise subprocess can face with 'permission denied'
    # errors while trying to list current directory
    cmd = "{ulimit_cmd} ; {su} {ambari_user} -s {sh_shell} -c '{command}'".format(ulimit_cmd=ulimit_cmd, 
                                                                                su=locate_file('su', '/bin'), ambari_user=ambari_user,
                                                                                sh_shell=locate_file('sh', '/bin'), command=command)
  else:
    cmd = "{ulimit_cmd} ; {command}".format(ulimit_cmd=ulimit_cmd, command=command)
    
  param_list.append(cmd)
  return (param_list, environ)
Example #14
0
def setup_ldap(options):
  logger.info("Setup LDAP.")

  properties = get_ambari_properties()

  server_status, pid = is_server_runing()
  if not server_status:
    err = 'Ambari Server is not running.'
    raise FatalException(1, err)

  current_client_security = get_value_from_properties(properties,CLIENT_SECURITY,"no auth method")
  if current_client_security != 'ldap':
    query = "Currently '" + current_client_security + "' is configured, do you wish to use LDAP instead [y/n] (n)? "
    if get_YN_input(query, False):
      pass
    else:
      err = "Currently '" + current_client_security + "' configured. Can not setup LDAP."
      raise FatalException(1, err)

  isSecure = get_is_secure(properties)

  ldap_property_list_reqd = init_ldap_properties_list_reqd(properties, options)

  ldap_property_list_opt = [LDAP_MGR_USERNAME_PROPERTY,
                            LDAP_MGR_PASSWORD_PROPERTY,
                            SSL_TRUSTSTORE_TYPE_PROPERTY,
                            SSL_TRUSTSTORE_PATH_PROPERTY,
                            SSL_TRUSTSTORE_PASSWORD_PROPERTY]

  ldap_property_list_passwords=[LDAP_MGR_PASSWORD_PROPERTY,
                                SSL_TRUSTSTORE_PASSWORD_PROPERTY]

  LDAP_MGR_DN_DEFAULT = None

  SSL_TRUSTSTORE_TYPE_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_TYPE_PROPERTY, "jks")
  SSL_TRUSTSTORE_PATH_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_PATH_PROPERTY)

  ldap_property_value_map = {}
  for ldap_prop in ldap_property_list_reqd:
    input = get_validated_string_input(ldap_prop.ldap_prop_val_prompt, ldap_prop.ldap_prop_name, ldap_prop.prompt_regex,
                                       "Invalid characters in the input!", False, ldap_prop.allow_empty_prompt,
                                       answer = ldap_prop.option)
    if input is not None and input != "":
      ldap_property_value_map[ldap_prop.prop_name] = input

  bindAnonymously = ldap_property_value_map[LDAP_ANONYMOUS_BIND]
  anonymous = (bindAnonymously and bindAnonymously.lower() == 'true')
  mgr_password = None
  # Ask for manager credentials only if bindAnonymously is false
  if not anonymous:
    username = get_validated_string_input("Manager DN* {0}: ".format(
     get_prompt_default(LDAP_MGR_DN_DEFAULT)), LDAP_MGR_DN_DEFAULT, ".*",
      "Invalid characters in the input!", False, False, answer = options.ldap_manager_dn)
    ldap_property_value_map[LDAP_MGR_USERNAME_PROPERTY] = username
    mgr_password = configure_ldap_password(options)
    ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = mgr_password

  useSSL = ldap_property_value_map[LDAP_USE_SSL]
  ldaps = (useSSL and useSSL.lower() == 'true')
  ts_password = None

  if ldaps:
    truststore_default = "n"
    truststore_set = bool(SSL_TRUSTSTORE_PATH_DEFAULT)
    if truststore_set:
      truststore_default = "y"
    custom_trust_store = True if options.trust_store_path is not None and options.trust_store_path else False
    if not custom_trust_store:
      custom_trust_store = get_YN_input("Do you want to provide custom TrustStore for Ambari [y/n] ({0})?".
                                      format(truststore_default),
                                      truststore_set)
    if custom_trust_store:
      ts_type = get_validated_string_input("TrustStore type [jks/jceks/pkcs12] {0}:".format(get_prompt_default(SSL_TRUSTSTORE_TYPE_DEFAULT)),
        SSL_TRUSTSTORE_TYPE_DEFAULT, "^(jks|jceks|pkcs12)?$", "Wrong type", False, answer=options.trust_store_type)
      ts_path = None
      while True:
        ts_path = get_validated_string_input("Path to TrustStore file {0}:".format(get_prompt_default(SSL_TRUSTSTORE_PATH_DEFAULT)),
          SSL_TRUSTSTORE_PATH_DEFAULT, ".*", False, False, answer = options.trust_store_path)
        if os.path.exists(ts_path):
          break
        else:
          print 'File not found.'
          hasAnswer = options.trust_store_path is not None and options.trust_store_path
          quit_if_has_answer(hasAnswer)

      ts_password = read_password("", ".*", "Password for TrustStore:", "Invalid characters in password", options.trust_store_password)

      ldap_property_value_map[SSL_TRUSTSTORE_TYPE_PROPERTY] = ts_type
      ldap_property_value_map[SSL_TRUSTSTORE_PATH_PROPERTY] = ts_path
      ldap_property_value_map[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = ts_password
      pass
    elif properties.get_property(SSL_TRUSTSTORE_TYPE_PROPERTY):
      print 'The TrustStore is already configured: '
      print '  ' + SSL_TRUSTSTORE_TYPE_PROPERTY + ' = ' + properties.get_property(SSL_TRUSTSTORE_TYPE_PROPERTY)
      print '  ' + SSL_TRUSTSTORE_PATH_PROPERTY + ' = ' + properties.get_property(SSL_TRUSTSTORE_PATH_PROPERTY)
      print '  ' + SSL_TRUSTSTORE_PASSWORD_PROPERTY + ' = ' + properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
      if get_YN_input("Do you want to remove these properties [y/n] (y)? ", True, options.trust_store_reconfigure):
        properties.removeOldProp(SSL_TRUSTSTORE_TYPE_PROPERTY)
        properties.removeOldProp(SSL_TRUSTSTORE_PATH_PROPERTY)
        properties.removeOldProp(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
    pass
  pass

  print '=' * 20
  print 'Review Settings'
  print '=' * 20
  for property in ldap_property_list_reqd:
    if ldap_property_value_map.has_key(property):
      print("%s: %s" % (property, ldap_property_value_map[property]))

  for property in ldap_property_list_opt:
    if ldap_property_value_map.has_key(property):
      if property not in ldap_property_list_passwords:
        print("%s: %s" % (property, ldap_property_value_map[property]))
      else:
        print("%s: %s" % (property, BLIND_PASSWORD))

  save_settings = True if options.ldap_save_settings is not None else get_YN_input("Save settings [y/n] (y)? ", True)

  if save_settings:
    if isSecure:
      if mgr_password:
        encrypted_passwd = encrypt_password(LDAP_MGR_PASSWORD_ALIAS, mgr_password, options)
        if mgr_password != encrypted_passwd:
          ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = encrypted_passwd
      pass
      if ts_password:
        encrypted_passwd = encrypt_password(SSL_TRUSTSTORE_PASSWORD_ALIAS, ts_password, options)
        if ts_password != encrypted_passwd:
          ldap_property_value_map[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = encrypted_passwd
      pass
    pass

    # Persisting values
    if mgr_password:
      ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = store_password_file(mgr_password, LDAP_MGR_PASSWORD_FILENAME)

    print 'Saving LDAP properties...'

    ldap_property_value_map[IS_LDAP_CONFIGURED] = "true"
    #Saving LDAP configuration in Ambari DB using the REST API
    update_ldap_configuration(properties, ldap_property_value_map)

    #The only property we want to write out in Ambari.properties is the client.security type being LDAP
    ldap_property_value_map.clear()
    ldap_property_value_map[CLIENT_SECURITY] = 'ldap'
    update_properties_2(properties, ldap_property_value_map)

    print 'Saving LDAP properties finished'

  return 0