Ejemplo n.º 1
0
def check_and_repair_disk(hutil):
    public_settings = hutil.get_public_settings()
    if public_settings:
        check_disk = public_settings.get('check_disk')
        repair_disk = public_settings.get('repair_disk')
        disk_name = public_settings.get('disk_name')

        if check_disk and repair_disk:
            err_msg = ("check_disk and repair_disk was both specified."
                       "Only one of them can be specified")
            hutil.error(err_msg)
            hutil.do_exit(1, 'Enable', 'error', '0', 'Enable failed.')

        if check_disk:
            ext_utils.add_extension_event(name=hutil.get_name(),
                                          op="scenario",
                                          is_success=True,
                                          message="check_disk")
            outretcode = _fsck_check(hutil)
            hutil.log("Successfully checked disk")
            return outretcode

        if repair_disk:
            ext_utils.add_extension_event(name=hutil.get_name(),
                                          op="scenario",
                                          is_success=True,
                                          message="repair_disk")
            outdata = _fsck_repair(hutil, disk_name)
            hutil.log("Repaired and remounted disk")
            return outdata
Ejemplo n.º 2
0
def _forcibly_reset_chap(hutil):
    name = "ChallengeResponseAuthentication"
    config = ext_utils.get_file_contents(SshdConfigPath).split("\n")
    for i in range(0, len(config)):
        if config[i].startswith(name) and "no" in config[i].lower():
            ext_utils.add_extension_event(name=hutil.get_name(), op="sshd", is_success=True,
                                          message="ChallengeResponseAuthentication no")
            return

    ext_utils.add_extension_event(name=hutil.get_name(), op="sshd", is_success=True,
                                  message="ChallengeResponseAuthentication yes")
    _backup_sshd_config(SshdConfigPath)
    _set_sshd_config(config, name, "no")
    ext_utils.replace_file_with_contents_atomic(SshdConfigPath, "\n".join(config))
    MyDistro.restart_ssh_service()
Ejemplo n.º 3
0
def _remove_user_account(user_name, hutil):
    hutil.log("Removing user account")

    try:
        sudoers = _get_other_sudoers(user_name)
        MyDistro.delete_account(user_name)
        _save_other_sudoers(sudoers)
    except Exception as e:
        ext_utils.add_extension_event(name=hutil.get_name(),
                                      op=constants.WALAEventOperation.Enable,
                                      is_success=False,
                                      message="(02102)Failed to remove user.")
        raise Exception("Failed to remove user {0}".format(e))

    ext_utils.add_extension_event(name=hutil.get_name(),
                                  op=constants.WALAEventOperation.Enable,
                                  is_success=True,
                                  message="Successfully removed user")
Ejemplo n.º 4
0
def enable():
    hutil = handler_util.HandlerUtility()
    hutil.do_parse_context('Enable')
    try:
        hutil.exit_if_enabled(
            remove_protected_settings=True)  # If no new seqNum received, exit.

        reset_ssh = None
        remove_user = None
        protect_settings = hutil.get_protected_settings()
        if protect_settings:
            reset_ssh = protect_settings.get('reset_ssh')
            remove_user = protect_settings.get('remove_user')

        if remove_user and _is_sshd_config_modified(protect_settings):
            ext_utils.add_extension_event(
                name=hutil.get_name(),
                op=constants.WALAEventOperation.Enable,
                is_success=False,
                message="(03002)Argument error, conflicting operations")
            raise Exception(
                "Cannot reset sshd_config and remove a user in one operation.")

        _forcibly_reset_chap(hutil)

        if _is_sshd_config_modified(protect_settings):
            _backup_sshd_config(SshdConfigPath)

        if reset_ssh:
            _open_ssh_port()
            hutil.log("Succeeded in check and open ssh port.")
            ext_utils.add_extension_event(name=hutil.get_name(),
                                          op="scenario",
                                          is_success=True,
                                          message="reset-ssh")
            _reset_sshd_config(SshdConfigPath)
            hutil.log("Succeeded in reset sshd_config.")

        if remove_user:
            ext_utils.add_extension_event(name=hutil.get_name(),
                                          op="scenario",
                                          is_success=True,
                                          message="remove-user")
            _remove_user_account(remove_user, hutil)

        _set_user_account_pub_key(protect_settings, hutil)

        if _is_sshd_config_modified(protect_settings):
            MyDistro.restart_ssh_service()

        check_and_repair_disk(hutil)
        hutil.do_exit(0, 'Enable', 'success', '0', 'Enable succeeded.')
    except Exception as e:
        hutil.error(("Failed to enable the extension with error: {0}, "
                     "stack trace: {1}").format(str(e),
                                                traceback.format_exc()))
        hutil.do_exit(1, 'Enable', 'error', '0',
                      "Enable failed: {0}".format(str(e)))
Ejemplo n.º 5
0
def _set_user_account_pub_key(protect_settings, hutil):
    ovf_xml = None
    ovf_env = None
    try:
        ovf_xml = ext_utils.get_file_contents('/var/lib/waagent/ovf-env.xml')
        ovf_env = ovf_utils.OvfEnv.parse(ovf_xml, Configuration)
    except (EnvironmentError, ValueError, KeyError, AttributeError):
        pass
    if ovf_xml is None or ovf_env is None:
        # default ovf_env with empty data
        ovf_env = ovf_utils.OvfEnv()
        logger.log("could not load ovf-env.xml")

    # user name must be provided if set ssh key or password
    if not protect_settings or 'username' not in protect_settings:
        return

    user_name = protect_settings['username']
    user_pass = protect_settings.get('password')
    cert_txt = protect_settings.get('ssh_key')
    expiration = protect_settings.get('expiration')
    no_convert = False
    if not user_pass and not cert_txt and not ovf_env.SshPublicKeys:
        raise Exception("No password or ssh_key is specified.")

    if user_pass is not None and len(user_pass) == 0:
        user_pass = None
        hutil.log("empty passwords are not allowed, ignoring password reset")

    # Reset user account and password, password could be empty
    sudoers = _get_other_sudoers(user_name)
    error_string = MyDistro.create_account(user_name, user_pass, expiration,
                                           None)
    _save_other_sudoers(sudoers)

    if error_string is not None:
        err_msg = "Failed to create the account or set the password"
        ext_utils.add_extension_event(name=hutil.get_name(),
                                      op=constants.WALAEventOperation.Enable,
                                      is_success=False,
                                      message="(02101)" + err_msg)
        raise Exception(err_msg + " with " + error_string)
    hutil.log("Succeeded in creating the account or setting the password.")

    # Allow password authentication if user_pass is provided
    if user_pass is not None:
        ext_utils.add_extension_event(name=hutil.get_name(),
                                      op="scenario",
                                      is_success=True,
                                      message="create-user-with-password")
        _allow_password_auth()

    # Reset ssh key with the new public key passed in or reuse old public key.
    if cert_txt:
        if cert_txt and cert_txt.strip().lower().startswith("ssh-rsa"):
            no_convert = True
        try:
            pub_path = os.path.join('/home/', user_name, '.ssh',
                                    'authorized_keys')
            ovf_env.UserName = user_name
            if no_convert:
                if cert_txt:
                    pub_path = ovf_env.prepare_dir(pub_path, MyDistro)
                    final_cert_txt = cert_txt
                    if not cert_txt.endswith("\n"):
                        final_cert_txt = final_cert_txt + "\n"
                    ext_utils.append_file_contents(pub_path, final_cert_txt)
                    MyDistro.set_se_linux_context(
                        pub_path, 'unconfined_u:object_r:ssh_home_t:s0')
                    ext_utils.change_owner(pub_path, user_name)
                    ext_utils.add_extension_event(name=hutil.get_name(),
                                                  op="scenario",
                                                  is_success=True,
                                                  message="create-user")
                    hutil.log("Succeeded in resetting ssh_key.")
                else:
                    err_msg = "Failed to reset ssh key because the cert content is empty."
                    ext_utils.add_extension_event(
                        name=hutil.get_name(),
                        op=constants.WALAEventOperation.Enable,
                        is_success=False,
                        message="(02100)" + err_msg)
            else:
                # do the certificate conversion
                # we support PKCS8 certificates besides ssh-rsa public keys
                _save_cert_str_as_file(cert_txt, 'temp.crt')
                pub_path = ovf_env.prepare_dir(pub_path, MyDistro)
                retcode = ext_utils.run_command_and_write_stdout_to_file([
                    constants.Openssl, 'x509', '-in', 'temp.crt', '-noout',
                    '-pubkey'
                ], "temp.pub")
                if retcode > 0:
                    raise Exception("Failed to generate public key file.")

                MyDistro.ssh_deploy_public_key('temp.pub', pub_path)
                os.remove('temp.pub')
                os.remove('temp.crt')
                ext_utils.add_extension_event(name=hutil.get_name(),
                                              op="scenario",
                                              is_success=True,
                                              message="create-user")
                hutil.log("Succeeded in resetting ssh_key.")
        except Exception as e:
            hutil.log(str(e))
            ext_utils.add_extension_event(
                name=hutil.get_name(),
                op=constants.WALAEventOperation.Enable,
                is_success=False,
                message="(02100)Failed to reset ssh key.")
            raise e