//go:build windows package host import ( "context" "errors" "fmt" "path/filepath" "syscall" "time" "unsafe" "golang.org/x/sys/windows" "golang.org/x/sys/windows/registry" ) const ( pfVirtFirmwareEnabled = 21 seeMaskNoCloseProcess = 0x00000040 swHide = 0 errorSuccessRebootRequired = 3010 volatileHardwareSystemKey = `HARDWARE\DESCRIPTION\System` deviceGuardKey = `SYSTEM\CurrentControlSet\Control\DeviceGuard` hvciScenarioKey = `SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity` keyGuardStatusSubKey = `SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\KeyGuard\Status` ) var ( procIsProcessorFeaturePresent = kernel32.NewProc("IsProcessorFeaturePresent") procGetTickCount64 = kernel32.NewProc("GetTickCount64") procShellExecuteExW = shell32.NewProc("ShellExecuteExW") ) 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 hIconOrMon uintptr hProcess windows.Handle } func currentBootSession() bootSession { var tickMs uint64 var epochSec int64 if procGetTickCount64.Find() == nil { raw, _, _ := procGetTickCount64.Call() tickMs = uint64(raw) if tickMs > 0 { epochSec = time.Now().Unix() - int64(tickMs/1000) } } return bootSession{ Marker: probeVolatileBootMarker(), EpochSec: epochSec, TickMs: tickMs, } } // probeVolatileBootMarker reads the LastWriteTime of HKLM\HARDWARE\DESCRIPTION\System, // an in-memory REG_OPTION_VOLATILE hive recreated by the Windows kernel on every OS // boot. Unlike wall-clock minus GetTickCount64, it stays constant across S3 sleep, // S4 hibernate, and NTP clock jumps, while changing immediately on even a fast reboot. func probeVolatileBootMarker() string { k, err := registry.OpenKey(registry.LOCAL_MACHINE, volatileHardwareSystemKey, registry.QUERY_VALUE) if err != nil { return "" } defer k.Close() st, err := k.Stat() if err != nil { return "" } ns := st.ModTime().UnixNano() if ns <= 0 { return "" } return fmt.Sprintf("hw:%x", ns) } func probeFirmwareVirtEnabled() bool { if procIsProcessorFeaturePresent.Find() != nil { return false } r, _, _ := procIsProcessorFeaturePresent.Call(uintptr(pfVirtFirmwareEnabled)) return r != 0 } func probeDeviceGuard() (hvciEnabled, vbsRunning bool) { vbsVal, _ := regReadDWORD(hkeyLocalMachine, deviceGuardKey, "EnableVirtualizationBasedSecurity") hvciVal, _ := regReadDWORD(hkeyLocalMachine, hvciScenarioKey, "Enabled") skVal, _ := regReadDWORD(hkeyLocalMachine, keyGuardStatusSubKey, "IsSecureKernelRunning") return EvaluateDeviceGuard(vbsVal, hvciVal, skVal) } func hasWinHvPlatformDLL() bool { mod := syscall.NewLazyDLL("WinHvPlatform.dll") if mod.Load() != nil { return false } return mod.NewProc("WHvGetCapability").Find() == nil } // buildEnableMissingWHPXCmdLine builds the cmd.exe /V:ON /d /s /c argument // string that enables HypervisorPlatform via DISM (accepting both 0 and 3010 // ERROR_SUCCESS_REBOOT_REQUIRED) and then sets hypervisorlaunchtype to auto. func buildEnableMissingWHPXCmdLine(dismCmd, bcdeditCmd string) string { return fmt.Sprintf( `/V:ON /d /s /c "%s & if !errorlevel! equ 0 (%s) else if !errorlevel! equ %d (%s) else (exit /b !errorlevel!)"`, dismCmd, bcdeditCmd, errorSuccessRebootRequired, bcdeditCmd, ) } // SetHypervisorBootElevated prompts for Windows UAC confirmation and updates // the Windows hypervisor boot launch configuration (`bcdedit /set {current} // hypervisorlaunchtype auto|off`). When enabling on a host that has not yet // installed Windows Hypervisor Platform (`WinHvPlatform.dll`), it enables // `HypervisorPlatform` via DISM in the same single UAC elevation. // // It never restarts Windows automatically. If the user declines the UAC prompt, // ErrElevationDeclined is returned. func SetHypervisorBootElevated(ctx context.Context, enable bool) error { sysDir, err := windows.GetSystemDirectory() if err != nil || sysDir == "" { return fmt.Errorf("resolve Windows System32 directory: %w", err) } bcdeditPath := filepath.Join(sysDir, "bcdedit.exe") if !enable { code, err := runElevatedWait(ctx, bcdeditPath, `/set {current} hypervisorlaunchtype off`) if err != nil { return err } if code != 0 { return &HypervisorExecError{Command: "bcdedit", ExitCode: code} } return nil } if hasWinHvPlatformDLL() { code, err := runElevatedWait(ctx, bcdeditPath, `/set {current} hypervisorlaunchtype auto`) if err != nil { return err } if code != 0 { return &HypervisorExecError{Command: "bcdedit", ExitCode: code} } return nil } cmdPath := filepath.Join(sysDir, "cmd.exe") dismPath := filepath.Join(sysDir, "dism.exe") dismCmd := fmt.Sprintf(`"%s" /Online /Enable-Feature /FeatureName:HypervisorPlatform /All /Quiet /NoRestart`, dismPath) bcdCmd := fmt.Sprintf(`"%s" /set {current} hypervisorlaunchtype auto`, bcdeditPath) params := buildEnableMissingWHPXCmdLine(dismCmd, bcdCmd) code, err := runElevatedWait(ctx, cmdPath, params) if err != nil { return err } if code != 0 && code != errorSuccessRebootRequired { return &HypervisorExecError{Command: "dism+bcdedit", ExitCode: code} } return nil } func runElevatedWait(ctx context.Context, exePath, params string) (uint32, error) { if ctx != nil && ctx.Err() != nil { return 0, ctx.Err() } verbPtr, err := syscall.UTF16PtrFromString("runas") if err != nil { return 0, err } filePtr, err := syscall.UTF16PtrFromString(exePath) if err != nil { return 0, err } paramPtr, err := syscall.UTF16PtrFromString(params) if err != nil { return 0, err } sei := shellExecuteInfoW{ fMask: seeMaskNoCloseProcess, lpVerb: verbPtr, lpFile: filePtr, lpParameters: paramPtr, nShow: swHide, } sei.cbSize = uint32(unsafe.Sizeof(sei)) r, _, callErr := procShellExecuteExW.Call(uintptr(unsafe.Pointer(&sei))) if r == 0 { if errors.Is(callErr, windows.ERROR_CANCELLED) || errors.Is(callErr, windows.ERROR_ACCESS_DENIED) || sei.hInstApp == seErrAccessDenied { return 0, ErrElevationDeclined } return 0, fmt.Errorf("ShellExecuteExW runas %s failed (inst=%d): %w", filepath.Base(exePath), sei.hInstApp, callErr) } if sei.hProcess == 0 { return 0, nil } defer windows.CloseHandle(sei.hProcess) for { event, werr := windows.WaitForSingleObject(sei.hProcess, 200) if werr != nil { return 0, fmt.Errorf("WaitForSingleObject(%s): %w", filepath.Base(exePath), werr) } if event == windows.WAIT_OBJECT_0 { break } if event != uint32(windows.WAIT_TIMEOUT) { return 0, fmt.Errorf("WaitForSingleObject(%s): unexpected status 0x%X", filepath.Base(exePath), event) } if ctx != nil && ctx.Err() != nil { return 0, ctx.Err() } } var exitCode uint32 if err := windows.GetExitCodeProcess(sei.hProcess, &exitCode); err != nil { return 0, fmt.Errorf("GetExitCodeProcess(%s): %w", filepath.Base(exePath), err) } return exitCode, nil } // OpenWindowsCoreIsolation opens Windows Security's Core Isolation page so the // user can inspect or toggle Memory Integrity (HVCI) themselves. func OpenWindowsCoreIsolation() error { err := windows.ShellExecute(0, windows.StringToUTF16Ptr("open"), windows.StringToUTF16Ptr("windowsdefender://coreisolation/"), nil, nil, windows.SW_SHOWNORMAL) if err != nil { return fmt.Errorf("open Windows Security Core Isolation: %w", err) } return nil }