feat(host,ui): add a switch to auto-apply ASLR to the selected QEMU runtime

This commit is contained in:
ELDment committed 2026-12-03 22:56:16 +08:00
1 parent 5e9621b7dd
commit b43cd9e16e
28 files changed
+965 -48

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["ELDment"],
"zh": "「内核」页新增 QEMU ASLR 开关,默认关闭。启用后,虚拟机冷启动时可能恢复 Dock 图标。规则随运行时版本切换,关闭时仅移除自动添加的规则。",
"en": "Add an opt-in QEMU ASLR switch on the Engine page. It may restore missing Dock icons after a cold start. Rules follow the selected runtime. Turning it off removes only Reims-Go's rules."
}
+19 -2
View File
@@ -7,13 +7,14 @@ import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib
import { describeHostWHPX } from '../lib/hypervisor'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Switch } from '../ui/settings'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
state: AppState
locale: Locale
onRefresh: () => void
onRefresh: () => Promise<void>
onNewVM?: () => void
onError: (title: string, e: unknown) => void
onToast?: (title: string) => void
@@ -26,6 +27,7 @@ interface Props {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [savingASLR, setSavingASLR] = useState(false)
const [confirmDelete, setConfirmDelete] = useState('')
const [removing, setRemoving] = useState('')
const [storage, setStorage] = useState<StorageBreakdown | null>(null)
@@ -43,7 +45,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
const guard = (fn: () => Promise<unknown>) => async () => {
try {
await fn()
onRefresh()
await onRefresh()
} catch (e) {
onError(tr('failGeneric'), e)
}
@@ -63,6 +65,12 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
}
}
const setQEMUASLR = async (enabled: boolean) => {
setSavingASLR(true)
await guard(() => api.SetQEMUASLR(enabled))()
setSavingASLR(false)
}
const importRuntime = async () => {
setImporting(true)
await guard(async () => {
@@ -207,6 +215,15 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('qemuASLR')}</div>
<div className="row-sub">{tr('qemuASLRHint')}</div>
</div>
<div className="row-right">
<Switch label={tr('qemuASLR')} checked={!!config.qemu_aslr} disabled={savingASLR} onChange={setQEMUASLR} />
</div>
</div>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main">
@@ -448,6 +448,8 @@ export const settingsZh: Record<string, string> = {
"optUnavailable": "不可用",
"pendingChanges": "{n, plural, other {# 项更改,下次启动生效}}",
"platformReadonly": "机型、序列号等平台身份信息不在界面显示",
"qemuASLR": "自动为 QEMU 启用 ASLR",
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
"recommendedBadge": "推荐",
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
@@ -1002,6 +1004,8 @@ export const settingsEn: Record<string, string> = {
"optUnavailable": "Unavailable",
"pendingChanges": "{n, plural, one {# change · applies on next start} other {# changes · applies on next start}}",
"platformReadonly": "Model, serial number and other platform identity are never shown",
"qemuASLR": "Automatically enable ASLR for QEMU",
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
"recommendedBadge": "Recommended",
"resCustom": "Custom",
"resCustomSub": "Width × height",
+2
View File
@@ -831,6 +831,8 @@ export type I18nKey =
| "pluginTrustOfficial"
| "pluginTrustVerified"
| "pluginViewLog"
| "qemuASLR"
| "qemuASLRHint"
| "quitFailed"
| "quitInProgress"
| "recommendedBadge"
+2
View File
@@ -314,6 +314,8 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, any>):Promise<void>;
export function SetQEMUASLR(arg1:boolean):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
+4
View File
@@ -606,6 +606,10 @@ export function SetPluginSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetPluginSettings'](arg1, arg2, arg3);
}
export function SetQEMUASLR(arg1) {
return window['go']['app']['App']['SetQEMUASLR'](arg1);
}
export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
}
+2
View File
@@ -775,6 +775,7 @@ export namespace config {
auto_pin_pcores: boolean;
default_gpu?: string;
runtime_channel?: string;
qemu_aslr?: boolean;
app_update_channel?: string;
minimize_to_tray?: boolean;
sync_host_memory_smbios?: boolean;
@@ -794,6 +795,7 @@ export namespace config {
this.auto_pin_pcores = source["auto_pin_pcores"];
this.default_gpu = source["default_gpu"];
this.runtime_channel = source["runtime_channel"];
this.qemu_aslr = source["qemu_aslr"];
this.app_update_channel = source["app_update_channel"];
this.minimize_to_tray = source["minimize_to_tray"];
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
+30 -10
View File
@@ -747,8 +747,8 @@ func (a *App) emitLog(source, line string) {
func (a *App) GetState() AppState {
a.noteUIAlive()
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
trCopy := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
trCopy[k] = v
@@ -1085,7 +1085,7 @@ func (a *App) SetDataRoot(dir string) error {
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, nextCfg); err != nil {
if err := rt.SavePreferences(nextCfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
@@ -1147,11 +1147,14 @@ func (a *App) OpenProcessorScheduling() error {
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
a.mu.Lock()
cfg := a.cfg
cfg := *a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return nil, err
}
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
inst, err := rt.InstallFromArchive(cfg, archivePath)
inst, err := rt.InstallFromArchive(&cfg, archivePath)
if err != nil {
a.emitLog("runtime", "Install failed: "+err.Error())
if errors.Is(err, rt.ErrRuntimeInUse) {
@@ -1159,19 +1162,36 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
}
return nil, err
}
a.mu.Lock()
a.cfg.ActiveRuntime = inst.Commit
_ = a.saveConfigLocked()
a.mu.Unlock()
if err := a.activateRuntime(cfg.DataRoot, inst.Commit); err != nil {
return nil, err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
return inst, nil
}
func (a *App) UseRuntime(commit string) error {
return a.activateRuntime("", commit)
}
func (a *App) activateRuntime(dataRoot, commit string) error {
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.ActiveRuntime = commit
return a.saveConfigLocked()
if err := a.requireWritableDataRootLocked(); err != nil {
return err
}
if dataRoot != "" && a.cfg.DataRoot != dataRoot {
return errors.New("data folder changed during runtime install")
}
return rt.Activate(a.baseCtx(), a.cfg, commit)
}
func (a *App) SetQEMUASLR(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
if err := a.requireWritableDataRootLocked(); err != nil {
return err
}
return rt.SetQEMUASLR(a.baseCtx(), a.cfg, enabled)
}
func (a *App) RemoveRuntime(commit string) error {
+20 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -55,6 +56,10 @@ func (a *App) dataRootUsable() bool {
func (a *App) requireWritableDataRoot() error {
a.mu.Lock()
defer a.mu.Unlock()
return a.requireWritableDataRootLocked()
}
func (a *App) requireWritableDataRootLocked() error {
if a.needsSetup {
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
}
@@ -72,7 +77,21 @@ func (a *App) saveConfigLocked() error {
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
return err
}
return config.Save("", a.cfg)
return rt.SavePreferences(a.cfg)
}
// runtimeConfig includes the last selection made by either the GUI or CLI.
func (a *App) runtimeConfig() config.Config {
a.mu.Lock()
cfg := *a.cfg
usable := !a.needsSetup && !a.root.ReadOnly
a.mu.Unlock()
if usable {
if err := rt.RefreshSelection(&cfg); err != nil {
a.emitLog("runtime", "Read runtime selection: "+err.Error())
}
}
return cfg
}
// ReopenDataRoot opens the current data folder again: after another process
+1 -7
View File
@@ -16,7 +16,6 @@ import (
"unicode"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/downloader"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/fetch"
@@ -117,12 +116,7 @@ func (a *App) initPlugins() {
})
cb := builtin.HostCallbacks{
GetConfig: func() config.Config {
a.mu.Lock()
cp := *a.cfg
a.mu.Unlock()
return cp
},
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
+3 -7
View File
@@ -90,9 +90,9 @@ func (a *App) SetRuntimeChannel(channel string) error {
// which resumes on the next install.
func (a *App) InstallRuntimeOnline(commit string) (string, error) {
a.mu.Lock()
if a.needsSetup {
if err := a.requireWritableDataRootLocked(); err != nil {
a.mu.Unlock()
return "", errors.New("choose a data folder first")
return "", err
}
cfg := *a.cfg
a.mu.Unlock()
@@ -167,11 +167,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
r.Commit = inst.Commit
}
a.mu.Lock()
a.cfg.ActiveRuntime = r.Commit
err = a.saveConfigLocked()
a.mu.Unlock()
if err != nil {
if err := a.activateRuntime(cfg.DataRoot, r.Commit); err != nil {
return "", err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s (%s) installed and active", r.Commit, r.Channel))
+48
View File
@@ -0,0 +1,48 @@
package app
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/config"
)
func TestRuntimeConfigFollowsExternalSelection(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir, ActiveRuntime: "current"}}
stored := *a.cfg
stored.ActiveRuntime, stored.QEMUASLR = "backup", true
if err := config.Save("", &stored); err != nil {
t.Fatal(err)
}
got := a.runtimeConfig()
if got.ActiveRuntime != "backup" || !got.QEMUASLR {
t.Fatalf("desktop reads stale selection: %+v", got)
}
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
t.Fatal(err)
}
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil {
t.Fatal(err)
}
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
t.Fatalf("saving an unrelated setting lost the selection: %+v", saved)
}
}
func TestPreferencesDoNotOverwriteDamagedConfig(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
path := filepath.Join(dir, "reims-go.json")
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if err := a.SetSyncHostMemorySMBIOS(true); err == nil {
t.Fatal("saved preferences over an unreadable selection")
}
if data, err := os.ReadFile(path); err != nil || string(data) != "{" {
t.Fatalf("damaged config replaced: %q, %v", data, err)
}
}
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -130,7 +131,7 @@ func (a *App) CompleteSetup(dir string) error {
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, cfg); err != nil {
if err := rt.SavePreferences(cfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
+7 -15
View File
@@ -299,8 +299,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
return err
}
cfg.ActiveRuntime = inst.Commit
if err := config.Save("", cfg); err != nil {
if err := rt.Activate(context.Background(), cfg, inst.Commit); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
@@ -335,21 +334,14 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime use <commit>")
}
list, err := rt.List(cfg)
if err != nil {
if err := rt.Activate(context.Background(), cfg, args[1]); err != nil {
if errors.Is(err, rt.ErrNotFound) {
return errors.New(i18n.T(loc, "runtime.not_found", args[1]))
}
return err
}
for _, item := range list {
if item.Commit == args[1] {
cfg.ActiveRuntime = item.Commit
if err := config.Save("", cfg); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", item.Commit))
return nil
}
}
return fmt.Errorf("%s", i18n.T(loc, "runtime.not_found", args[1]))
fmt.Println(i18n.T(loc, "runtime.activated", args[1]))
return nil
case "remove", "rm", "delete":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime remove <commit>")
+1 -2
View File
@@ -90,8 +90,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
_ = os.Remove(path)
r.Commit = inst.Commit
}
cfg.ActiveRuntime = r.Commit
if err := config.Save("", cfg); err != nil {
if err := rt.Activate(ctx, cfg, r.Commit); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", r.Commit))
+10 -3
View File
@@ -19,6 +19,7 @@ type Config struct {
DefaultGPU string `json:"default_gpu,omitempty"`
// RuntimeChannel is "stable" (default, also when empty) or "alpha" (legacy alias "candidate").
RuntimeChannel string `json:"runtime_channel,omitempty"`
QEMUASLR bool `json:"qemu_aslr,omitempty"`
// AppUpdateChannel is "stable" (default, also when empty), "alpha", or "dev":
// controls which Reims-Go client releases CheckAppUpdate offers, and whether
// previous executables/installers are kept on startup for rollback.
@@ -205,11 +206,17 @@ func Load(path string) (*Config, error) {
if path == "" {
path = DefaultConfigPath()
}
cfg, err := LoadExisting(path)
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return cfg, err
}
// LoadExisting reads an existing config and reports a missing file to the caller.
func LoadExisting(path string) (*Config, error) {
raw, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return nil, err
}
cfg := Default()
+3
View File
@@ -0,0 +1,3 @@
package host
const QEMUASLRHelperArg = "--apply-qemu-aslr"
+19
View File
@@ -0,0 +1,19 @@
//go:build !windows
package host
import (
"context"
"errors"
)
func ApplyQEMUASLR(_, _ string) error {
return errors.New("QEMU ASLR requires Windows")
}
func SyncQEMUASLR(_ context.Context, runtimesDir, qemuPath string) error {
if qemuPath == "" {
return nil
}
return ApplyQEMUASLR(runtimesDir, qemuPath)
}
+321
View File
@@ -0,0 +1,321 @@
package host
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
const (
qemuImage = "qemu-system-x86_64.exe"
qemuIFEO = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\` + qemuImage
aslrOriginal = "ReimsGoASLROriginal"
filterMode = "ReimsGoASLRFilterMode"
createdFilter = 1 << 8
createdOptions = 1 << 9
)
// SyncQEMUASLR reconciles this runtime directory's owned mitigations. An empty
// target removes them. No elevation is needed when the rules already match.
func SyncQEMUASLR(ctx context.Context, runtimesDir, qemuPath string) error {
if err := ctx.Err(); err != nil {
return err
}
err := ApplyQEMUASLR(runtimesDir, qemuPath)
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
return err
}
exe, err := os.Executable()
if err != nil {
return err
}
args := windows.ComposeCommandLine([]string{QEMUASLRHelperArg, runtimesDir, qemuPath})
// Once authorized, wait for the helper to finish before the caller commits
// or rolls back the corresponding runtime preference.
code, err := runElevatedWait(context.WithoutCancel(ctx), exe, args)
if err == nil && code != 0 {
return fmt.Errorf("apply QEMU ASLR: helper exited with code %d", code)
}
return err
}
func ApplyQEMUASLR(runtimesDir, qemuPath string) error {
// Separate data directories can share the image key and its UseFilter value.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
name := windows.StringToUTF16Ptr(`Global\Reims-Go-QEMU-ASLR`)
mutex, err := windows.CreateMutex(nil, false, name)
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
return err
}
defer windows.CloseHandle(mutex)
event, err := windows.WaitForSingleObject(mutex, 5000)
if err != nil {
return err
}
if event != windows.WAIT_OBJECT_0 && event != windows.WAIT_ABANDONED {
return errors.New("timed out waiting for the QEMU policy update")
}
defer windows.ReleaseMutex(mutex)
return reconcileQEMUASLR(registry.LOCAL_MACHINE, qemuIFEO, runtimesDir, qemuPath)
}
func runtimeQEMUPath(root, path string) bool {
rel, err := filepath.Rel(root, path)
if err != nil || !filepath.IsLocal(rel) {
return false
}
parts := strings.Split(rel, `\`)
return (len(parts) == 4 || len(parts) == 5) &&
strings.EqualFold(filepath.Join(parts[len(parts)-3:]...), filepath.Join("qemu", "bin", qemuImage))
}
func reconcileQEMUASLR(hive registry.Key, imagePath, root, target string) error {
if !filepath.IsAbs(root) || !strings.EqualFold(filepath.Base(root), "runtimes") ||
(target != "" && (!filepath.IsAbs(target) || filepath.Clean(target) != target || !runtimeQEMUPath(root, target))) {
return fmt.Errorf("invalid QEMU ASLR runtime path %q in %q", target, root)
}
image, err := registry.OpenKey(hive, imagePath, registry.READ)
var createdImage bool
if errors.Is(err, registry.ErrNotExist) {
if target == "" {
return nil
}
var existed bool
image, existed, err = registry.CreateKey(hive, imagePath, registry.READ|registry.WRITE)
createdImage = !existed
}
if err != nil {
return err
}
defer image.Close()
names, err := image.ReadSubKeyNames(-1)
if err != nil {
return err
}
var active string
var stale []string
otherOwner := false
for _, name := range names {
k, err := registry.OpenKey(image, name, registry.QUERY_VALUE)
if err != nil {
return err
}
path, _, pathErr := k.GetStringValue("FilterFullPath")
_, _, markerErr := k.GetIntegerValue(aslrOriginal)
k.Close()
if errors.Is(pathErr, registry.ErrNotExist) {
continue
}
if pathErr != nil {
return pathErr
}
if !runtimeQEMUPath(root, path) {
otherOwner = otherOwner || markerErr == nil
continue
}
if strings.EqualFold(path, target) {
if active != "" {
return fmt.Errorf("multiple QEMU policy filters for %q", path)
}
active = name
} else if markerErr == nil {
stale = append(stale, name)
} else if !errors.Is(markerErr, registry.ErrNotExist) {
return markerErr
}
}
if target != "" {
if err := enableASLRPathFilters(image, createdImage, active == "", len(names)); err != nil {
return err
}
if active == "" {
active = fmt.Sprintf("Reims-Go-%x", sha256.Sum256([]byte(strings.ToLower(target))))
}
if err := updateASLRFilter(image, active, target); err != nil {
return err
}
}
for _, name := range stale {
if err := updateASLRFilter(image, name, ""); err != nil {
return err
}
}
if target != "" || otherOwner {
return nil
}
return restoreASLRFilterMode(hive, imagePath, image)
}
func enableASLRPathFilters(image registry.Key, createdImage, newPath bool, filters int) error {
if newPath {
values, err := image.ReadValueNames(-1)
if err != nil {
return err
}
for _, v := range values {
if !strings.EqualFold(v, "UseFilter") && !strings.EqualFold(v, filterMode) {
return fmt.Errorf("a QEMU path filter would shadow the image-wide Windows setting %q", v)
}
}
}
useFilter, _, err := image.GetIntegerValue("UseFilter")
if err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
if useFilter == 1 {
return nil
}
if filters != 0 || useFilter != 0 {
return errors.New("QEMU has incompatible Windows path filter settings")
}
// 1 = missing UseFilter, 2 = existing zero, 3 = newly created image.
mode := uint32(1)
if createdImage {
mode = 3
} else if err == nil {
mode = 2
}
w, err := registry.OpenKey(image, "", registry.SET_VALUE)
if err != nil {
return err
}
defer w.Close()
if err := w.SetDWordValue(filterMode, mode); err != nil {
return err
}
return w.SetDWordValue("UseFilter", 1)
}
func restoreASLRFilterMode(hive registry.Key, imagePath string, image registry.Key) error {
mode, _, err := image.GetIntegerValue(filterMode)
if errors.Is(err, registry.ErrNotExist) {
return nil
}
if err != nil {
return err
}
info, err := image.Stat()
if err != nil {
return err
}
useFilter, _, err := image.GetIntegerValue("UseFilter")
if err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
w, err := registry.OpenKey(hive, imagePath, registry.READ|registry.WRITE)
if err != nil {
return err
}
defer w.Close()
if useFilter == 1 && info.SubKeyCount == 0 {
if mode == 3 && info.ValueCount == 2 {
return registry.DeleteKey(hive, imagePath)
}
if mode == 2 {
err = w.SetDWordValue("UseFilter", 0)
} else {
err = w.DeleteValue("UseFilter")
}
if err != nil {
return err
}
}
return w.DeleteValue(filterMode)
}
func updateASLRFilter(image registry.Key, name, target string) error {
k, err := registry.OpenKey(image, name, registry.READ)
create := errors.Is(err, registry.ErrNotExist)
if create && target != "" {
var existed bool
k, existed, err = registry.CreateKey(image, name, registry.READ|registry.WRITE)
create = !existed
}
if err != nil {
return err
}
defer k.Close()
if create {
if err := k.SetStringValue("FilterFullPath", target); err != nil {
return err
}
} else if target != "" {
path, _, err := k.GetStringValue("FilterFullPath")
if err != nil || !strings.EqualFold(path, target) {
return fmt.Errorf("QEMU policy filter %q does not match %q", name, target)
}
}
options, _, err := k.GetBinaryValue("MitigationOptions")
newOptions := errors.Is(err, registry.ErrNotExist)
if newOptions {
options = make([]byte, 24)
} else if err != nil {
return err
}
if len(options) < 3 {
return errors.New("invalid QEMU MitigationOptions length")
}
original, _, err := k.GetIntegerValue(aslrOriginal)
owned := err == nil
if !owned && !errors.Is(err, registry.ErrNotExist) {
return err
}
// Windows PROCESS_CREATION_MITIGATION_POLICY_*_ASLR fields occupy bits
// 16..17 (bottom-up) and 20..21 (high entropy); value 1 means always on.
if target != "" && options[2]&0x33 == 0x11 {
return nil
}
w, err := registry.OpenKey(image, name, registry.READ|registry.WRITE)
if err != nil {
return err
}
defer w.Close()
if target != "" {
if !owned {
original = uint64(options[2] & 0x33)
if create {
original |= createdFilter
}
if newOptions {
original |= createdOptions
}
if err := w.SetDWordValue(aslrOriginal, uint32(original)); err != nil {
return err
}
}
options[2] = options[2]&^0x33 | 0x11
return w.SetBinaryValue("MitigationOptions", options)
}
for _, shift := range []uint{0, 4} {
mask := byte(3 << shift)
if options[2]&mask == 1<<shift {
options[2] = (options[2] &^ mask) | byte(original)&mask
}
}
if original&createdOptions != 0 && len(bytes.Trim(options, "\x00")) == 0 {
if err := w.DeleteValue("MitigationOptions"); err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
} else if err := w.SetBinaryValue("MitigationOptions", options); err != nil {
return err
}
info, err := w.Stat()
if err != nil {
return err
}
if original&createdFilter != 0 && info.SubKeyCount == 0 && info.ValueCount == 2 {
// Only our journal and FilterFullPath remain.
return registry.DeleteKey(image, name)
}
return w.DeleteValue(aslrOriginal)
}
+179
View File
@@ -0,0 +1,179 @@
package host
import (
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"golang.org/x/sys/windows/registry"
)
func TestQEMUASLRFollowsRuntimeAndRestoresOnlyOwnedRules(t *testing.T) {
imagePath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
hive := registry.CURRENT_USER
image, _, err := registry.CreateKey(hive, imagePath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer func() {
names, _ := image.ReadSubKeyNames(-1)
for _, name := range names {
if err := registry.DeleteKey(image, name); err != nil {
t.Error(err)
}
}
image.Close()
if err := registry.DeleteKey(hive, imagePath); err != nil {
t.Error(err)
}
}()
root := filepath.Join(t.TempDir(), "runtimes")
current := filepath.Join(root, "current", "qemu", "bin", qemuImage)
backup := filepath.Join(root, "backup", "qemu", "bin", qemuImage)
update := func(target string) {
t.Helper()
if err := reconcileQEMUASLR(hive, imagePath, root, target); err != nil {
t.Fatal(err)
}
}
countFilters := func(want int) {
t.Helper()
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != want {
t.Fatalf("filters = %v, want %d, err = %v", names, want, err)
}
}
update("")
countFilters(0)
update(current)
update(current)
countFilters(1)
readByte := func(k registry.Key, want byte) {
t.Helper()
b, _, err := k.GetBinaryValue("MitigationOptions")
if err != nil || len(b) != 24 || b[2] != want {
t.Fatalf("mitigations = %x, want byte 2 = %02x, err = %v", b, want, err)
}
}
names, _ := image.ReadSubKeyNames(-1)
active, err := registry.OpenKey(image, names[0], registry.READ)
if err != nil {
t.Fatal(err)
}
readByte(active, 0x11)
active.Close()
// One manual OFF override and unrelated bits on the backup runtime.
manual, _, err := registry.CreateKey(image, "User filter", registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer manual.Close()
if err := manual.SetStringValue("FilterFullPath", backup); err != nil {
t.Fatal(err)
}
b := make([]byte, 24)
b[2] = 0x82
if err := manual.SetBinaryValue("MitigationOptions", b); err != nil {
t.Fatal(err)
}
update(backup)
countFilters(1)
readByte(manual, 0x91)
update(current)
countFilters(2)
readByte(manual, 0x82)
update("")
update("")
countFilters(1)
if _, _, err := manual.GetIntegerValue(aslrOriginal); !errors.Is(err, registry.ErrNotExist) {
t.Fatalf("ownership marker remains: %v", err)
}
// Options already ON before enabling continue to belong to the user.
b[2] = 0x91
if err := manual.SetBinaryValue("MitigationOptions", b); err != nil {
t.Fatal(err)
}
update(backup)
update("")
readByte(manual, 0x91)
}
func TestQEMUASLRRestoresImageKey(t *testing.T) {
imagePath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
root := filepath.Join(t.TempDir(), "runtimes")
target := filepath.Join(root, "current", "qemu", "bin", qemuImage)
hive := registry.CURRENT_USER
update := func(target string) error { return reconcileQEMUASLR(hive, imagePath, root, target) }
t.Cleanup(func() {
if err := update(""); err != nil {
t.Error(err)
}
if err := registry.DeleteKey(hive, imagePath); err != nil && !errors.Is(err, registry.ErrNotExist) {
t.Error(err)
}
})
if err := update(target); err != nil {
t.Fatal(err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if k, err := registry.OpenKey(hive, imagePath, registry.READ); !errors.Is(err, registry.ErrNotExist) {
k.Close()
t.Fatalf("new image key not removed: %v", err)
}
image, _, err := registry.CreateKey(hive, imagePath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer image.Close()
if err := image.SetDWordValue("UseFilter", 0); err != nil {
t.Fatal(err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if mode, _, err := image.GetIntegerValue("UseFilter"); err != nil || mode != 0 {
t.Fatalf("restored UseFilter = %v, %v", mode, err)
}
if err := image.SetBinaryValue("MitigationOptions", []byte{1, 0, 0}); err != nil {
t.Fatal(err)
}
if err := update(target); err == nil {
t.Fatal("unexpectedly shadowed image-wide mitigations")
}
if err := image.DeleteValue("MitigationOptions"); err != nil {
t.Fatal(err)
}
if err := image.SetDWordValue("UseFilter", 1); err != nil {
t.Fatal(err)
}
name := fmt.Sprintf("Reims-Go-%x", sha256.Sum256([]byte(strings.ToLower(target))))
filter, _, err := registry.CreateKey(image, name, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer registry.DeleteKey(image, name)
defer filter.Close()
if err := filter.SetStringValue("FilterFullPath", `C:\Other\`+qemuImage); err != nil {
t.Fatal(err)
}
if err := update(target); err == nil {
t.Fatal("unexpectedly adopted a filter for a different executable")
}
if _, _, err := filter.GetBinaryValue("MitigationOptions"); !errors.Is(err, registry.ErrNotExist) {
t.Fatalf("foreign filter was modified: %v", err)
}
}
+10
View File
@@ -32,6 +32,7 @@ type Client struct {
registryDir string
probeGPUs func() []host.GPUInfo
statFile func(string) (os.FileInfo, error)
checkLaunch func(context.Context) error
}
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
@@ -42,6 +43,10 @@ func NewClient(cfg *config.Config, installed rt.Installed) *Client {
if cfg != nil {
c.Locale = cfg.Locale
if cfg.DataRoot != "" {
selection := *cfg
c.checkLaunch = func(ctx context.Context) error {
return rt.CheckLaunchASLR(ctx, selection, installed.QemuPath())
}
c.imagesDir = cfg.ImagesDir()
c.registryDir = filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
for _, entry := range c.Env {
@@ -839,6 +844,11 @@ func (c *Client) Start(ctx context.Context, name string, stdout, stderr io.Write
return err
}
defer release()
if c.checkLaunch != nil {
if err := c.checkLaunch(ctx); err != nil {
return err
}
}
return c.run(ctx, stdout, stderr, "start", name)
}
+33
View File
@@ -0,0 +1,33 @@
package runtime
import (
"context"
"errors"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
)
// CheckLaunchASLR repairs the selected runtime's rule after a data folder
// move and avoids reactivating a version superseded during launch prep.
func CheckLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string) error {
if err := RefreshSelection(&cfg); err != nil || !cfg.QEMUASLR {
return err
}
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
if err != nil {
return err
}
defer release()
if err := RefreshSelection(&cfg); err != nil || !cfg.QEMUASLR {
return err
}
activePath, err := qemuASLRPath(&cfg)
if err != nil {
return err
}
if activePath == "" || !samePath(activePath, qemuPath) {
return errors.New("active runtime changed during VM start")
}
return host.SyncQEMUASLR(ctx, cfg.RuntimesDir(), activePath)
}
+3
View File
@@ -444,6 +444,9 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err
}
func lockRuntimeDirectories(runtimesDir string) (func(), error) {
if err := os.MkdirAll(runtimesDir, 0o755); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-runtime.lock"), 0)
+122
View File
@@ -0,0 +1,122 @@
package runtime
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
)
func Activate(ctx context.Context, cfg *config.Config, commit string) error {
return saveSelection(ctx, cfg, commit, nil, host.SyncQEMUASLR)
}
func SetQEMUASLR(ctx context.Context, cfg *config.Config, enabled bool) error {
return saveSelection(ctx, cfg, "", &enabled, host.SyncQEMUASLR)
}
// RefreshSelection reads the last atomically published selection, without
// waiting for a concurrent install or a pending Windows consent prompt.
func RefreshSelection(cfg *config.Config) error {
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
cfg.ActiveRuntime, cfg.QEMUASLR = saved.ActiveRuntime, saved.QEMUASLR
return nil
}
// SavePreferences keeps an unrelated GUI edit from overwriting a CLI switch.
func SavePreferences(cfg *config.Config) error {
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
if err != nil {
return err
}
defer release()
if err := RefreshSelection(cfg); err != nil {
return err
}
return config.Save("", cfg)
}
func qemuASLRPath(cfg *config.Config) (string, error) {
if !cfg.QEMUASLR {
return "", nil
}
active, err := ResolveActive(cfg)
if errors.Is(err, ErrNoActiveRuntime) {
return "", nil // The first runtime install will apply the preference.
}
if err != nil {
return "", err
}
return active.QemuPath(), nil
}
func saveSelection(ctx context.Context, cfg *config.Config, commit string, aslr *bool, syncPolicy func(context.Context, string, string) error) error {
root := cfg.RuntimesDir()
release, err := lockRuntimeDirectories(root)
if err != nil {
return err
}
defer release()
// Another client may have selected a runtime or changed ASLR since startup.
path := filepath.Join(cfg.DataRoot, "reims-go.json")
prev := *cfg
if saved, err := config.LoadExisting(path); err == nil {
prev = *saved
prev.DataRoot = cfg.DataRoot
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
next := prev
if aslr != nil {
next.QEMUASLR = *aslr
} else {
installed, err := List(&prev)
if err != nil {
return err
}
if !slices.ContainsFunc(installed, func(r Installed) bool {
return r.Commit == commit || r.Kind+"/"+r.Commit == commit
}) {
return fmt.Errorf("%w: %s", ErrNotFound, commit)
}
next.ActiveRuntime = commit
}
managePolicy := aslr != nil || next.QEMUASLR
if managePolicy {
target, pathErr := qemuASLRPath(&next)
if pathErr != nil {
return pathErr
}
err = syncPolicy(ctx, root, target)
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
return err
}
}
if err == nil {
err = config.Save(path, &next)
}
if err != nil && managePolicy {
previousPath, restoreErr := qemuASLRPath(&prev)
if restoreErr == nil {
restoreErr = syncPolicy(context.WithoutCancel(ctx), root, previousPath)
}
return errors.Join(err, restoreErr)
}
if err != nil {
return err
}
cfg.ActiveRuntime, cfg.QEMUASLR = next.ActiveRuntime, next.QEMUASLR
return nil
}
+102
View File
@@ -0,0 +1,102 @@
package runtime
import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
)
func TestSelectionFollowsRuntimeAndToggle(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
var targets []string
sync := func(_ context.Context, root, path string) error {
if root != cfg.RuntimesDir() {
t.Fatalf("unexpected runtimes root %q", root)
}
targets = append(targets, path)
return nil
}
selectRuntime := func(client *config.Config, commit string, toggle *bool) {
t.Helper()
if err := saveSelection(context.Background(), client, commit, toggle, sync); err != nil {
t.Fatal(err)
}
}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
backup := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "backup")}
writeFakeRuntime(t, current.Dir, Manifest{Commit: "current"})
writeFakeRuntime(t, backup.Dir, Manifest{Commit: "backup"})
on, off := true, false
selectRuntime(cfg, "current", nil) // An older config has ASLR off.
stale := *cfg
selectRuntime(cfg, "", &on)
selectRuntime(&stale, "backup", nil) // CLI picks up the desktop preference.
selectRuntime(cfg, "current", nil)
selectRuntime(cfg, "", &off)
selectRuntime(&stale, "backup", nil)
want := []string{current.QemuPath(), backup.QemuPath(), current.QemuPath(), ""}
if !slices.Equal(targets, want) {
t.Fatalf("synced paths = %q, want %q", targets, want)
}
saved, err := config.Load(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || saved.QEMUASLR || saved.ActiveRuntime != "backup" {
t.Fatalf("saved selection = %+v, %v", saved, err)
}
}
func TestSelectionFailureKeepsPreviousRuntime(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true}
for _, commit := range []string{"old", "new"} {
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), commit), Manifest{Commit: commit})
}
if err := config.Save("", cfg); err != nil {
t.Fatal(err)
}
calls := 0
err := saveSelection(context.Background(), cfg, "new", nil, func(context.Context, string, string) error {
calls++
return host.ErrElevationDeclined
})
if !errors.Is(err, host.ErrElevationDeclined) || calls != 1 {
t.Fatalf("declined activation: calls = %d, error = %v", calls, err)
}
// Prevent the atomic config write after a successful host update.
if err := os.Mkdir(filepath.Join(cfg.DataRoot, "reims-go.json.tmp"), 0o755); err != nil {
t.Fatal(err)
}
var applied []string
err = saveSelection(context.Background(), cfg, "new", nil, func(_ context.Context, _, path string) error {
applied = append(applied, path)
return nil
})
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
next := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "new")}
if err == nil || !slices.Equal(applied, []string{next.QemuPath(), old.QemuPath()}) {
t.Fatalf("rollback paths = %v, error = %v", applied, err)
}
saved, err := config.Load(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || cfg.ActiveRuntime != "old" || saved.ActiveRuntime != "old" || !saved.QEMUASLR {
t.Fatalf("failed selection was committed: %+v, %v", saved, err)
}
}
func TestLaunchPolicyRejectsSupersededRuntime(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "backup", QEMUASLR: true}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
writeFakeRuntime(t, current.Dir, Manifest{Commit: "current"})
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "backup"), Manifest{Commit: "backup"})
if err := config.Save("", &cfg); err != nil {
t.Fatal(err)
}
stale := cfg
stale.ActiveRuntime, stale.QEMUASLR = "current", false
if err := CheckLaunchASLR(t.Context(), stale, current.QemuPath()); err == nil {
t.Fatal("launch would reapply policy to the superseded runtime")
}
}
+2
View File
@@ -124,6 +124,8 @@
"guestToolsConnected": "Connected",
"guestToolsReady": "Configured",
"hostRuntime": "Runtime",
"qemuASLR": "Automatically enable ASLR for QEMU",
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
"hostGPUs": "Graphics cards",
"language": "Language",
"languageSub": "Simplified Chinese and English built in; add more via plugins",
+2
View File
@@ -124,6 +124,8 @@
"guestToolsConnected": "已连接",
"guestToolsReady": "已配置",
"hostRuntime": "运行时",
"qemuASLR": "自动为 QEMU 启用 ASLR",
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
"hostGPUs": "显卡",
"language": "语言",
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
+7
View File
@@ -32,6 +32,13 @@ var noticeText string
func main() {
args := os.Args[1:]
if len(args) == 3 && args[0] == host.QEMUASLRHelperArg {
if err := host.ApplyQEMUASLR(args[1], args[2]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if cli.IsCommand(args) {
attachConsole()
os.Exit(cli.Main(args))