diff --git a/internal/exec/exec.go b/internal/exec/exec.go index dc9c3ca..d66c876 100755 --- a/internal/exec/exec.go +++ b/internal/exec/exec.go @@ -48,7 +48,7 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser, // Gets suffix "download//0/script.sh" downloadPathSuffix := scriptPath[len(constants.DataDir):] - // formats into something like "/home//waagent/run-command-handler-runas/download//0/script.sh", This filepath doesn't exist yet. + // formats into something like "/home//waagent/run-command-handler-runas/download//0/script.sh", This filepath shouldn't exist yet. runAsScriptFilePath := filepath.Join(fmt.Sprintf(constants.RunAsDir, cfg.PublicSettings.RunAsUser), downloadPathSuffix) runAsScriptDirectoryPath := filepath.Dir(runAsScriptFilePath) // Get directory of runAsScript that doesn't exist yet @@ -64,24 +64,27 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser, return constants.ExitCode_RunAsOpenSourceScriptFileFailed, errors.Wrap(sourceScriptFileOpenError, errMessage) } - destScriptFile, destScriptCreateError := os.Create(runAsScriptFilePath) + destScriptFile, destScriptCreateError := createRunAsScriptFile(runAsScriptFilePath) if destScriptCreateError != nil { + sourceScriptFile.Close() errMessage := "Failed to create script for Run As in Run As directory. Contact ICM team AzureRT\\Extensions for this service error." ctx.Log("message", errMessage+fmt.Sprintf(" Destination runAs script file is '%s'", runAsScriptFilePath)) return constants.ExitCode_RunAsCreateRunAsScriptFileFailed, errors.Wrap(destScriptCreateError, errMessage) } _, runAsScriptCopyError := io.Copy(destScriptFile, sourceScriptFile) if runAsScriptCopyError != nil { + sourceScriptFile.Close() + destScriptFile.Close() errMessage := fmt.Sprintf("Failed to copy script file '%s' to Run As path '%s'. Contact ICM team AzureRT\\Extensions for this service error.", scriptPath, runAsScriptFilePath) ctx.Log("message", errMessage) return constants.ExitCode_RunAsCopySourceScriptToRunAsScriptFileFailed, errors.Wrap(runAsScriptCopyError, errMessage) } sourceScriptFile.Close() - destScriptFile.Close() // Provide read and execute permissions to RunAsUser on .sh file at runAsScriptFilePath lookedUpUser, lookupUserError := user.Lookup(cfg.PublicSettings.RunAsUser) if lookupUserError != nil { + destScriptFile.Close() errMessage := fmt.Sprintf("Failed to lookup RunAs user '%s'. Looks like user does not exist. For RunAs to work properly, contact admin of VM and make sure RunAs user is added on the VM and user has access to resources accessed by the Run Command (Directories, Files, Network etc.). Refer: https://aka.ms/RunCommandManagedLinux", cfg.PublicSettings.RunAsUser) ctx.Log("message", errMessage) return constants.ExitCode_RunAsLookupUserFailed, errors.Wrap(lookupUserError, errMessage) @@ -89,24 +92,28 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser, lookedUpUserUid, lookedUpUserUidErr := strconv.Atoi(lookedUpUser.Uid) if lookedUpUserUidErr != nil { + destScriptFile.Close() errMessage := "Failed to determine RunAs user's Uid and Guid . Contact ICM team AzureRT\\Extensions for this service error." ctx.Log("message", errMessage) return constants.ExitCode_RunAsLookupUserUidFailed, errors.Wrap(lookedUpUserUidErr, errMessage) } - runAsScriptChownError := os.Chown(runAsScriptFilePath, lookedUpUserUid, os.Getegid()) + runAsScriptChownError := destScriptFile.Chown(lookedUpUserUid, os.Getegid()) if runAsScriptChownError != nil { + destScriptFile.Close() errMessage := fmt.Sprintf("Failed to change owner of file '%s' to RunAs user '%s'. Contact ICM team AzureRT\\Extensions for this service error.", runAsScriptFilePath, cfg.PublicSettings.RunAsUser) ctx.Log("message", errMessage) return constants.ExitCode_RunAsScriptFileChangeOwnerFailed, errors.Wrap(runAsScriptChownError, errMessage) } - runAsScriptChmodError := os.Chmod(runAsScriptFilePath, 0550) + runAsScriptChmodError := destScriptFile.Chmod(0550) if runAsScriptChmodError != nil { + destScriptFile.Close() errMessage := fmt.Sprintf("Failed to change permissions to execute for file '%s' for RunAs user '%s'. Contact ICM team AzureRT\\Extensions for this service error.", runAsScriptFilePath, cfg.PublicSettings.RunAsUser) ctx.Log("message", errMessage) return constants.ExitCode_RunAsScriptFileChangePermissionsFailed, errors.Wrap(runAsScriptChmodError, errMessage) } + destScriptFile.Close() // Execute the command as RunAsUser. -n for non-interactive mode (do not prompt for password) // sudo -n -u @@ -144,6 +151,16 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser, return exitCode, errors.Wrap(err, "failed to execute command") } +func createRunAsScriptFile(path string) (*os.File, error) { + // os.Remove does not follow symlinks, so it is safe to use here. + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return nil, err + } + + // do not follow symlinks to avoid symlink attacks. + return os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0500) +} + func SetEnvironmentVariables(cfg *handlersettings.HandlerSettings) (string, error) { var err error commandArgs := "" diff --git a/internal/exec/exec_test.go b/internal/exec/exec_test.go index 14fb4cf..9f1ad15 100644 --- a/internal/exec/exec_test.go +++ b/internal/exec/exec_test.go @@ -55,6 +55,43 @@ func TestExec_failure_timeout(t *testing.T) { require.EqualValues(t, -1, ec) } +func TestCreateRunAsScriptFile_replacesExistingFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "script.sh") + require.NoError(t, os.WriteFile(path, []byte("old"), 0600)) + + file, err := createRunAsScriptFile(path) + require.NoError(t, err) + _, err = file.Write([]byte("new")) + require.NoError(t, err) + require.NoError(t, file.Close()) + + contents, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, "new", string(contents)) +} + +func TestCreateRunAsScriptFile_doesNotFollowExistingSymlink(t *testing.T) { + dir := t.TempDir() + targetPath := filepath.Join(dir, "target") + scriptPath := filepath.Join(dir, "script.sh") + require.NoError(t, os.WriteFile(targetPath, []byte("protected"), 0600)) + require.NoError(t, os.Symlink(targetPath, scriptPath)) + + file, err := createRunAsScriptFile(scriptPath) + require.NoError(t, err) + _, err = file.Write([]byte("script")) + require.NoError(t, err) + require.NoError(t, file.Close()) + + targetContents, err := os.ReadFile(targetPath) + require.NoError(t, err) + require.Equal(t, "protected", string(targetContents)) + scriptInfo, err := os.Lstat(scriptPath) + require.NoError(t, err) + require.Zero(t, scriptInfo.Mode()&os.ModeSymlink) +} + // func TestExec_runasuser(t *testing.T) { // if os.Geteuid() != 0 { // fmt.Println("SKIP: Should be run under root. Use sudo.")