Files
Reims-Go/internal/host/elevate_windows.go
T

230 lines
7.6 KiB
Go

//go:build windows
package host
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
const (
seeMaskNoCloseProcess = 0x00000040
seeMaskNoAsync = 0x00000100
seeMaskFlagNoUI = 0x00000400
// dism.exe exits with ERROR_SUCCESS_REBOOT_REQUIRED when the change worked
// and needs a restart.
dismExitRebootRequired = 3010
hyperVAdminsSID = "S-1-5-32-578"
// How long one wait on the elevated process lasts before the context is checked.
elevateWaitSliceMS = 200
)
var procShellExecuteExW = shell32.NewProc("ShellExecuteExW")
// shellExecuteInfoW mirrors SHELLEXECUTEINFOW.
type shellExecuteInfoW struct {
cbSize uint32
fMask uint32
hwnd uintptr
lpVerb *uint16
lpFile *uint16
lpParameters *uint16
lpDirectory *uint16
nShow int32
hInstApp uintptr
lpIDList uintptr
lpClass *uint16
hkeyClass uintptr
dwHotKey uint32
hIcon windows.Handle
hProcess windows.Handle
}
// systemExe resolves a Windows tool inside System32, so an elevated run never
// follows PATH.
func systemExe(name string) string {
if root := os.Getenv("SystemRoot"); root != "" {
return filepath.Join(root, "System32", name)
}
return name
}
func runElevatedTool(ctx context.Context, exe string, args ...string) (int, string, error) {
cmd := exec.CommandContext(ctx, exe, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
out, err := cmd.CombinedOutput()
text := strings.TrimSpace(string(out))
if err == nil {
return 0, text, nil
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return exitErr.ExitCode(), text, nil
}
return -1, text, err
}
func enableOptionalFeature(ctx context.Context, spec ElevationActionSpec, feature string) (ElevationResult, error) {
code, out, err := runElevatedTool(ctx, systemExe("dism.exe"),
"/Online", "/Enable-Feature", "/FeatureName:"+feature, "/All", "/NoRestart")
if err != nil {
return ElevationResult{Action: spec.Action, ExitCode: code, Error: err.Error()}, err
}
if code == 0 || code == dismExitRebootRequired {
return ElevationResult{OK: true, Action: spec.Action, ExitCode: code, RebootRequired: spec.NeedsReboot}, nil
}
res := ElevationResult{Action: spec.Action, ExitCode: code, Error: out}
return res, fmt.Errorf("dism exited with code %d: %s", code, out)
}
// hyperVAdminsGroupName returns the local name of the Hyper-V Administrators
// group, which Windows localizes; the well-known SID is the stable handle.
func hyperVAdminsGroupName() (string, error) {
sid, err := windows.StringToSid(hyperVAdminsSID)
if err != nil {
return "", err
}
name, _, _, err := sid.LookupAccount("")
if err != nil {
return "", err
}
return name, nil
}
// ExecuteElevatedAction runs a whitelisted action in the current process. The
// process must already be elevated. It never restarts Windows.
func ExecuteElevatedAction(ctx context.Context, action, targetUser string) (ElevationResult, error) {
spec, ok := LookupElevationAction(action)
if !ok {
return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action)
}
switch spec.Action {
case ElevateHyperVEnable:
return enableOptionalFeature(ctx, spec, "Microsoft-Hyper-V-All")
case ElevateSandboxEnable:
return enableOptionalFeature(ctx, spec, "Containers-DisposableClientVM")
case ElevateHyperVAddAdminGroup:
if err := ValidateElevationTargetUser(targetUser); err != nil {
return ElevationResult{Action: action, Error: err.Error()}, err
}
group, err := hyperVAdminsGroupName()
if err != nil {
return ElevationResult{Action: action, Error: err.Error()}, fmt.Errorf("find the Hyper-V Administrators group: %w", err)
}
code, out, err := runElevatedTool(ctx, systemExe("net.exe"), "localgroup", group, strings.TrimSpace(targetUser), "/add")
if err != nil {
return ElevationResult{Action: action, ExitCode: code, Error: err.Error()}, err
}
if code == 0 || isNetAlreadyMemberOutput(out) {
return ElevationResult{OK: true, Action: action, LogoffRequired: spec.NeedsLogoff}, nil
}
return ElevationResult{Action: action, ExitCode: code, Error: out}, fmt.Errorf("net localgroup exited with code %d: %s", code, out)
}
return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action)
}
// RunElevatedAction starts exePath with the hidden __elevate subcommand through
// a UAC prompt and waits for it. The result file is created by the caller
// first and filled in place by the elevated process, so the caller can always
// read and remove it.
func RunElevatedAction(ctx context.Context, exePath, action, targetUser string) (ElevationResult, error) {
spec, ok := LookupElevationAction(action)
if !ok {
return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action)
}
if spec.Action == ElevateHyperVAddAdminGroup {
if err := ValidateElevationTargetUser(targetUser); err != nil {
return ElevationResult{Action: action}, err
}
}
if strings.TrimSpace(exePath) == "" {
return ElevationResult{Action: action}, errors.New("the host executable path is unknown")
}
f, err := os.CreateTemp("", "reims-elevate-*.json")
if err != nil {
return ElevationResult{Action: action}, err
}
resultPath := f.Name()
_ = f.Close()
defer os.Remove(resultPath)
args := []string{"__elevate", "--action", spec.Action, "--result-file", resultPath}
if strings.TrimSpace(targetUser) != "" {
args = append(args, "--user", strings.TrimSpace(targetUser))
}
escaped := make([]string, len(args))
for i, a := range args {
escaped[i] = syscall.EscapeArg(a)
}
verb, _ := syscall.UTF16PtrFromString("runas")
file, err := syscall.UTF16PtrFromString(exePath)
if err != nil {
return ElevationResult{Action: action}, err
}
params, err := syscall.UTF16PtrFromString(strings.Join(escaped, " "))
if err != nil {
return ElevationResult{Action: action}, err
}
sei := shellExecuteInfoW{
fMask: seeMaskNoCloseProcess | seeMaskNoAsync | seeMaskFlagNoUI,
lpVerb: verb,
lpFile: file,
lpParameters: params,
nShow: windows.SW_HIDE,
}
sei.cbSize = uint32(unsafe.Sizeof(sei))
r, _, callErr := procShellExecuteExW.Call(uintptr(unsafe.Pointer(&sei)))
if r == 0 {
if errors.Is(callErr, windows.ERROR_CANCELLED) {
return ElevationResult{Action: action}, ErrElevationDeclined
}
return ElevationResult{Action: action}, fmt.Errorf("ShellExecuteExW runas failed: %w", callErr)
}
var exitCode uint32
if sei.hProcess != 0 {
defer windows.CloseHandle(sei.hProcess)
for {
if ctx.Err() != nil {
return ElevationResult{Action: action}, ctx.Err()
}
ev, werr := windows.WaitForSingleObject(sei.hProcess, elevateWaitSliceMS)
if werr != nil || ev == windows.WAIT_OBJECT_0 {
break
}
}
if err := windows.GetExitCodeProcess(sei.hProcess, &exitCode); err != nil {
return ElevationResult{Action: action}, fmt.Errorf("read the elevated exit code: %w", err)
}
}
if data, rerr := os.ReadFile(resultPath); rerr == nil && len(strings.TrimSpace(string(data))) > 0 {
var res ElevationResult
if jerr := json.Unmarshal(data, &res); jerr == nil {
if res.Action == "" {
res.Action = spec.Action
}
if res.OK {
return res, nil
}
msg := res.Error
if msg == "" {
msg = fmt.Sprintf("the elevated action failed (exit code %d)", exitCode)
}
return res, errors.New(msg)
}
}
if exitCode == 0 {
return ElevationResult{OK: true, Action: spec.Action, RebootRequired: spec.NeedsReboot, LogoffRequired: spec.NeedsLogoff}, nil
}
return ElevationResult{Action: spec.Action, ExitCode: int(exitCode)}, fmt.Errorf("the elevated action exited with code %d", exitCode)
}