diff --git a/clean/installer/CMakeLists.txt b/clean/installer/CMakeLists.txt index ff3180db..9b8b5a6d 100644 --- a/clean/installer/CMakeLists.txt +++ b/clean/installer/CMakeLists.txt @@ -129,7 +129,7 @@ add_library(wg_core STATIC src/wg_core/model.cpp src/wg_core/checks.cpp src/wg_core/install.cpp src/wg_core/logs.cpp src/wg_core/profile.cpp src/wg_core/logtail.cpp src/wg_core/launcher.cpp src/wg_core/fingerprint.cpp src/wg_core/optikeys.cpp src/wg_core/leftovers.cpp src/wg_core/rr.cpp src/wg_core/rrprep.cpp src/wg_core/gamerules.cpp - src/wg_core/rrconfig.cpp src/wg_core/convert_ignore.cpp) + src/wg_core/rrconfig.cpp src/wg_core/convert_ignore.cpp src/wg_core/elevated_job.cpp src/wg_core/package_snapshot.cpp src/wg_core/secure_fs.cpp) target_include_directories(wg_core PUBLIC src) target_compile_definitions(wg_core PUBLIC ${PRESET_K_DEFINITION} ${DIRECT_ROUTE_DEFINITION}) # (private: model-choice-tests compiles profile.cpp with the Model L choice on, against this library) diff --git a/clean/installer/README.md b/clean/installer/README.md index a8a83e55..1147bb94 100644 --- a/clean/installer/README.md +++ b/clean/installer/README.md @@ -316,9 +316,28 @@ ctest `source-size`. copied or shipped; games without art get a generated tile), a page per game with cards, custom-drawn menus and dialogs, DPI aware per monitor. Every widget is a UI Automation element with a name (`ui_uia.cpp`); typed text stays in native `EDIT` windows. A game folder that needs - administrator rights goes to the elevated worker: the window writes a job file (operation, exact paths, the - player's `%LOCALAPPDATA%`, the profile) and starts `WrongGPU.exe apply --job= --result=` with `runas`; - the window itself never runs elevated. + administrator rights goes to the elevated worker: the window writes a job file per game (operation, exact paths, + the player's `%LOCALAPPDATA%`, the profile, the OptiScaler package's digest) and a batch file listing each job file + with its SHA-256, makes a reply pipe that only this account and administrators can open, and starts + `WrongGPU.exe apply --batch= --sha256= --pipe=` with `runas` (one permission prompt for + every game); the window itself never runs elevated. The elevated step reads each file once and checks every job + before the first one runs: each SHA-256, every path absolute, and the OptiScaler package of an install, update or + repair copied into a new folder that only administrators can write, installed only from that copy when its digest + is the job's. One job that fails a check: no job runs. The worker writes no log or result file; its log lines and + each job's result come back over the pipe, the window takes them only from the worker it started and only in that + run, and a game without a result there is shown as not reported (`src/wg_core/elevated_job.h`, + `src/wg_core/package_snapshot.h`). The worker acts on files through held handles (`src/wg_core/secure_fs.h`): each + job's folders (the game's, the player's local app data and Documents folders, its own private folder) are opened + before any job runs, from the volume root one folder at a time without following a link, checked to be where the + job's path says (their final path), and held so that none of them can be renamed or replaced until the job ends. + Every file and folder below them is opened the same way relative to the held folder; a junction, a symbolic link or + any other reparse point that leads elsewhere, on any part of a path, is refused with the path named (reparse points + that only store a file differently, such as Windows' compression or OneDrive's files on demand, are opened as the + file itself). Files are written under a new name next to their target and renamed over it through the handle; + renames and deletes go through the file's handle; nothing outside the job's folders is written. The converter reads + private copies and writes into the private folder, from where its output is copied into place through the handles. + The window binds each path of a job to the path Windows reports for it before the prompt, so a game reached through + a link the player made is bound to the real folder. - **Command line** (a verb as the first argument; `src/app/cli.cpp`): `scan`, `status [game]`, `install`, `repair`, `update`, `uninstall`, `rollback`, `adopt [game | --all]`, `set key=value ...`, `set --global key=value`, `get [key]`, `get --global`, `collect [--zip=]`, `hipcheck`, `model status|convert [--preset=M|L]` @@ -326,7 +345,7 @@ ctest `source-size`. `rr-data status|convert [--dll=]` (both converts also take `--ignore=`, `--ignore-list=` and `--library=`: "Ignore lists" below), `self-install [--dir=] [--startmenu=|-]`, `self-uninstall [--keep-games]`, `play `, `update-check`, - `apply --job= --result=` (the elevated worker), `version`, `ui-dump --dump= [--shots=]` (the window's + `apply --batch= --sha256= --pipe=` (the elevated worker), `version`, `ui-dump --dump= [--shots=]` (the window's pages painted offscreen, never shown: their widgets as JSON, PNGs, for tests), `ui-render --out-dir= --fixture=tests/ui_fixture.ini [--size=1180x760] [--scales=1,1.5] [--frames=library,game,...]` (fixture screenshots for development: named frames, among them empty and busy states, a big library, long names, dialogs). A game is its exe, its folder or its install folder. Options: `--out=` (the result as JSON; console output of a GUI program is unreliable), diff --git a/clean/installer/src/app/cli.cpp b/clean/installer/src/app/cli.cpp index e4d9017d..6fc18636 100644 --- a/clean/installer/src/app/cli.cpp +++ b/clean/installer/src/app/cli.cpp @@ -32,8 +32,9 @@ // installed launcher may use it) // play start the game (without the ROCm/HIP SDK variables) // update-check the opt-in release check (no network while it is off or no URL is set) -// apply --job= --result= the elevated worker (started by the window with runas); apply --batch=: -// several jobs in one run (one permission prompt; job= / result= lines, stop=1) +// apply --batch= --sha256= --pipe= the elevated worker (started by the window with runas): the jobs +// of one batch in one run (one permission prompt; job= / sha256= lines, stop=1); its log +// and results go back over the launcher's pipe (elevated_job.h) // ui-dump --dump= [--shots=] [--apply=fps|rrconfig|rrdue] the window's pages painted offscreen, as JSON // (tests; --apply: the checklist's FPS button, the Engine.ini choices, or the choice waiting for the game's folder, applied for real) // ui-render --out-dir= --fixture= [--size=1180x760] [--scales=1,1.5] [--frames=a,b] [--theme=light|dark] fixture screenshots (development) @@ -45,16 +46,19 @@ #include +#include "wg_core/elevated_job.h" #include "wg_core/json_writer.h" #include "wg_core/logs.h" #include "wg_core/model.h" #include "wg_core/optiedition.h" #include "wg_core/optiscaler.h" +#include "wg_core/package_snapshot.h" #include "wg_core/payload.h" #include "wg_core/pe.h" #include "wg_core/rr.h" #include "wg_core/rrconfig.h" #include "wg_core/rrprep.h" +#include "wg_core/secure_fs.h" namespace wg::app { @@ -145,9 +149,10 @@ void OpLogEnd() { } // The elevated worker started with runas for `args`, waited for; false: Windows did not start it (permission not given). -// Called on a worker thread without a message loop: COM is set up for the shell on it, and the shell finishes before it -// returns (SEE_MASK_NOASYNC), as ShellExecuteEx asks of such a thread. -static bool StartElevated(const wstring& args, HWND owner, DWORD& code) { +// `worker`: the process started (the reply pipe takes only its reply, elevated_job.h). Called on a worker thread without a +// message loop: COM is set up for the shell on it, and the shell finishes before it returns (SEE_MASK_NOASYNC), as +// ShellExecuteEx asks of such a thread. +static bool StartElevated(const wstring& args, HWND owner, DWORD& code, ProcessIdentity& worker) { const wstring self = SelfPath(); #ifdef WRONGGPU_TESTING // tests (r2c): every permission prompt the window would raise is written to WRONGGPU_TEST_ELEVATION_LOG. With protected @@ -174,6 +179,7 @@ static bool StartElevated(const wstring& args, HWND owner, DWORD& code) { STARTUPINFOW si{}; si.cb = sizeof(si); PROCESS_INFORMATION pi{}; if (!CreateProcessW(self.c_str(), &cmd[0], nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW, &env[0], nullptr, &si, &pi)) return false; + worker = IdentityOf(pi.hProcess); WaitForSingleObject(pi.hProcess, INFINITE); code = 0; GetExitCodeProcess(pi.hProcess, &code); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); @@ -186,73 +192,40 @@ static bool StartElevated(const wstring& args, HWND owner, DWORD& code) { const bool started = ShellExecuteExW(&sei) && sei.hProcess; if (SUCCEEDED(com)) CoUninitialize(); if (!started) return false; + worker = IdentityOf(sei.hProcess); WaitForSingleObject(sei.hProcess, INFINITE); code = 0; GetExitCodeProcess(sei.hProcess, &code); CloseHandle(sei.hProcess); return true; } -static const wchar_t* const kNotGranted = L"Administrator permission is needed to change this game folder and was not granted."; -OpResult RunElevated(const OpRequest& r, HWND owner) { - OpResult res; - const wstring dir = Join(gl.paths.dataDir, L"jobs"); - EnsureDir(dir); - const wstring stamp = NowStamp(true); - const wstring job = Join(dir, L"job-" + stamp + L".txt"), result = Join(dir, L"result-" + stamp + L".txt"); - const string text = JobText(r, EnvVar(L"LOCALAPPDATA"), Join(Join(gl.paths.dataDir, L"logs"), L"elevated-" + stamp + L".log"), CurrentUserSid(), g.ctx.perGameEntry ? 1 : 0, - PlayerDocumentsDir(g.ctx)); - WriteFileAtomic(job, text.data(), text.size()); - DWORD code = 0; - if (!StartElevated(L"apply \"--job=" + job + L"\" \"--result=" + result + L"\"", owner, code)) { - DeleteFileW(job.c_str()); - res.code = EXIT_REFUSED; - res.message = kNotGranted; - return res; - } - string out; - if (!ReadAll(result, out) || !ParseResult(out, res)) { res.code = code ? (int)code : EXIT_FAILED; res.message = L"The elevated worker gave no result (exit " + std::to_wstring(code) + L")."; } - DeleteFileW(job.c_str()); DeleteFileW(result.c_str()); - return res; -} - -// Several operations in one elevated worker (one permission prompt): "apply --batch=" runs the jobs in order; stop: -// none after the first failure. A result per request (kOpNotRun: not run). +// Several operations in one elevated worker (one permission prompt): the jobs run in order (elevated_job.h); stop: none +// after the first failure. A result per request (kOpNotRun: not run). static std::vector RunElevatedBatch(const std::vector& rs, HWND owner, bool stop) { - std::vector out(rs.size()); - if (rs.empty()) return out; - const wstring dir = Join(gl.paths.dataDir, L"jobs"); - EnsureDir(dir); - const wstring stamp = NowStamp(true); - const wstring log = Join(Join(gl.paths.dataDir, L"logs"), L"elevated-" + stamp + L".log"); - std::vector> files; - for (size_t i = 0; i < rs.size(); ++i) { - const wstring n = std::to_wstring(i + 1); - files.push_back({Join(dir, L"job-" + stamp + L"-" + n + L".txt"), Join(dir, L"result-" + stamp + L"-" + n + L".txt")}); - const string text = JobText(rs[i], EnvVar(L"LOCALAPPDATA"), log, CurrentUserSid(), g.ctx.perGameEntry ? 1 : 0, - PlayerDocumentsDir(g.ctx)); - WriteFileAtomic(files[i].first, text.data(), text.size()); - } - const wstring batch = Join(dir, L"batch-" + stamp + L".txt"); - const string list = BatchText(files, stop); - WriteFileAtomic(batch, list.data(), list.size()); - DWORD code = 0; - const bool started = StartElevated(L"apply \"--batch=" + batch + L"\"", owner, code); - bool failed = false; - for (size_t i = 0; i < rs.size(); ++i) { - string text; - if (!started) { out[i].code = EXIT_REFUSED; out[i].message = kNotGranted; } - else if (!ReadAll(files[i].second, text) || !ParseResult(text, out[i])) { - out[i] = OpResult(); - if (stop && failed) out[i].code = kOpNotRun; - else { out[i].code = code ? (int)code : EXIT_FAILED; out[i].message = L"The elevated worker gave no result (exit " + std::to_wstring(code) + L")."; } - } - failed = failed || (out[i].code != EXIT_OK && out[i].code != kOpNotRun); - DeleteFileW(files[i].first.c_str()); DeleteFileW(files[i].second.c_str()); + std::vector texts; + for (OpRequest r : rs) { + // the paths as this process reaches them (secure_fs.h BoundPath: links and short names resolved here, as the + // player chose them; the worker opens them without following any link and refuses one whose final path differs), + // and the OptiScaler package's digest before the permission prompt (package_snapshot.h: the worker installs only a + // copy with this digest); other operations take no package + r.exe = BoundPath(r.exe); + r.dir = BoundPath(r.dir); + r.modelDll = BoundPath(r.modelDll); + if (r.op == Op::Install || r.op == Op::Update || r.op == Op::Repair) { + if (!r.optiPackage.empty()) { + r.optiPackage = BoundPath(r.optiPackage); + wstring why; + if (!PackageDigest(r.optiPackage, r.optiDigest, why)) LogLine(g.ctx, L"elevated step: " + why); + } + } else r.optiPackage.clear(); + texts.push_back(JobText(r, BoundPath(EnvVar(L"LOCALAPPDATA")), CurrentUserSid(), g.ctx.perGameEntry ? 1 : 0, BoundPath(PlayerDocumentsDir(g.ctx)))); } - DeleteFileW(batch.c_str()); - return out; + const StartWorkerFn start = [owner](const wstring& args, DWORD& code, ProcessIdentity& worker) { return StartElevated(args, owner, code, worker); }; + return RunElevatedJobs(texts, Join(gl.paths.dataDir, L"jobs"), stop, start, [](const wstring& s) { LogLine(g.ctx, s); }); } +OpResult RunElevated(const OpRequest& r, HWND owner) { return RunElevatedBatch({r}, owner, false)[0]; } + std::vector RunElevatedOps(const std::vector& rs, HWND owner, bool stop) { return RunElevatedBatch(rs, owner, stop); } // The per-game operations of the launcher's own install or uninstall, in order: in this process where the folder allows @@ -728,60 +701,36 @@ int Verb(const wstring& verb, const Args& a, Output& o) { ResultJson(o, res); return res.code; } - if (verb == L"apply") { // the elevated worker: one job (--job, --result), or several in one run (--batch: one prompt) + if (verb == L"apply") { // the elevated worker: the jobs of one batch (one prompt); --sha256 binds it to the files of the + // launcher's request, and its log lines and results go back over --pipe (elevated_job.h) bool hiveSet = false; - auto runJob = [&hiveSet](const wstring& job, const wstring& result) { - string text; - OpRequest r; wstring lad, logFile, why, sid, docs; - int perEntry = -1; - OpResult res; - if (job.empty() || result.empty() || !ReadAll(job, text)) { res.code = EXIT_USAGE; res.message = L"apply needs --job= and --result="; } - else if (!ParseJob(text, r, lad, logFile, &why, &sid, &perEntry, &docs)) { res.code = EXIT_USAGE; res.message = L"bad job file: " + why; } - else { - SetEnvironmentVariableW(L"LOCALAPPDATA", lad.c_str()); // the player's model and shared data, not this account's - g.ctx.playerDocuments = docs; // and the player's Documents (rrconfig.h), not this account's - if (!logFile.empty()) g.ctx.logFile = logFile; - // run by another account (an administrator's name typed at the prompt): the Apps & features entries go to the - // player's hive, where the player's launcher and Settings > Apps look - HKEY hive = nullptr; - if (!hiveSet && !sid.empty() && !IEq(sid, CurrentUserSid())) { - hiveSet = true; - if (RegOpenKeyExW(HKEY_USERS, sid.c_str(), 0, KEY_READ | KEY_WRITE, &hive) == ERROR_SUCCESS) SetUninstallHive(hive); - else LogLine(g.ctx, L"elevated worker: the player's registry hive cannot be opened; Apps & features entries go to this account"); - } - g.ctx.perGameEntry = perEntry >= 0 ? perEntry == 1 : !LauncherInstalled(); - Ui ui; ui.step = [](int, int, const wstring&) {}; ui.log = [](const wstring& s) { LogLine(g.ctx, s); }; - LogLine(g.ctx, wstring(L"elevated worker: ") + OpName(r.op) + L" " + (r.dir.empty() ? r.exe : r.dir) + (IsElevated() ? L" (elevated)" : L" (not elevated)")); - res = RunOp(g.ctx, r, ui); + auto runJob = [&hiveSet](const WorkerJob& w) { + SetEnvironmentVariableW(L"LOCALAPPDATA", w.localAppData.c_str()); // the player's model and shared data, not this account's + g.ctx.playerDocuments = w.documents; // and the player's Documents (rrconfig.h), not this account's + // run by another account (an administrator's name typed at the prompt): the Apps & features entries go to the + // player's hive, where the player's launcher and Settings > Apps look + HKEY hive = nullptr; + if (!hiveSet && !w.userSid.empty() && !IEq(w.userSid, CurrentUserSid())) { + hiveSet = true; + if (RegOpenKeyExW(HKEY_USERS, w.userSid.c_str(), 0, KEY_READ | KEY_WRITE, &hive) == ERROR_SUCCESS) SetUninstallHive(hive); + else LogLine(g.ctx, L"elevated worker: the player's registry hive cannot be opened; Apps & features entries go to this account"); } - if (!result.empty()) { const string rt = ResultText(res); try { WriteFileAtomic(result, rt.data(), rt.size()); } catch (const SetupError&) {} } - return res; + g.ctx.perGameEntry = w.perGameEntry >= 0 ? w.perGameEntry == 1 : !LauncherInstalled(); + Ui ui; ui.step = [](int, int, const wstring&) {}; ui.log = [](const wstring& s) { LogLine(g.ctx, s); }; + LogLine(g.ctx, wstring(L"elevated worker: ") + OpName(w.r.op) + L" " + (w.r.dir.empty() ? w.r.exe : w.r.dir) + (IsElevated() ? L" (elevated)" : L" (not elevated)")); + return RunOp(g.ctx, w.r, ui); }; - if (!a.get(L"batch").empty()) { - string text; - std::vector> jobs; - bool stop = false, failed = false; - OpResult last; - if (!ReadAll(a.get(L"batch"), text) || !ParseBatch(text, jobs, stop)) { last.code = EXIT_USAGE; last.message = L"apply --batch needs a file of job= and result= lines"; } - int ran = 0; - for (auto& j : jobs) { - if (stop && failed) { // an earlier game failed: this one is not run, and its result says so - OpResult skip; skip.code = kOpNotRun; skip.message = L"not run: an earlier game failed"; - const string rt = ResultText(skip); - try { WriteFileAtomic(j.second, rt.data(), rt.size()); } catch (const SetupError&) {} - continue; - } - const OpResult res = runJob(j.first, j.second); - ++ran; - if (res.code) { failed = true; last = res; } - } - o.j.N("jobs", (long long)jobs.size()).N("ran", ran); - ResultJson(o, last); - return last.code; - } - const OpResult res = runJob(a.get(L"job"), a.get(L"result")); - ResultJson(o, res); - return res.code; + WorkerArgs wa; + wa.batch = a.get(L"batch"); wa.sha256 = a.get(L"sha256"); wa.pipe = a.get(L"pipe"); + wstring privateParent; // empty: the Windows folder's Temp (package_snapshot.h) +#ifdef WRONGGPU_TESTING + privateParent = BoundPath(EnvVar(L"WRONGGPU_TEST_PRIVATE_DIR")); // tests: the worker's private folder in their work folder +#endif + const WorkerRun run = RunWorker(wa, g.ctx, runJob, privateParent); + if (run.refused) Print(run.last.message); + o.j.N("jobs", (long long)run.jobs).N("ran", run.ran); + ResultJson(o, run.last); + return run.last.code; } if (verb == L"set" || verb == L"get") { if (a.has(L"global")) { @@ -1152,10 +1101,12 @@ int RunCli(int argc, wchar_t** argv) { } else a.pos.push_back(s); } gl.dataOverride = a.get(L"data"); - logFile = a.get(L"log"); - LauncherInit(logFile, verb == L"apply"); + // the elevated worker writes no file of its own (no --log, no --out): its log and result go back over its pipe + const bool worker = verb == L"apply"; + logFile = worker ? wstring() : a.get(L"log"); + LauncherInit(logFile, worker); Output o; - o.outFile = a.get(L"out"); + o.outFile = worker ? wstring() : a.get(L"out"); // `collect` writes a zip: --out is the JSON as everywhere; --zip= names the zip if (!a.get(L"zip").empty()) a.opt[L"out-zip"] = a.get(L"zip"); o.j.Obj().S("verb", verb).S("version", g.ctx.data->version); diff --git a/clean/installer/src/wg_core/checks.cpp b/clean/installer/src/wg_core/checks.cpp index bdcf8ceb..be3bc473 100644 --- a/clean/installer/src/wg_core/checks.cpp +++ b/clean/installer/src/wg_core/checks.cpp @@ -5,6 +5,7 @@ #include #include #include "optiscaler.h" +#include "secure_fs.h" namespace wg { @@ -165,28 +166,36 @@ std::vector HipCandidates() { const wstring env = EnvVar(L"WRONGGPU_HIP_RUNTIME"); if (!env.empty()) c.push_back(env); #endif + // The elevated worker (its guard active, secure_fs.h) probes, as administrator, only the folders that only + // administrators can write (System32, Program Files): never a PATH or HIP_PATH folder, which the player may write. + const bool elevatedWorker = ActiveFsGuard() != nullptr; wchar_t sys[MAX_PATH]; if (GetSystemDirectoryW(sys, MAX_PATH)) c.push_back(Join(sys, kHipDll)); - wstring path = EnvVar(L"PATH"); - if (path.empty()) { // PATH can be longer than EnvVar's buffer + wstring path = elevatedWorker ? wstring() : EnvVar(L"PATH"); + if (path.empty() && !elevatedWorker) { // PATH can be longer than EnvVar's buffer DWORD n = GetEnvironmentVariableW(L"PATH", nullptr, 0); if (n) { path.resize(n); path.resize(GetEnvironmentVariableW(L"PATH", path.data(), n)); } } - for (size_t i = 0; i <= path.size();) { + for (size_t i = 0; i < path.size();) { size_t j = path.find(L';', i); if (j == wstring::npos) j = path.size(); wstring d = path.substr(i, j - i); if (d.size() > 2 && d[1] == L':') c.push_back(Join(d, kHipDll)); // absolute folders only i = j + 1; } - auto dirs = ListDirs(L"C:\\Program Files\\AMD\\ROCm"); + std::vector dirs; + try { dirs = ListDirs(L"C:\\Program Files\\AMD\\ROCm"); } catch (const SetupError&) {} // (a folder the worker's guard refuses) std::sort(dirs.begin(), dirs.end(), [](const wstring& a, const wstring& b) { return VersionLess(BaseName(b), BaseName(a)); }); // newest first for (auto& d : dirs) c.push_back(Join(d, wstring(L"bin\\") + kHipDll)); - wstring hipPath = EnvVar(L"HIP_PATH"); + wstring hipPath = elevatedWorker ? wstring() : EnvVar(L"HIP_PATH"); if (!hipPath.empty()) c.push_back(Join(Join(hipPath, L"bin"), kHipDll)); std::vector out; std::set seen; - for (auto& p : c) if (IsFile(p) && seen.insert(Lower(FullPath(p))).second) out.push_back(FullPath(p)); + for (auto& p : c) { + bool file = false; + try { file = IsFile(p); } catch (const SetupError&) {} // the worker's guard refused it (a link on the way): not a candidate + if (file && seen.insert(Lower(FullPath(p))).second) out.push_back(FullPath(p)); + } return out; } // The architecture name ("gfx1201", ...) in a HIP device-properties structure. The structure's layout differs between @@ -394,6 +403,14 @@ bool IsElevated() { // 0 = writable, otherwise the Win32 error. DWORD WriteTest(const wstring& dir) { wstring p = Join(dir, L".wronggpu-write-test"); + if (ActiveFsGuard()) { // the elevated worker (secure_fs.h): a new file through the guard, then deleted + DeletePath(p); + HANDLE h = CreateNewFile(p); + if (h == INVALID_HANDLE_VALUE) return GetLastError(); + CloseHandle(h); + DeletePath(p); + return 0; + } HANDLE h = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); if (h == INVALID_HANDLE_VALUE) return GetLastError(); CloseHandle(h); diff --git a/clean/installer/src/wg_core/context.cpp b/clean/installer/src/wg_core/context.cpp index fc41f019..97ae83a7 100644 --- a/clean/installer/src/wg_core/context.cpp +++ b/clean/installer/src/wg_core/context.cpp @@ -12,6 +12,7 @@ void LogLine(Context& ctx, const wstring& s) { wchar_t ts[40]; swprintf(ts, 40, L"[%02d:%02d:%02d] ", t.wHour, t.wMinute, t.wSecond); string line = ToUtf8(wstring(ts) + s + L"\r\n"); std::lock_guard lock(ctx.logMutex); // the file's name read under it too (the window can move the log meanwhile) + if (ctx.logSink) { ctx.logSink(s); return; } if (ctx.logFile.empty()) return; // Logging must not write through a junction used as the shared data-folder root, even before uninstall starts. const wstring shared = AppDataPath(), fullShared = FullPath(shared), fullLog = FullPath(ctx.logFile); @@ -37,7 +38,7 @@ wstring AppDataPath() { // %LOCALAPPDATA%\WrongGPU (created on first use). wstring AppDataDir() { const wstring dir = AppDataPath(); - CreateDirectoryW(dir.c_str(), nullptr); + if (!IsDir(dir)) MakeDir(dir); return dir; } wstring DefaultLogPath() { return Join(AppDataDir(), L"setup.log"); } diff --git a/clean/installer/src/wg_core/context.h b/clean/installer/src/wg_core/context.h index 47395fa0..72a58db3 100644 --- a/clean/installer/src/wg_core/context.h +++ b/clean/installer/src/wg_core/context.h @@ -69,6 +69,11 @@ struct Context { const EmbeddedData* data = nullptr; // set before anything else (app/payload_embed.cpp) wstring logFile; // /LOG= or %LOCALAPPDATA%\WrongGPU\setup.log; empty: no log std::mutex logMutex; + // Set: every log line goes here instead of logFile (the elevated worker: back to the launcher, elevated_job.h). + std::function logSink; + // Set: temporary files (the OptiScaler package unpacked, the files an install prepares) go under this folder instead of + // the temp folder (the elevated worker: its folder only administrators can write, package_snapshot.h). + wstring workRoot; #if WRONGGPU_PRESET_K bool presetK = false; // Preset K starts first (/PRESET=K, the wizard's choice) #else diff --git a/clean/installer/src/wg_core/convert_ignore.cpp b/clean/installer/src/wg_core/convert_ignore.cpp index fc45b821..61446629 100644 --- a/clean/installer/src/wg_core/convert_ignore.cpp +++ b/clean/installer/src/wg_core/convert_ignore.cpp @@ -5,6 +5,8 @@ #include #include +#include "secure_fs.h" + namespace wg { bool FileIdent::operator==(const FileIdent& o) const { @@ -197,7 +199,7 @@ bool ParseIgnoreText(const string& bytes, const wstring& source, IgnoreLists& in // The size is checked on the open handle before anything is read. bool ReadIgnoreListBytes(const wstring& file, string& out, wstring& why) { out.clear(); - const DWORD attrs = GetFileAttributesW(file.c_str()); + const DWORD attrs = GetAttrs(file); if (attrs == INVALID_FILE_ATTRIBUTES) { const DWORD err = GetLastError(); why = err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND ? wstring(L"there is no such file") : ErrText(err); @@ -209,7 +211,7 @@ bool ReadIgnoreListBytes(const wstring& file, string& out, wstring& why) { for (int i = 0; i < kIgnoreReadTries; ++i) { if (i) Sleep(kIgnoreReadWaitMs); // FILE_SHARE_READ only: while another program has it open for writing, this waits instead of reading half a list - h = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + h = OpenForRead(file, FILE_SHARE_READ); if (h != INVALID_HANDLE_VALUE) break; err = GetLastError(); if (err != ERROR_SHARING_VIOLATION && err != ERROR_LOCK_VIOLATION) break; @@ -368,7 +370,7 @@ IgnoreLists LoadConvertIgnore(Context& ctx, const wchar_t* what, IgnoreReport* r LogLine(ctx, wstring(what) + L": the ignore list " + f + L" can't be read: " + why); }; for (auto& f : WellKnownIgnoreLists(ctx.ownDataDir)) { - if (GetFileAttributesW(f.c_str()) == INVALID_FILE_ATTRIBUTES) { + if (GetAttrs(f) == INVALID_FILE_ATTRIBUTES) { const DWORD err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) continue; // not there: nothing to read why = ErrText(err); // there, or may be, but not to be looked at (no permission, a bad name): fail closed @@ -430,17 +432,30 @@ static wstring ErrShort(DWORD err) { } // The list to `to`, never over a file that is there: moved (a rename beside it), else copied (a link as the link). 0: done. static DWORD MoveOrCopyList(const wstring& from, const wstring& to, bool link) { - if (MoveFileExW(from.c_str(), to.c_str(), MOVEFILE_WRITE_THROUGH)) return 0; + if (MovePath(from, to, 0)) return 0; const DWORD moveErr = GetLastError(); + if (ActiveFsGuard()) return !Exists(to) && CopyPath(from, to) ? 0 : moveErr; // the elevated worker (secure_fs.h; never a link) BOOL cancel = FALSE; if (CopyFileExW(from.c_str(), to.c_str(), nullptr, nullptr, &cancel, COPY_FILE_FAIL_IF_EXISTS | (link ? COPY_FILE_COPY_SYMLINK : 0))) return 0; return moveErr; } +static ListKept PutBack(Context& ctx, const wstring& moved, const wstring& shared); ListKept PutIgnoreListBack(Context& ctx, const wstring& moved, const wstring& shared) { + try { return PutBack(ctx, moved, shared); } + catch (const SetupError& e) { // the elevated worker's guard refused it (secure_fs.h): the list stays where it is + ListKept r; + r.leftIn = Join(moved, kIgnoreListName); + r.said = L"could not put your ignore-files.txt back into " + shared + L" (" + e.msg + L"); it is kept at " + r.leftIn + L". Move it back to " + + Join(shared, kIgnoreListName) + L" yourself (WrongGPU reads only that one); everything else in that folder is removed."; + LogLine(ctx, L"cleanup: " + r.said); + return r; + } +} +static ListKept PutBack(Context& ctx, const wstring& moved, const wstring& shared) { ListKept r; const wstring from = Join(moved, kIgnoreListName), to = Join(shared, kIgnoreListName); - const DWORD a = GetFileAttributesW(from.c_str()); + const DWORD a = GetAttrs(from); if (a == INVALID_FILE_ATTRIBUTES || (a & FILE_ATTRIBUTE_DIRECTORY)) return r; // no list (a folder of that name is none) const bool link = (a & FILE_ATTRIBUTE_REPARSE_POINT) != 0; if (const PutBackHookFn hook = g_putBackHook.load()) hook(shared); @@ -449,7 +464,7 @@ ListKept PutIgnoreListBack(Context& ctx, const wstring& moved, const wstring& sh // the command-line suites: another program made the folder again with its own list, or a file is where it should be const wstring how = EnvVar(L"WRONGGPU_TEST_LIST_PUTBACK"); if (how == L"exists") { - CreateDirectoryW(shared.c_str(), nullptr); + MakeDir(shared); const string other = "wronggpu-ignore-files 1\r\n# another program's new list (test)\r\n"; WriteFileAtomic(to, other.data(), other.size()); } else if (how == L"blocked") { @@ -458,7 +473,7 @@ ListKept PutIgnoreListBack(Context& ctx, const wstring& moved, const wstring& sh } } #endif - CreateDirectoryW(shared.c_str(), nullptr); + if (!IsDir(shared)) MakeDir(shared); const DWORD err = MoveOrCopyList(from, to, link); if (!err) { r.said = wstring(kKeptIgnoreListText) + L": " + to; @@ -470,9 +485,9 @@ ListKept PutIgnoreListBack(Context& ctx, const wstring& moved, const wstring& sh // under the first free ignore-files.txt.kept-, never over it and never deleted. for (int n = 1; n <= 99; ++n) { const wstring keptAs = to + L".kept-" + std::to_wstring(n); - if (GetFileAttributesW(keptAs.c_str()) != INVALID_FILE_ATTRIBUTES) continue; + if (GetAttrs(keptAs) != INVALID_FILE_ATTRIBUTES) continue; if (MoveOrCopyList(from, keptAs, link)) break; // the folder can't take it: not one name of this kind will do - const bool other = GetFileAttributesW(to.c_str()) != INVALID_FILE_ATTRIBUTES; + const bool other = GetAttrs(to) != INVALID_FILE_ATTRIBUTES; r.said = L"kept your ignore-files.txt as " + keptAs + L": " + (other ? L"another program made " + to + L" again meanwhile, so both are kept" : L"it could not go back to " + to + L" (" + ErrShort(err) + L")") + L". WrongGPU reads only ignore-files.txt: copy the lines you still need from " + BaseName(keptAs) + L" into it, then delete " + diff --git a/clean/installer/src/wg_core/detect.cpp b/clean/installer/src/wg_core/detect.cpp index 1c4dbfdc..96bd6eb8 100644 --- a/clean/installer/src/wg_core/detect.cpp +++ b/clean/installer/src/wg_core/detect.cpp @@ -117,24 +117,21 @@ wstring FindGameExe(const wstring& root, const wstring& hint) { size_t visited = 0; while (!stack.empty() && visited < 20000) { auto [dir, depth] = stack.back(); stack.pop_back(); - WIN32_FIND_DATAW fd; - HANDLE h = FindFirstFileW(Join(dir, L"*").c_str(), &fd); - if (h == INVALID_HANDLE_VALUE) continue; + std::vector entries; + try { if (!ListEntries(dir, entries)) continue; } catch (const SetupError&) { continue; } // (a folder the worker's guard refuses) const size_t first = all.size(); - do { + for (auto& en : entries) { ++visited; - wstring n = fd.cFileName; - if (n == L"." || n == L"..") continue; + const wstring& n = en.name; wstring p = Join(dir, n); - if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - if (depth < 4 && !(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && !IEq(n, kStateDirName) && !IEq(n, kLegacyStateDir)) stack.push_back({p, depth + 1}); + if (en.attrs & FILE_ATTRIBUTE_DIRECTORY) { + if (depth < 4 && !(en.attrs & FILE_ATTRIBUTE_REPARSE_POINT) && !IEq(n, kStateDirName) && !IEq(n, kLegacyStateDir)) stack.push_back({p, depth + 1}); } else if (EndsWithI(n, L".exe") && !LooksLikeHelperExe(p)) { const int name = Contains(n, L"dx12") || Contains(n, L"d3d12") ? 1 : Contains(n, L"dx11") || Contains(n, L"d3d11") || Contains(n, L"vulkan") || Contains(n, L"_vk") ? -1 : 0; - all.push_back({p, ((long long)fd.nFileSizeHigh << 32) | fd.nFileSizeLow, 0, name}); + all.push_back({p, (long long)en.size, 0, name}); } - } while (FindNextFileW(h, &fd)); - FindClose(h); + } if (first == all.size()) continue; int where = 0; for (auto& sl : kSlots) if (IsFile(Join(dir, sl.name))) where = 2; @@ -205,8 +202,10 @@ wstring StoreExe(const wstring& root, const wstring& hint) { // Every game folder of the Steam, Epic and GOG libraries on this PC. Read-only. std::vector ScanLibraries() { std::vector roots; + // In the elevated worker a folder its guard refuses (a link on the way: secure_fs.h) is left out, as a missing one is. + auto isDir = [](const wstring& d) { try { return IsDir(d); } catch (const SetupError&) { return false; } }; auto add = [&](const wstring& name, const wstring& root, const wstring& hint, const wchar_t* source) { - if (name.empty() || root.empty() || !IsDir(root)) return; + if (name.empty() || root.empty() || !isDir(root)) return; for (auto& r : roots) if (IEq(FullPath(r.root), FullPath(root))) return; roots.push_back({name, FullPath(root), hint, source}); }; @@ -216,7 +215,9 @@ std::vector ScanLibraries() { for (auto& c : steam) if (c == L'/') c = L'\\'; std::vector libs{steam}; string raw; - if (ReadAll(Join(steam, L"steamapps\\libraryfolders.vdf"), raw)) { + bool readable = false; + try { readable = ReadAll(Join(steam, L"steamapps\\libraryfolders.vdf"), raw); } catch (const SetupError&) {} + if (readable) { wstring t = FromUtf8(raw); size_t pos = 0; while (pos < t.size()) { size_t nl = t.find(L'\n', pos); wstring line = t.substr(pos, nl == wstring::npos ? wstring::npos : nl - pos); pos = nl == wstring::npos ? t.size() : nl + 1; @@ -228,9 +229,11 @@ std::vector ScanLibraries() { } } for (auto& lib : libs) { - for (auto& acf : ListFiles(Join(lib, L"steamapps"), L"appmanifest_*.acf")) { + std::vector acfs; + try { acfs = ListFiles(Join(lib, L"steamapps"), L"appmanifest_*.acf"); } catch (const SetupError&) { continue; } + for (auto& acf : acfs) { string a; - if (!ReadAll(acf, a)) continue; + try { if (!ReadAll(acf, a)) continue; } catch (const SetupError&) { continue; } wstring t = FromUtf8(a), dir = KeyValue(t, L"installdir"); // benchmarks that ship upscaler test files but are not games (3DMark and its demo) static const wchar_t* const kNotGames[] = {L"223850", L"231350"}; @@ -244,9 +247,11 @@ std::vector ScanLibraries() { // Epic Games Store. wstring pd = EnvVar(L"ProgramData"); if (!pd.empty()) { - for (auto& item : ListFiles(Join(pd, L"Epic\\EpicGamesLauncher\\Data\\Manifests"), L"*.item")) { + std::vector items; + try { items = ListFiles(Join(pd, L"Epic\\EpicGamesLauncher\\Data\\Manifests"), L"*.item"); } catch (const SetupError&) {} + for (auto& item : items) { string raw; - if (!ReadAll(item, raw)) continue; + try { if (!ReadAll(item, raw)) continue; } catch (const SetupError&) { continue; } const StoreGame e = EpicItemGame(FromUtf8(raw)); add(e.name, e.root, e.hint, L"Epic"); } diff --git a/clean/installer/src/wg_core/elevated_job.cpp b/clean/installer/src/wg_core/elevated_job.cpp new file mode 100644 index 00000000..a91b1548 --- /dev/null +++ b/clean/installer/src/wg_core/elevated_job.cpp @@ -0,0 +1,453 @@ +// SPDX-License-Identifier: MIT +// The launcher's elevated step (elevated_job.h): the reply pipe, the worker's checks before it runs anything, and the +// launcher's side of one worker run. Written for this project. +#include "elevated_job.h" + +#include + +#include +#include +#include + +#include "detect.h" // GameRoot +#include "package_snapshot.h" +#include "secure_fs.h" + +namespace wg { + +namespace { + +const wchar_t* const kPipePrefix = L"\\\\.\\pipe\\WrongGPU-reply-"; +const size_t kMaxReply = 4u << 20; // bytes one connection may send +const DWORD kPipeBuffer = 64 * 1024; + +// Records the worker sends: a type byte, a 32-bit job number (1-based; 0: none), a 32-bit length, that many bytes (UTF-8). +enum : char { kRecLog = 'L', kRecResult = 'R', kRecRefused = 'X', kRecEnd = 'E' }; + +struct HandleCloser { void operator()(HANDLE h) const { if (h && h != INVALID_HANDLE_VALUE) CloseHandle(h); } }; +using Held = std::unique_ptr; +Held Hold(HANDLE h) { return Held(h == INVALID_HANDLE_VALUE ? nullptr : h); } + +void PutU32(string& s, uint32_t v) { for (int i = 0; i < 4; ++i) s.push_back((char)((v >> (8 * i)) & 0xff)); } +uint32_t GetU32(const string& s, size_t at) { + uint32_t v = 0; + for (int i = 0; i < 4; ++i) v |= (uint32_t)(unsigned char)s[at + i] << (8 * i); + return v; +} + +// The records of one connection, in order, into a reply. +void ParseRecords(const string& bytes, size_t jobs, WorkerReply& out) { + out.results.assign(jobs, {false, OpResult()}); + size_t at = 0; + while (at + 9 <= bytes.size()) { + const char type = bytes[at]; + const uint32_t n = GetU32(bytes, at + 1), len = GetU32(bytes, at + 5); + if (len > bytes.size() - at - 9) break; + const string body = bytes.substr(at + 9, len); + at += 9 + len; + if (out.complete) break; // nothing counts after the end record + if (type == kRecLog) out.log.push_back(FromUtf8(body)); + else if (type == kRecResult && n >= 1 && n <= jobs) { + OpResult r; + if (ParseResult(body, r)) out.results[n - 1] = {true, r}; + } else if (type == kRecRefused) { + out.refused = ParseResult(body, out.refusal); + } else if (type == kRecEnd) out.complete = true; + } +} + +} // namespace + +const wchar_t* const kElevationNotGranted = L"Administrator permission is needed to change this game folder and was not granted."; + +ProcessIdentity IdentityOf(HANDLE process) { + ProcessIdentity id; + FILETIME created{}, exited{}, kernel{}, user{}; + if (!process || !GetProcessTimes(process, &created, &exited, &kernel, &user)) return id; + id.pid = GetProcessId(process); + id.started = ((unsigned long long)created.dwHighDateTime << 32) | created.dwLowDateTime; + return id; +} + +bool IsReplyPipeName(const wstring& name) { + const wstring pre = kPipePrefix; + if (name.size() != pre.size() + 32 || name.compare(0, pre.size(), pre) != 0) return false; + for (size_t i = pre.size(); i < name.size(); ++i) + if (!((name[i] >= L'0' && name[i] <= L'9') || (name[i] >= L'a' && name[i] <= L'f'))) return false; + return true; +} + +// ---- the reply pipe (the launcher's end) ------------------------------------------------------------------------------ +struct ReplyChannel::Impl { + wstring name; + Held pipe, stop, io; + std::thread reader; + struct Connection { ProcessIdentity who; string bytes; bool ended = false; }; + std::mutex m; + std::vector done; + + // Waits for the pending operation on `ov`; false when stop was signalled first (the operation is then cancelled). The + // operation's own completion is looked at first, so what a finished worker left in the pipe is never cut off. + bool Wait(OVERLAPPED& ov, DWORD& got, bool& ok) { + HANDLE hs[2] = {io.get(), stop.get()}; + const DWORD w = WaitForMultipleObjects(2, hs, FALSE, INFINITE); + if (w == WAIT_OBJECT_0) { ok = GetOverlappedResult(pipe.get(), &ov, &got, FALSE) != FALSE; return true; } + CancelIoEx(pipe.get(), &ov); + GetOverlappedResult(pipe.get(), &ov, &got, TRUE); + return false; + } + void Run() { + for (;;) { + OVERLAPPED ov{}; ov.hEvent = io.get(); + ResetEvent(io.get()); + DWORD got = 0; + bool ok = ConnectNamedPipe(pipe.get(), &ov) != FALSE; + DWORD e = ok ? 0 : GetLastError(); + // connected before this call (and maybe closed again: what it sent is still read) + if (!ok && (e == ERROR_PIPE_CONNECTED || e == ERROR_NO_DATA)) ok = true; + else if (!ok && e == ERROR_IO_PENDING) { if (!Wait(ov, got, ok)) return; } + if (!ok) { + if (WaitForSingleObject(stop.get(), 10) == WAIT_OBJECT_0) return; + DisconnectNamedPipe(pipe.get()); + continue; + } + Connection c; + ULONG pid = 0; + if (GetNamedPipeClientProcessId(pipe.get(), &pid)) { + Held p = Hold(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)); + c.who = IdentityOf(p.get()); + } + bool stopped = false; + std::vector buf(kPipeBuffer); + for (;;) { + OVERLAPPED rv{}; rv.hEvent = io.get(); + ResetEvent(io.get()); + got = 0; + ok = ReadFile(pipe.get(), buf.data(), (DWORD)buf.size(), &got, &rv) != FALSE; + e = ok ? 0 : GetLastError(); + if (!ok && e == ERROR_IO_PENDING) { if (!Wait(rv, got, ok)) { stopped = true; break; } e = ok ? 0 : GetLastError(); } + if (!ok) { c.ended = e == ERROR_BROKEN_PIPE; break; } + c.bytes.append(buf.data(), got); + if (c.bytes.size() > kMaxReply) break; + } + DisconnectNamedPipe(pipe.get()); + { std::lock_guard l(m); done.push_back(std::move(c)); } + if (stopped) return; + } + } +}; + +ReplyChannel::ReplyChannel() : impl_(new Impl) {} +ReplyChannel::~ReplyChannel() { + if (impl_->reader.joinable()) { SetEvent(impl_->stop.get()); impl_->reader.join(); } + delete impl_; +} +const wstring& ReplyChannel::Name() const { return impl_->name; } + +bool ReplyChannel::Create(wstring& why) { + // this account and administrators only; one instance, this computer only, made by this process first (a name that + // is taken is never used) + const wstring me = CurrentUserSid(); + if (me.empty()) { why = L"cannot read this account's SID"; return false; } + const wstring sddl = L"D:P(A;;GA;;;" + me + L")(A;;GA;;;BA)"; + PSECURITY_DESCRIPTOR sd = nullptr; + if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &sd, nullptr)) { + why = L"cannot make the reply pipe's permissions (" + ErrText(GetLastError()) + L")"; + return false; + } + SECURITY_ATTRIBUTES sa{sizeof(sa), sd, FALSE}; + for (int i = 0; i < 4 && !impl_->pipe; ++i) { + impl_->name = kPipePrefix + RandomHex(); + impl_->pipe = Hold(CreateNamedPipeW(impl_->name.c_str(), PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, kPipeBuffer, kPipeBuffer, 0, &sa)); + } + const DWORD e = GetLastError(); + LocalFree(sd); + if (!impl_->pipe) { why = L"cannot make the reply pipe (" + ErrText(e) + L")"; return false; } + impl_->stop = Hold(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + impl_->io = Hold(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + if (!impl_->stop || !impl_->io) { why = L"cannot make the reply pipe's events"; impl_->pipe.reset(); return false; } + impl_->reader = std::thread([this] { impl_->Run(); }); + return true; +} + +WorkerReply ReplyChannel::Finish(const ProcessIdentity& worker, size_t jobs) { + WorkerReply out; + out.results.assign(jobs, {false, OpResult()}); + if (impl_->reader.joinable()) { SetEvent(impl_->stop.get()); impl_->reader.join(); } + if (!worker.pid) return out; + // exactly one connection of the worker that ended normally + const Impl::Connection* from = nullptr; + int count = 0; + for (auto& c : impl_->done) + if (c.who == worker) { ++count; from = &c; } + if (count != 1 || !from->ended) return out; + ParseRecords(from->bytes, jobs, out); + out.connected = true; + return out; +} + +// ---- the launcher's side of one worker run ---------------------------------------------------------------------------- +std::vector RunElevatedJobs(const std::vector& jobTexts, const wstring& jobsDir, bool stop, const StartWorkerFn& start, const LogFn& log) { + const size_t n = jobTexts.size(); + std::vector out(n); + if (!n) return out; + auto all = [&out](int code, const wstring& message) { for (auto& r : out) { r = OpResult(); r.code = code; r.message = message; } return out; }; + std::vector files; + const wstring stamp = NowStamp(true) + L"-" + RandomHex().substr(0, 8); + wstring batch; + auto cleanup = [&] { for (auto& f : files) DeleteFileW(f.c_str()); if (!batch.empty()) DeleteFileW(batch.c_str()); }; + string list; + try { + EnsureDir(jobsDir); + // the folder as the worker finds it (it opens the files without following a link and checks their final path) + const wstring dir = BoundPath(jobsDir); + batch = Join(dir, L"batch-" + stamp + L".txt"); + std::vector> listed; + for (size_t i = 0; i < n; ++i) { + files.push_back(Join(dir, L"job-" + stamp + L"-" + std::to_wstring(i + 1) + L".txt")); + WriteFileAtomic(files[i], jobTexts[i].data(), jobTexts[i].size()); + listed.push_back({files[i], Sha256Bytes(jobTexts[i].data(), jobTexts[i].size())}); + } + list = BatchText(listed, stop); + WriteFileAtomic(batch, list.data(), list.size()); + } catch (const SetupError& e) { + cleanup(); + return all(EXIT_FAILED, L"The elevated step could not be prepared: " + e.msg); + } + ReplyChannel channel; + wstring why; + if (!channel.Create(why)) { cleanup(); return all(EXIT_FAILED, L"The elevated step could not be prepared: " + why + L"."); } + DWORD code = 0; + ProcessIdentity worker; + const bool started = start(L"apply \"--batch=" + batch + L"\" --sha256=" + Sha256Bytes(list.data(), list.size()) + L" --pipe=" + channel.Name(), code, worker); + const WorkerReply reply = channel.Finish(started ? worker : ProcessIdentity(), n); + cleanup(); + if (log) for (auto& line : reply.log) log(L"elevated step: " + line); + if (!started) return all(EXIT_REFUSED, kElevationNotGranted); + if (reply.refused) return all(reply.refusal.code ? reply.refusal.code : EXIT_USAGE, reply.refusal.message); + for (size_t i = 0; i < n; ++i) { + if (reply.results[i].first) { out[i] = reply.results[i].second; continue; } + out[i] = OpResult(); + out[i].code = EXIT_FAILED; + out[i].message = L"The elevated step did not report a result for this game (exit " + std::to_wstring(code) + L"). Check the game before trying again."; + } + if (log && (!reply.connected || !reply.complete)) log(L"elevated step: no complete reply from the worker it started (exit " + std::to_wstring(code) + L")"); + return out; +} + +// ---- the worker ------------------------------------------------------------------------------------------------------- +namespace { + +// The worker's end of the reply pipe. +class Reply { +public: + bool Open(const wstring& name, wstring& why) { + if (!IsReplyPipeName(name)) { why = L"no reply pipe was named"; return false; } + for (int i = 0; i < 3 && !h_; ++i) { + // identification only: the launcher's end never acts as this process + h_ = Hold(CreateFileW(name.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr)); + if (!h_ && GetLastError() == ERROR_PIPE_BUSY) WaitNamedPipeW(name.c_str(), 10000); + else if (!h_) break; + } + if (!h_ || GetFileType(h_.get()) != FILE_TYPE_PIPE) { why = L"the launcher's reply pipe cannot be opened (" + ErrText(GetLastError()) + L")"; h_.reset(); return false; } + return true; + } + void Send(char type, uint32_t n, const string& body) { + std::lock_guard l(m_); + if (!h_) return; + string rec(1, type); + PutU32(rec, n); + PutU32(rec, (uint32_t)body.size()); + rec += body; + DWORD wrote = 0; + if (!WriteFile(h_.get(), rec.data(), (DWORD)rec.size(), &wrote, nullptr) || wrote != rec.size()) h_.reset(); + } + bool ok() const { return (bool)h_; } +private: + Held h_; + std::mutex m_; +}; + +// A file read once into memory (a job or batch file: at most 1 MiB), opened without following a link (secure_fs.h). +bool ReadOnce(const wstring& path, string& bytes, wstring& why) { + if (!IsAbsolutePath(path)) { why = L"not an absolute path: " + path; return false; } + FsGuard reader; // no roots: reading only + ScopedFsGuard active(&reader); + Held h; + try { h = Hold(OpenForRead(path, FILE_SHARE_READ)); } + catch (const SetupError& e) { why = e.msg; return false; } + if (!h) { why = L"cannot open " + path + L" (" + ErrText(GetLastError()) + L")"; return false; } + LARGE_INTEGER size{}; + if (!GetFileSizeEx(h.get(), &size) || size.QuadPart > (1 << 20)) { why = path + L" is not a job file (size)"; return false; } + bytes.resize((size_t)size.QuadPart); + size_t done = 0; + while (done < bytes.size()) { + DWORD got = 0; + if (!ReadFile(h.get(), bytes.data() + done, (DWORD)(bytes.size() - done), &got, nullptr) || !got) { why = L"cannot read " + path; return false; } + done += got; + } + return true; +} + +bool SameHash(const wstring& a, const wstring& b) { return a.size() == 64 && IEq(a, b); } +bool UsesPackage(Op op) { return op == Op::Install || op == Op::Update || op == Op::Repair; } + +// The folders a job may change (secure_fs.h): the worker's private folder, the player's local app data folder, the game's +// folder (its root: GameRoot of the exe's folder or of the job's folder) and the player's Documents folder. Each is opened +// and held by the job's guard before any job runs; one that is not there is not a root (nothing in it is changed: the job +// then fails when it runs, as it would have), one with a link on its way or elsewhere than its path says is refused. +bool GuardJob(const WorkerJob& w, const wstring& privateDir, FsGuard& g, wstring& why) { + std::vector roots{privateDir}, maybe{w.localAppData, w.documents}; + if (!w.r.exe.empty()) maybe.push_back(GameRoot(Parent(w.r.exe))); + if (!w.r.dir.empty()) maybe.push_back(GameRoot(w.r.dir)); + { + FsGuard reader; + ScopedFsGuard active(&reader); + for (auto& m : maybe) { + if (m.empty()) continue; + try { if (IsDir(m)) roots.push_back(m); } + catch (const SetupError& e) { why = e.msg; return false; } + } + } + std::vector added; + for (auto& r : roots) { + bool dup = false; + for (auto& a : added) dup = dup || IEq(NormalPath(a), NormalPath(r)); + if (dup) continue; + if (!g.AddRoot(r, why)) return false; + added.push_back(r); + } + return true; +} + +} // namespace + +WorkerRun RunWorker(const WorkerArgs& a, Context& ctx, const WorkerRunFn& run, const wstring& privateParent) { + WorkerRun out; + Reply reply; + wstring why; + out.last.code = EXIT_USAGE; + if (!reply.Open(a.pipe, why)) { // no way to report: nothing is run + out.refused = true; + out.last.message = L"The elevated step did not run: " + why + L"."; + return out; + } + // from here on the log lines go back to the launcher; the private folder and the log sink are undone on every return + wstring privateDir; + const auto oldSink = ctx.logSink; + const wstring oldRoot = ctx.workRoot; + { + std::lock_guard l(ctx.logMutex); + ctx.logSink = [&reply](const wstring& s) { reply.Send(kRecLog, 0, ToUtf8(s)); }; + } + struct Undo { + Context& ctx; const std::function& sink; const wstring& root; wstring& dir; + ~Undo() { + if (!dir.empty()) { + if (!ctx.opti.tempDir.empty() && StartsWithI(ctx.opti.tempDir, dir)) ctx.opti = OptiPackage(); + if (!ctx.opti.dir.empty() && StartsWithI(ctx.opti.dir, dir)) ctx.opti = OptiPackage(); + // removed below its parent's held handle (the jobs' guards, which hold the folder itself, are gone by now) + try { + FsGuard g; + wstring why; + if (g.AddRoot(Parent(dir), why)) { ScopedFsGuard active(&g); RemoveTree(dir); } + } catch (const SetupError&) {} + } + ctx.workRoot = root; + std::lock_guard l(ctx.logMutex); + ctx.logSink = sink; + } + } undo{ctx, oldSink, oldRoot, privateDir}; + auto refuse = [&](const wstring& reason) { + out.refused = true; + out.ran = 0; + out.last = OpResult(); + out.last.code = EXIT_USAGE; + out.last.message = L"The elevated step did not run: " + reason + L"."; + LogLine(ctx, L"elevated worker: refused: " + reason); + reply.Send(kRecRefused, 0, ResultText(out.last)); + reply.Send(kRecEnd, 0, ""); + return out; + }; + + // 1. the batch and every job file, each read once and checked against the request + if (a.batch.empty() || a.sha256.empty()) return refuse(L"apply needs --batch=, --sha256= and --pipe="); + string text; + if (!ReadOnce(a.batch, text, why)) return refuse(why); + if (!SameHash(Sha256Bytes(text.data(), text.size()), a.sha256)) + return refuse(BaseName(a.batch) + L" is not the file the launcher wrote for this request (SHA-256 mismatch)"); + std::vector> listed; + bool stop = false; + if (!ParseBatch(text, listed, stop, &why)) return refuse(L"bad batch file: " + why); + out.jobs = (int)listed.size(); + std::vector jobs(listed.size()); + for (size_t i = 0; i < listed.size(); ++i) { + const wstring label = L"job " + std::to_wstring(i + 1) + L" (" + BaseName(listed[i].first) + L")"; + string jt; + if (!ReadOnce(listed[i].first, jt, why)) return refuse(label + L": " + why); + if (!SameHash(Sha256Bytes(jt.data(), jt.size()), listed[i].second)) + return refuse(label + L" is not the job file the launcher wrote for this request (SHA-256 mismatch)"); + WorkerJob& w = jobs[i]; + if (!ParseJob(jt, w.r, w.localAppData, &why, &w.userSid, &w.perGameEntry, &w.documents)) return refuse(label + L": bad job file: " + why); + } + + // 2. the private folder for this run's temporary files, and the OptiScaler packages copied into it and checked (the + // package read and the copy written through a guard whose one root is the private folder: secure_fs.h) + if (!MakePrivateFolder(privateParent, privateDir, why)) { privateDir.clear(); return refuse(why); } + ctx.workRoot = privateDir; + { + FsGuard snapshot; + if (!snapshot.AddRoot(privateDir, why)) return refuse(why); + ScopedFsGuard active(&snapshot); + std::map copies; // package path + digest -> its checked copy + for (size_t i = 0; i < jobs.size(); ++i) { + OpRequest& r = jobs[i].r; + if (!UsesPackage(r.op)) { r.optiPackage.clear(); r.optiDigest.clear(); continue; } + if (r.optiPackage.empty()) continue; + const wstring key = Lower(FullPath(r.optiPackage)) + L"|" + Lower(r.optiDigest); + auto it = copies.find(key); + if (it == copies.end()) { + const wstring into = Join(privateDir, L"package-" + std::to_wstring(copies.size() + 1)); + wstring copy; + try { EnsureDir(into); } catch (const SetupError& e) { return refuse(e.msg); } + if (!SnapshotPackage(r.optiPackage, r.optiDigest, into, copy, why)) return refuse(L"job " + std::to_wstring(i + 1) + L": " + why); + LogLine(ctx, L"elevated worker: OptiScaler package " + r.optiPackage + L" checked (" + r.optiDigest.substr(0, 12) + L")"); + it = copies.emplace(key, copy).first; + } + r.optiPackage = it->second; + } + } + + // 3. every job's folders opened and held without following a link, each where its path says (secure_fs.h): a job whose + // folder fails this runs, like any job that fails a check, no job at all + std::vector> guards; + for (size_t i = 0; i < jobs.size(); ++i) { + guards.push_back(std::make_unique()); + if (!GuardJob(jobs[i], privateDir, *guards.back(), why)) + return refuse(L"job " + std::to_wstring(i + 1) + L" (" + BaseName(listed[i].first) + L"): " + why); + } + + // 4. every job checked: run them in order, each through its guard + bool failed = false; + out.last = OpResult(); + for (size_t i = 0; i < jobs.size(); ++i) { + OpResult res; + if (stop && failed) { + res.code = kOpNotRun; + res.message = L"not run: an earlier game failed"; + } else { + ScopedFsGuard active(guards[i].get()); + try { res = run(jobs[i]); } + catch (const SetupError& e) { res = OpResult(); res.code = e.code ? e.code : EXIT_FAILED; res.message = e.msg; } + ++out.ran; + if (res.code) { failed = true; out.last = res; } + } + reply.Send(kRecResult, (uint32_t)(i + 1), ResultText(res)); + } + guards.clear(); + reply.Send(kRecEnd, 0, ""); + return out; +} + +} // namespace wg diff --git a/clean/installer/src/wg_core/elevated_job.h b/clean/installer/src/wg_core/elevated_job.h new file mode 100644 index 00000000..42ebcc71 --- /dev/null +++ b/clean/installer/src/wg_core/elevated_job.h @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: MIT +// The launcher's elevated step ("WrongGPU.exe apply"): the launcher's side (RunElevatedJobs) and the worker's (RunWorker). +// +// The launcher writes one job file per operation (launcher.h JobText) and a batch file listing each job file with its +// SHA-256 (BatchText) into its jobs folder, creates a reply pipe with a random name that only this account and +// administrators can open (ReplyChannel), and starts the worker with runas: +// WrongGPU.exe apply --batch=\batch-.txt --sha256= --pipe=\\.\pipe\WrongGPU-reply- +// The worker +// - runs nothing without the reply pipe; +// - reads the batch file and every job file once into memory, checks each SHA-256 against the command line and the batch +// and parses those same bytes; +// - checks every job before the first one runs: every path absolute, the OptiScaler package of an install, update or +// repair copied into a new folder only administrators can write, the copy's digest the job's (package_snapshot.h; the +// install uses that copy), and the job's folders opened without following a link, where their paths say, and held +// (secure_fs.h). A batch with one job that fails these checks runs no job at all; +// - runs each job through its guard (secure_fs.h): every file operation through held handles, nothing outside the job's +// folders written; +// - writes no log or result file: its log lines and each job's result go back over the pipe, and the launcher writes the +// lines to its own log. +// The launcher takes the reply only from the worker process it started (the pipe client's process id and start time) and +// only from this run: a job without a result on the pipe did not report. +#pragma once + +#include + +#include "launcher.h" + +namespace wg { + +// ---- both sides --------------------------------------------------------------------------------------------------- +// A process as the launcher recognises the worker: its id and start time. +struct ProcessIdentity { + DWORD pid = 0; + unsigned long long started = 0; + bool operator==(const ProcessIdentity& o) const { return pid && pid == o.pid && started == o.started; } +}; +ProcessIdentity IdentityOf(HANDLE process); + +// The pipe name the launcher makes: \\.\pipe\WrongGPU-reply-<32 lower-case hex digits>; the worker opens nothing else. +bool IsReplyPipeName(const wstring& name); + +// ---- the launcher's side ------------------------------------------------------------------------------------------ +// What the worker sent over the pipe in this run. +struct WorkerReply { + bool connected = false; // the worker connected + bool complete = false; // its last record arrived + bool refused = false; // it refused the request before running any job (refusal says why) + OpResult refusal; + std::vector> results; // per job, in order: received, the result + std::vector log; // its log lines +}; + +// The reply pipe: made before the permission prompt (Create), read while the worker runs, finished after it exited. +class ReplyChannel { +public: + ReplyChannel(); + ~ReplyChannel(); + ReplyChannel(const ReplyChannel&) = delete; + ReplyChannel& operator=(const ReplyChannel&) = delete; + bool Create(wstring& why); + const wstring& Name() const; + // The reply of `worker` (nothing when it is the empty identity: the worker was not started) for `jobs` jobs. + WorkerReply Finish(const ProcessIdentity& worker, size_t jobs); +private: + struct Impl; + Impl* impl_; +}; + +// Starts the worker with these arguments and waits until it exits; false: it was not started (permission not given). +// `worker`: the process started; `exitCode`: its exit code. +using StartWorkerFn = std::function; +using LogFn = std::function; + +// The launcher's elevated step for these job texts (JobText), in order, in one worker run (one permission prompt). stop: +// none runs after the first failure (kOpNotRun). A result per job; a job the worker did not report on gets a failure that +// says so. The job and batch files are written to `jobsDir` and deleted afterwards; the worker's log lines go to `log`. +std::vector RunElevatedJobs(const std::vector& jobTexts, const wstring& jobsDir, bool stop, const StartWorkerFn& start, const LogFn& log); + +extern const wchar_t* const kElevationNotGranted; + +// ---- the worker's side -------------------------------------------------------------------------------------------- +// One checked job, as the worker runs it. +struct WorkerJob { + OpRequest r; + wstring localAppData, userSid, documents; + int perGameEntry = -1; +}; +// Runs one job's operation (the launcher: environment, registry hive, RunOp). The tests pass their own. +using WorkerRunFn = std::function; + +struct WorkerArgs { wstring batch, sha256, pipe; }; +struct WorkerRun { + OpResult last; // the last failure, or OK; the refusal when refused + int jobs = 0, ran = 0; // ran: the jobs run (not the ones stop=1 skipped) + bool refused = false; // no job was run +}; + +// "apply --batch= --sha256= --pipe=". ctx: its log lines go over the pipe while it runs, and its +// temporary files under the worker's private folder (made in privateParent; empty: the Windows folder's Temp). +WorkerRun RunWorker(const WorkerArgs& a, Context& ctx, const WorkerRunFn& run, const wstring& privateParent = L""); + +} // namespace wg diff --git a/clean/installer/src/wg_core/install.cpp b/clean/installer/src/wg_core/install.cpp index 618fdb73..a6d1ea98 100644 --- a/clean/installer/src/wg_core/install.cpp +++ b/clean/installer/src/wg_core/install.cpp @@ -50,7 +50,7 @@ void RemoveEarlierDirect(Context& ctx, const GameTarget& target, Ui& ui, std::ve RemoveTree(StateDir(old)); const wstring from = Join(old, L"wronggpu.ini"), to = Join(target.dir, L"wronggpu.ini"); if (IsFile(from)) { - if (!IsFile(to) && MoveFileExW(from.c_str(), to.c_str(), MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) ui.log(L"wronggpu.ini (your settings) moved to " + target.dir); + if (!IsFile(to) && MovePath(from, to, MOVEFILE_COPY_ALLOWED)) ui.log(L"wronggpu.ini (your settings) moved to " + target.dir); else { ForceDelete(from); ui.log(L"wronggpu.ini of the earlier installation removed from " + old); } } } @@ -130,7 +130,7 @@ CompareDll RecordCompareDll(Context& ctx, Ui& ui, const wstring& gameRoot) { } const CompareDll c = FindCompareDll(ctx, libraries); if (c.path.empty()) { - DeleteFileW(CompareRecordFile().c_str()); + DeletePath(CompareRecordFile()); ui.log(L"No AMD FSR 4 DLL was found in your other games."); return c; } @@ -279,8 +279,10 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod struct EarlierGone { const wstring& dir; Ui& ui; bool armed = false; ~EarlierGone() { - if (!armed || IsFile(RecordPath(dir))) return; - RemoveStateKeepingSettings(dir); + try { // (the elevated worker's guard can refuse a path: secure_fs.h; never thrown out of a destructor) + if (!armed || IsFile(RecordPath(dir))) return; + RemoveStateKeepingSettings(dir); + } catch (const SetupError&) { return; } ui.log(L"The earlier installation was removed and the game's original files are back; the new version was not installed (your settings were kept)."); } } earlierGone{dir, ui}; @@ -630,7 +632,7 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod const wstring src = Join(dir, sl->name); ui.step(++done, total, L"Keeping the game's " + wstring(sl->name) + L" as " + e.rel); if (Exists(tp)) ForceDelete(tp); - if (!MoveFileExW(src.c_str(), tp.c_str(), MOVEFILE_WRITE_THROUGH)) Fail(L"Cannot rename " + src + L": " + ErrText(GetLastError()) + L". Is the game running?"); + if (!MovePath(src, tp, 0)) Fail(L"Cannot rename " + src + L": " + ErrText(GetLastError()) + L". Is the game running?"); if (Sha256File(tp) != e.inst) Fail(L"Verification failed after renaming " + wstring(sl->name)); ui.log(L"renamed " + wstring(sl->name) + L" to " + e.rel); } @@ -687,7 +689,7 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod } catch (const SetupError& r) { ui.log(L"Rollback problem: " + r.msg); } throw; } - if (!ctx.logFile.empty() && IsFile(ctx.logFile)) CopyFileW(ctx.logFile.c_str(), Join(state, L"setup.log").c_str(), FALSE); + if (!ctx.logFile.empty() && IsFile(ctx.logFile)) CopyPath(ctx.logFile, Join(state, L"setup.log")); return warnings; } diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 694d39ec..6767f785 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -579,7 +579,7 @@ static void SavePrevious(Context& ctx, const wstring& dir, Record m, Ui& ui) { } WriteFileAtomic(Join(tmp, L"previous.txt"), list.data(), list.size()); RemoveTree(prev); - if (!MoveFileExW(tmp.c_str(), prev.c_str(), MOVEFILE_WRITE_THROUGH)) Fail(L"Cannot keep the previous version: " + ErrText(GetLastError())); + if (!MovePath(tmp, prev, 0)) Fail(L"Cannot keep the previous version: " + ErrText(GetLastError())); ui.log(L"kept WrongGPU " + m.version + L" for Roll back (" + std::to_wstring(n) + L" files in wronggpu-setup\\previous)"); } struct PrevFile { wstring sha, rel; }; @@ -655,7 +655,7 @@ static void Rollback(Context& ctx, const wstring& dir, Ui& ui, OpResult& res) { SaveRecord(RecordPath(dir), m); WriteOwnedFiles(dir, m); RemoveTree(prev); - if (!MoveFileExW(swap.c_str(), prev.c_str(), MOVEFILE_WRITE_THROUGH)) res.warnings.push_back(L"the newer version could not be kept for a later update: " + ErrText(GetLastError())); + if (!MovePath(swap, prev, 0)) res.warnings.push_back(L"the newer version could not be kept for a later update: " + ErrText(GetLastError())); res.message = L"Rolled back from " + newer + L" to " + version + L" (" + std::to_wstring(files.size()) + (files.size() == 1 ? L" file)" : L" files)"); } @@ -1160,12 +1160,18 @@ OpResult RunOp(Context& ctx, const OpRequest& r, Ui& ui) { } // ---- job file ------------------------------------------------------------------------------------------------------ -string JobText(const OpRequest& r, const wstring& localAppData, const wstring& logFile, const wstring& userSid, int perGameEntry, const wstring& documents) { - string t = "; WrongGPU launcher job (run by: WrongGPU.exe apply --job --result )\r\n"; +bool IsAbsolutePath(const wstring& p) { + if (p.size() > 2 && iswalpha(p[0]) && p[1] == L':' && (p[2] == L'\\' || p[2] == L'/')) return true; + // \\server\share\..., not the \\?\ and \\.\ device forms + return p.size() > 4 && p[0] == L'\\' && p[1] == L'\\' && p[2] != L'?' && p[2] != L'.' && p[2] != L'\\' && p.find(L'\\', 3) != wstring::npos; +} +string JobText(const OpRequest& r, const wstring& localAppData, const wstring& userSid, int perGameEntry, const wstring& documents) { + string t = "; WrongGPU launcher job (listed with its SHA-256 in the batch of: WrongGPU.exe apply --batch=)\r\n"; if (!userSid.empty()) t += "usersid=" + ToUtf8(userSid) + "\r\n"; if (perGameEntry >= 0) t += string("perentry=") + (perGameEntry ? "1" : "0") + "\r\n"; t += "op=" + ToUtf8(OpName(r.op)) + "\r\nexe=" + ToUtf8(r.exe) + "\r\ndir=" + ToUtf8(r.dir) + "\r\nopti=" + ToUtf8(r.optiPackage) + - "\r\nmodel=" + ToUtf8(r.modelDll) + "\r\nlocalappdata=" + ToUtf8(localAppData) + "\r\nlog=" + ToUtf8(logFile) + "\r\n"; + "\r\nmodel=" + ToUtf8(r.modelDll) + "\r\nlocalappdata=" + ToUtf8(localAppData) + "\r\n"; + if (!r.optiDigest.empty()) t += "optisha256=" + ToUtf8(r.optiDigest) + "\r\n"; if (!documents.empty()) t += "documents=" + ToUtf8(documents) + "\r\n"; t += string("movemods=") + (r.moveMods ? "1" : "0") + "\r\nremoveold=" + (r.removeOld ? "1" : "0") + "\r\nexperimental=" + (r.experimental ? "1" : "0") + "\r\nforce=" + (r.force ? "1" : "0") + "\r\nnoscan=" + (r.noScan ? "1" : "0") + "\r\n"; @@ -1179,7 +1185,7 @@ string JobText(const OpRequest& r, const wstring& localAppData, const wstring& l if (!r.rrConfigSet.empty()) t += "rrconfigset=" + r.rrConfigSet + "\r\n"; return t; } -bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring& logFile, wstring* why, wstring* userSid, int* perGameEntry, wstring* documents) { +bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring* why, wstring* userSid, int* perGameEntry, wstring* documents) { wstring docs; bool haveOp = false; r = OpRequest(); @@ -1194,7 +1200,7 @@ bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring& else if (k == "model") r.modelDll = v; else if (k == "localappdata") localAppData = v; else if (k == "documents") docs = v; - else if (k == "log") logFile = v; + else if (k == "optisha256") r.optiDigest = v; else if (k == "usersid") { if (userSid) *userSid = v; } else if (k == "perentry") { if (perGameEntry) *perGameEntry = Truthy(kv.second) ? 1 : 0; } else if (k == "movemods") r.moveMods = Truthy(kv.second); @@ -1214,9 +1220,10 @@ bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring& } } if (!haveOp) { if (why) *why = L"the job names no operation"; return false; } - // explicit absolute paths only: the worker never guesses from its own (possibly another account's) environment - for (const wstring* p : {&r.exe, &r.dir, &localAppData, &docs}) - if (!p->empty() && !(p->size() > 2 && (*p)[1] == L':' && ((*p)[2] == L'\\' || (*p)[2] == L'/')) && p->rfind(L"\\\\", 0) != 0) { + // explicit absolute paths only (a drive path or \\server\share): the worker never guesses from its own (possibly another + // account's) environment or current folder + for (const wstring* p : {&r.exe, &r.dir, &r.optiPackage, &r.modelDll, &localAppData, &docs}) + if (!p->empty() && !IsAbsolutePath(*p)) { if (why) *why = L"not an absolute path: " + *p; return false; } @@ -1225,21 +1232,28 @@ bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring& return true; } string BatchText(const std::vector>& jobs, bool stop) { - string t = "; WrongGPU launcher batch (run by: WrongGPU.exe apply --batch )\r\n"; + string t = "; WrongGPU launcher batch (run by: WrongGPU.exe apply --batch= --sha256=)\r\n"; if (stop) t += "stop=1\r\n"; - for (auto& j : jobs) t += "job=" + ToUtf8(j.first) + "\r\nresult=" + ToUtf8(j.second) + "\r\n"; + for (auto& j : jobs) t += "job=" + ToUtf8(j.first) + "\r\nsha256=" + ToUtf8(j.second) + "\r\n"; return t; } -bool ParseBatch(const string& text, std::vector>& jobs, bool& stop) { +bool ParseBatch(const string& text, std::vector>& jobs, bool& stop, wstring* why) { jobs.clear(); stop = false; wstring job; + auto fail = [&](const wstring& w) { if (why) *why = w; jobs.clear(); return false; }; for (auto& kv : KeyValues(text)) { if (kv.first == "stop") stop = Truthy(kv.second); - else if (kv.first == "job") job = FromUtf8(kv.second); - else if (kv.first == "result" && !job.empty()) { jobs.push_back({job, FromUtf8(kv.second)}); job.clear(); } - } - return !jobs.empty(); + else if (kv.first == "job") { if (!job.empty()) return fail(L"a job line without its sha256 line"); job = FromUtf8(kv.second); } + else if (kv.first == "sha256") { + if (job.empty() || kv.second.size() != 64) return fail(L"a sha256 line without a job line, or not 64 hex digits"); + jobs.push_back({job, FromUtf8(kv.second)}); + job.clear(); + } else if (kv.first == "result") return fail(L"result= is not accepted (the result paths are the worker's own)"); + } + if (!job.empty()) return fail(L"a job line without its sha256 line"); + if (jobs.empty()) return fail(L"no job"); + return true; } string ResultText(const OpResult& res) { string t = "code=" + std::to_string(res.code) + "\r\nmessage=" + ToUtf8(res.message) + "\r\n"; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index baaf8883..8764281b 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -172,6 +172,7 @@ struct OpRequest { wstring dir; // the install folder (uninstall, rollback, apply, adopt) wstring optiPackage; // install/update/repair: the player's OptiScaler download wstring modelDll; // a DLSS model file to try first + wstring optiDigest; // the elevated worker's job: optiPackage's digest as the launcher saw it (package_snapshot.h) bool moveMods = false, removeOld = false, experimental = false, force = false, noScan = true; bool hasProfile = false; // apply: this profile (else the game's profile.ini); install: the profile a new install starts with Profile profile; @@ -220,21 +221,23 @@ bool HasPrevious(const wstring& dir, wstring* version = nullptr); bool PreviousFits(const wstring& dir, const Record& m, wstring* version = nullptr); // ---- the elevated worker's job file ------------------------------------------------------------------------------- -// UTF-8 key=value lines: op, exe, dir, opti, model, flags, localappdata (the player's, so the model and the shared data -// are the player's even when an administrator account runs the worker), log, profile.; usersid (the player's -// account: its Apps & features entries, when another account runs the worker) and perentry (1: a new install gets its own -// entry, 0: the player's launcher is installed), each left out when empty / -1. -// documents: the player's Documents folder (rrconfig.h; the worker may run as another account, whose Documents it is not). -string JobText(const OpRequest& r, const wstring& localAppData, const wstring& logFile, const wstring& userSid = L"", int perGameEntry = -1, - const wstring& documents = L""); -bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring& logFile, wstring* why, wstring* userSid = nullptr, int* perGameEntry = nullptr, +// UTF-8 key=value lines: op, exe, dir, opti, optisha256 (the OptiScaler package's digest, package_snapshot.h), model, +// flags, localappdata (the player's, so the model and the shared data are the player's even when an administrator account +// runs the worker), profile.; usersid (the player's account: its Apps & features entries, when another account runs +// the worker) and perentry (1: a new install gets its own entry, 0: the player's launcher is installed), each left out when +// empty / -1. documents: the player's Documents folder (rrconfig.h; the worker may run as another account, whose Documents +// it is not). Every path in a job must be absolute. +string JobText(const OpRequest& r, const wstring& localAppData, const wstring& userSid = L"", int perGameEntry = -1, const wstring& documents = L""); +bool IsAbsolutePath(const wstring& p); // C:\... or \\server\share\... (not \\?\ or \\.\) +bool ParseJob(const string& text, OpRequest& r, wstring& localAppData, wstring* why, wstring* userSid = nullptr, int* perGameEntry = nullptr, wstring* documents = nullptr); string ResultText(const OpResult& res); bool ParseResult(const string& text, OpResult& res); -// Several jobs for one elevated worker ("apply --batch=", one permission prompt): job= / result= pairs in -// the order they run; stop=1: none runs after the first that fails (its result then has the code kOpNotRun). +// Several jobs for one elevated worker ("apply --batch= --sha256=", one permission prompt): job= / +// sha256= pairs in the order they run; stop=1: none runs after the first that fails (its result then +// has the code kOpNotRun). Results come back over the reply pipe (elevated_job.h); a result= line is refused. string BatchText(const std::vector>& jobs, bool stop); -bool ParseBatch(const string& text, std::vector>& jobs, bool& stop); +bool ParseBatch(const string& text, std::vector>& jobs, bool& stop, wstring* why = nullptr); // ---- the launcher's own install ------------------------------------------------------------------------------------ // Copies the exe to `dir` (default DefaultInstallDir()), adds the Start-menu shortcut (startMenu: a folder; empty: diff --git a/clean/installer/src/wg_core/leftovers.cpp b/clean/installer/src/wg_core/leftovers.cpp index 1f219d39..ca1bee16 100644 --- a/clean/installer/src/wg_core/leftovers.cpp +++ b/clean/installer/src/wg_core/leftovers.cpp @@ -161,14 +161,14 @@ std::vector CleanLeftovers(Context& ctx, const wstring& dir, const std: const wstring orig = Join(Parent(p), sl->original); wstring info; if (IsFile(orig) && ClassifySlot(*sl, orig, nullptr, info) == FFX_GAME) { - if (!MoveFileExW(orig.c_str(), p.c_str(), MOVEFILE_WRITE_THROUGH)) Fail(L"Cannot put the game's " + wstring(sl->name) + L" back: " + ErrText(GetLastError())); + if (!MovePath(orig, p, 0)) Fail(L"Cannot put the game's " + wstring(sl->name) + L" back: " + ErrText(GetLastError())); notes.push_back(L"the game's " + wstring(sl->name) + L" is back under its own name"); } } } for (const wchar_t* sub : {L"plugins", kAsiPluginOwnDir}) { const wstring d = Join(dir, sub); - if (IsDir(d) && ListFiles(d, L"*").empty() && ListDirs(d).empty() && RemoveDirectoryW(d.c_str())) notes.push_back(L"removed the empty folder " + wstring(sub)); + if (IsDir(d) && ListFiles(d, L"*").empty() && ListDirs(d).empty() && RemoveDirPath(d)) notes.push_back(L"removed the empty folder " + wstring(sub)); } LogLine(ctx, L"leftovers cleaned up in " + dir + L": " + std::to_wstring(files.size()) + L" file(s)"); return notes; diff --git a/clean/installer/src/wg_core/model.cpp b/clean/installer/src/wg_core/model.cpp index 708df5c4..fb185f30 100644 --- a/clean/installer/src/wg_core/model.cpp +++ b/clean/installer/src/wg_core/model.cpp @@ -4,6 +4,7 @@ #include "model.h" #include #include "optiscaler.h" +#include "secure_fs.h" namespace wg { @@ -19,7 +20,8 @@ bool ExistingModelValid(Context& ctx, wstring* why, wgc::ModelFileInfo* info) { if (info) *info = wgc::ModelFileInfo(); if (!LoadEmbeddedMap(ctx) || !IsFile(ModelFile(ctx))) { if (why) *why = L"no converted model on this PC"; return false; } string w; - const bool ok = wgc::verify_model_file(*ctx.map.map, std::filesystem::path(ModelFile(ctx)), w, info); + const ConverterFile in(ModelFile(ctx), ctx.workRoot); // (the elevated worker: a checked private copy, secure_fs.h) + const bool ok = wgc::verify_model_file(*ctx.map.map, std::filesystem::path(in.path()), w, info); if (why) *why = FromUtf8(w); return ok; } @@ -138,7 +140,8 @@ ModelState FindModel(Context& ctx, const GameTarget* t, const wstring& userDll, ModelCandidate chosenCand, withoutCand; for (auto& cand : cands) { auto conv = std::make_shared(); - const wgc::Result r = wgc::convert_file(*ctx.map.map, std::filesystem::path(cand.path), opt, *conv, + const ConverterFile in(cand.path, ctx.workRoot); + const wgc::Result r = wgc::convert_file(*ctx.map.map, std::filesystem::path(in.path()), opt, *conv, [&ctx](const string& s) { LogLine(ctx, L"converter: " + FromUtf8(s)); }); if (r.code == wgc::kOk) { if (wgc::has_every_group(*ctx.map.map, *conv)) { chosen = conv; chosenCand = cand; break; } @@ -247,32 +250,36 @@ bool ReplaceModel(Context& ctx, const ModelState& m, wstring& problem) { const bool needGroups = m.trust == ModelState::TRUSTED; const wstring side = Join(ModelDir(ctx), L"model-new"), sideFile = Join(side, FromUtf8(wgc::kModelFileName)); const wstring previous = ModelFile(ctx) + L".previous"; - auto cleanup = [&] { if (IsDir(side)) RemoveTree(side); DeleteFileW(previous.c_str()); }; + auto cleanup = [&] { if (IsDir(side)) RemoveTree(side); DeletePath(previous); }; cleanup(); // what an interrupted earlier run left behind - const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, std::filesystem::path(side), false, + // the elevated worker: written and checked in its private folder, then copied beside the file in use (secure_fs.h) + ConverterDir out(side, ctx.workRoot); + const wstring checkFile = Join(out.path(), FromUtf8(wgc::kModelFileName)); + const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, std::filesystem::path(out.path()), false, [&ctx](const string& s) { LogLine(ctx, L"converter: " + FromUtf8(s)); }); if (r.code != wgc::kOk) { problem = L"it could not be saved next to the model data in use"; cleanup(); return false; } #ifdef WRONGGPU_TESTING if (!EnvVar(L"WRONGGPU_TEST_DAMAGE_NEW_MODEL").empty()) { // tests: the new file is damaged before its check string bytes; - if (ReadAll(sideFile, bytes) && bytes.size() > 200) { bytes[200] ^= 1; WriteFileAtomic(sideFile, bytes.data(), bytes.size()); } + if (ReadAll(checkFile, bytes) && bytes.size() > 200) { bytes[200] ^= 1; WriteFileAtomic(checkFile, bytes.data(), bytes.size()); } } #endif string w; wgc::ModelFileInfo info; - if (!wgc::verify_model_file(*ctx.map.map, std::filesystem::path(sideFile), w, &info) || (needGroups && !info.absent_groups.empty()) || !info.same_map) { + if (!wgc::verify_model_file(*ctx.map.map, std::filesystem::path(checkFile), w, &info) || (needGroups && !info.absent_groups.empty()) || !info.same_map) { problem = L"the new file failed its check" + (w.empty() ? wstring() : L" (" + FromUtf8(w) + L")"); cleanup(); return false; } + out.Publish(); LogLine(ctx, L"model: the new file " + sideFile + L" passed its check"); - if (!CopyFileW(ModelFile(ctx).c_str(), previous.c_str(), FALSE)) { problem = L"the model data in use could not be copied first: " + ErrText(GetLastError()); cleanup(); return false; } - if (!MoveFileExW(sideFile.c_str(), ModelFile(ctx).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + if (!CopyPath(ModelFile(ctx), previous)) { problem = L"the model data in use could not be copied first: " + ErrText(GetLastError()); cleanup(); return false; } + if (!MovePath(sideFile, ModelFile(ctx), MOVEFILE_REPLACE_EXISTING)) { problem = L"the model data in use could not be replaced: " + ErrText(GetLastError()); cleanup(); return false; } wstring why; if (!ExistingModelValid(ctx, &why, &info) || (needGroups && !info.absent_groups.empty())) { // not expected: the same bytes passed a moment ago - const bool back = MoveFileExW(previous.c_str(), ModelFile(ctx).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE; + const bool back = MovePath(previous, ModelFile(ctx), MOVEFILE_REPLACE_EXISTING); problem = L"the new file failed its check after it was moved into place (" + why + L")" + (back ? L"; the earlier file was put back" : L""); cleanup(); return false; } @@ -308,9 +315,11 @@ ModelResult WriteModel(Context& ctx, const ModelState& m, Ui& ui) { return res; } } else { - const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, std::filesystem::path(ModelDir(ctx)), false, + ConverterDir out(ModelDir(ctx), ctx.workRoot); // (the elevated worker: its private folder, then copied: secure_fs.h) + const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, std::filesystem::path(out.path()), false, [&ctx](const string& s) { LogLine(ctx, L"converter: " + FromUtf8(s)); }); if (r.code != wgc::kOk) Fail(FromUtf8(r.message)); + out.Publish(); wstring why; if (!ExistingModelValid(ctx, &why)) Fail(L"The saved model data failed its check (" + why + L")."); } diff --git a/clean/installer/src/wg_core/optiscaler.cpp b/clean/installer/src/wg_core/optiscaler.cpp index 2b3b4635..0aed9fb7 100644 --- a/clean/installer/src/wg_core/optiscaler.cpp +++ b/clean/installer/src/wg_core/optiscaler.cpp @@ -9,10 +9,15 @@ namespace wg { +// The folder temporary files go under: the Context's work folder (the elevated worker's), else the temp folder. +static wstring TempRoot(Context& ctx) { + if (!ctx.workRoot.empty()) return ctx.workRoot; + wchar_t tmp[MAX_PATH] = {}; GetTempPathW(MAX_PATH, tmp); + return tmp; +} wstring OptiTempDir(Context& ctx) { if (!ctx.opti.tempDir.empty()) return ctx.opti.tempDir; - wchar_t tmp[MAX_PATH] = {}; GetTempPathW(MAX_PATH, tmp); - ctx.opti.tempDir = Join(tmp, L"wronggpu-optiscaler-" + std::to_wstring(GetCurrentProcessId())); + ctx.opti.tempDir = Join(TempRoot(ctx), L"wronggpu-optiscaler-" + std::to_wstring(GetCurrentProcessId())); EnsureDir(ctx.opti.tempDir); return ctx.opti.tempDir; } @@ -39,8 +44,7 @@ OptiPackage PrepareOptiScaler(Context& ctx, const wstring& chosen) { if (IsDir(p.source)) root = p.source; else if (IsFile(p.source) && IEq(BaseName(p.source), L"OptiScaler.dll")) root = Parent(p.source); else if (IsFile(p.source) && (EndsWithI(p.source, L".7z") || EndsWithI(p.source, L".zip"))) { - wchar_t tmp[MAX_PATH] = {}; GetTempPathW(MAX_PATH, tmp); - p.tempDir = Join(tmp, L"wronggpu-optiscaler-" + std::to_wstring(GetCurrentProcessId())); + p.tempDir = Join(TempRoot(ctx), L"wronggpu-optiscaler-" + std::to_wstring(GetCurrentProcessId())); RemoveTree(p.tempDir); EnsureDir(Join(p.tempDir, L"package")); wchar_t sys[MAX_PATH] = {}; GetSystemDirectoryW(sys, MAX_PATH); const wstring tar = Join(sys, L"tar.exe"); diff --git a/clean/installer/src/wg_core/package_snapshot.cpp b/clean/installer/src/wg_core/package_snapshot.cpp new file mode 100644 index 00000000..d4acbf28 --- /dev/null +++ b/clean/installer/src/wg_core/package_snapshot.cpp @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: MIT +// The OptiScaler package's digest and the elevated worker's copy of it (package_snapshot.h). Written for this project. +#include "package_snapshot.h" + +#include +#include + +#include +#include + +#include "checks.h" // IsElevated +#include "launcher.h" // CurrentUserSid +#include "secure_fs.h" +#include "sha256.h" + +#pragma comment(lib, "bcrypt.lib") + +namespace wg { + +namespace { + +const size_t kMaxFiles = 20000; +const unsigned long long kMaxBytes = 1ull << 30; // 1 GiB: far more than an OptiScaler release + +struct Source { + bool archive = false; + wstring root; // the folder (folder kinds), or the archive's folder + wstring file; // the archive (archive kind) +}; + +bool SourceOf(const wstring& chosen, Source& s, wstring& why) { + const wstring full = FullPath(chosen); + if (IsDir(full)) { s.root = full; return true; } + if (IsFile(full) && IEq(BaseName(full), L"OptiScaler.dll")) { s.root = Parent(full); return true; } + if (IsFile(full) && (EndsWithI(full, L".7z") || EndsWithI(full, L".zip"))) { s.archive = true; s.file = full; s.root = Parent(full); return true; } + why = L"the OptiScaler package " + chosen + L" is not an archive (.7z or .zip), a folder or OptiScaler.dll"; + return false; +} + +// The files of a folder and its subfolders, relative to it (links left out: util.h ListEntries, the same on the launcher's +// side and through the elevated worker's guard), sorted. +bool ListPackage(const wstring& root, std::vector& files, wstring& why) { + std::vector stack{L""}; + while (!stack.empty()) { + const wstring rel = stack.back(); + stack.pop_back(); + std::vector entries; + const wstring dir = rel.empty() ? root : Join(root, rel); + if (!ListEntries(dir, entries) && GetLastError() != ERROR_FILE_NOT_FOUND) { + why = L"cannot list " + dir + L" (" + ErrText(GetLastError()) + L")"; + return false; + } + for (auto& en : entries) { + if (en.attrs & FILE_ATTRIBUTE_REPARSE_POINT) continue; + const wstring r = rel.empty() ? en.name : Join(rel, en.name); + if (en.attrs & FILE_ATTRIBUTE_DIRECTORY) stack.push_back(r); + else files.push_back(r); + if (files.size() > kMaxFiles) { why = L"the OptiScaler package has more files than a package can have"; return false; } + } + } + std::sort(files.begin(), files.end(), [](const wstring& a, const wstring& b) { return Lower(a) < Lower(b); }); + return true; +} + +struct HandleCloser { void operator()(HANDLE h) const { if (h && h != INVALID_HANDLE_VALUE) CloseHandle(h); } }; +using Held = std::unique_ptr; + +// One file read once (no other writer while it is read): its SHA-256, and its bytes written to `copyTo` when given. +bool HashFile(const wstring& path, const wstring& copyTo, unsigned long long& total, wstring& sha, wstring& why) { + Held in(OpenForRead(path, FILE_SHARE_READ)); + if (in.get() == INVALID_HANDLE_VALUE) { in.release(); why = L"cannot read " + path + L" (" + ErrText(GetLastError()) + L")"; return false; } + Held out; + if (!copyTo.empty()) { + out.reset(CreateNewFile(copyTo)); + if (out.get() == INVALID_HANDLE_VALUE) { out.release(); why = L"cannot write " + copyTo + L" (" + ErrText(GetLastError()) + L")"; return false; } + } + wgc::Sha256 h; + std::vector buf(1 << 20); + for (;;) { + DWORD got = 0; + if (!ReadFile(in.get(), buf.data(), (DWORD)buf.size(), &got, nullptr)) { why = L"cannot read " + path + L" (" + ErrText(GetLastError()) + L")"; return false; } + if (!got) break; + total += got; + if (total > kMaxBytes) { why = L"the OptiScaler package is larger than a package can be"; return false; } + h.update(buf.data(), got); + DWORD wrote = 0; + if (out && (!WriteFile(out.get(), buf.data(), got, &wrote, nullptr) || wrote != got)) { why = L"cannot write " + copyTo; return false; } + } + sha = HexW(h.finish()); + return true; +} + +// The manifest of the package (and its copy in `copyDir` when given) and the manifest's SHA-256. +bool Digest(const Source& s, const wstring& copyDir, wstring& digest, wstring& copy, wstring& why) { + std::vector files; + wstring base = s.root; + if (s.archive) files.push_back(BaseName(s.file)); + else if (!ListPackage(s.root, files, why)) return false; + if (files.empty()) { why = L"the OptiScaler package " + s.root + L" has no files"; return false; } + string manifest = string("; WrongGPU OptiScaler package\r\nkind=") + (s.archive ? "archive" : "folder") + "\r\n"; + unsigned long long total = 0; + const wstring into = copyDir.empty() ? L"" : (s.archive ? copyDir : Join(copyDir, L"package")); + if (!into.empty() && !s.archive) EnsureDir(into); + for (auto& rel : files) { + wstring target; + if (!into.empty()) { + target = Join(into, rel); + if (Parent(target) != into) EnsureDir(Parent(target)); + } + wstring sha; + if (!HashFile(Join(base, rel), target, total, sha, why)) return false; + manifest += "file=" + ToUtf8(rel) + "\r\nsha256=" + ToUtf8(sha) + "\r\n"; + } + digest = Sha256Bytes(manifest.data(), manifest.size()); + copy = into.empty() ? L"" : (s.archive ? Join(into, files[0]) : into); + return true; +} + +} // namespace + +wstring RandomHex() { + unsigned char b[16] = {}; + if (BCryptGenRandom(nullptr, b, sizeof(b), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) Fail(L"no random numbers from Windows", EXIT_FAILED); + static const wchar_t* hex = L"0123456789abcdef"; + wstring s; + for (unsigned char c : b) { s.push_back(hex[c >> 4]); s.push_back(hex[c & 15]); } + return s; +} + +bool PackageDigest(const wstring& chosen, wstring& digest, wstring& why) { + Source s; + wstring copy; + return SourceOf(chosen, s, why) && Digest(s, L"", digest, copy, why); +} + +bool SnapshotPackage(const wstring& chosen, const wstring& expected, const wstring& intoDir, wstring& copy, wstring& why) { + Source s; + wstring digest; + if (expected.size() != 64) { why = L"the job has no digest for the OptiScaler package " + chosen; return false; } + try { + if (!SourceOf(chosen, s, why) || !Digest(s, intoDir, digest, copy, why)) return false; + } catch (const SetupError& e) { why = e.msg; return false; } + if (!IEq(digest, expected)) { why = L"the OptiScaler package " + chosen + L" is not the one chosen for this request (its files changed)"; return false; } + return true; +} + +bool MakePrivateFolder(const wstring& parentIn, wstring& path, wstring& why) { + wstring parent = parentIn; + if (parent.empty()) { + wchar_t win[MAX_PATH] = {}; + const UINT n = GetWindowsDirectoryW(win, MAX_PATH); + if (!n || n >= MAX_PATH) { why = L"cannot find the Windows folder"; return false; } + parent = Join(win, L"Temp"); + } + // administrators and SYSTEM only, nothing inherited from the parent; this account too when not elevated (tests) + wstring sddl = L"D:P(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)"; + if (!IsElevated()) { + const wstring me = CurrentUserSid(); + if (me.empty()) { why = L"cannot read this account's SID"; return false; } + sddl += L"(A;OICI;FA;;;" + me + L")"; + } + PSECURITY_DESCRIPTOR sd = nullptr; + if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &sd, nullptr)) { + why = L"cannot make the folder's permissions (" + ErrText(GetLastError()) + L")"; + return false; + } + // made relative to the parent's held handle, the parent opened without following a link (secure_fs.h) + bool ok = false; + DWORD e = 0; + FsGuard guard; + wstring refused; + if (!guard.AddRoot(parent, refused)) { + LocalFree(sd); + why = L"cannot make a private folder in " + parent + L": " + refused; + return false; + } + for (int i = 0; i < 8 && !ok; ++i) { + path = Join(NormalPath(parent), L"WrongGPU-elevated-" + RandomHex()); + try { ok = guard.CreateNewDir(path, sd, e); } + catch (const SetupError& x) { refused = x.msg; break; } + if (!ok && e != ERROR_ALREADY_EXISTS && e != ERROR_FILE_EXISTS) break; + } + if (!ok) why = L"cannot make a private folder in " + parent + L" (" + (refused.empty() ? ErrText(e) : refused) + L")"; + LocalFree(sd); + return ok; +} + +} // namespace wg diff --git a/clean/installer/src/wg_core/package_snapshot.h b/clean/installer/src/wg_core/package_snapshot.h new file mode 100644 index 00000000..8ac42957 --- /dev/null +++ b/clean/installer/src/wg_core/package_snapshot.h @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT +// The player's OptiScaler package as the elevated worker installs it: bound to the launcher's request by a digest and +// installed from the worker's own copy. +// +// The launcher computes the package's digest before the permission prompt (PackageDigest) and puts it in the job +// (optisha256=). The worker copies the package into a new folder only administrators can write (MakePrivateFolder, +// SnapshotPackage), computes the digest of that copy and installs from the copy only when it is the job's digest. +// +// The digest is the SHA-256 of a manifest listing every file with its SHA-256: for an archive (.7z / .zip) the archive +// file itself; for a folder, or the OptiScaler.dll in a folder, every file in that folder and its subfolders (folders and +// files that are links are left out on both sides). +#pragma once + +#include "util.h" + +namespace wg { + +// The digest of the package `chosen` (an archive, a folder, or OptiScaler.dll in a folder). False with *why when it cannot +// be read or is larger than a package can be. +bool PackageDigest(const wstring& chosen, wstring& digest, wstring& why); + +// Copies the package `chosen` into `intoDir` (an existing private folder), reading each file once; true when the digest of +// the copy is `expected`. `copy`: the package to install from (the archive's copy, or the folder's copy). +bool SnapshotPackage(const wstring& chosen, const wstring& expected, const wstring& intoDir, wstring& copy, wstring& why); + +// A new folder with a random name in `parent` (empty: the Windows folder's Temp) that only administrators and SYSTEM can +// open (and this account, when this process is not elevated: the tests' stand-in for the elevated worker). It must not exist +// before: a name that is taken is never reused. +bool MakePrivateFolder(const wstring& parent, wstring& path, wstring& why); + +// 16 random bytes as 32 hex digits (the system's random number generator). +wstring RandomHex(); + +} // namespace wg diff --git a/clean/installer/src/wg_core/record.cpp b/clean/installer/src/wg_core/record.cpp index c50d00d1..2c02cde1 100644 --- a/clean/installer/src/wg_core/record.cpp +++ b/clean/installer/src/wg_core/record.cpp @@ -180,7 +180,7 @@ wstring Target(const wstring& dir, const wstring& rel) { if (part == L"..") Fail(L"Invalid path in the install record: " + rel); if (!part.empty()) { cur = Join(cur, part); - DWORD a = GetFileAttributesW(cur.c_str()); + DWORD a = GetAttrs(cur); if (a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_REPARSE_POINT)) Fail(L"Refusing to follow a link inside the game folder: " + cur); } i = j + 1; @@ -248,7 +248,7 @@ bool DriveUnreachable(const wstring& dir) { if (a == wstring::npos) return false; root = (b == wstring::npos ? full : full.substr(0, b)) + L"\\"; } else return false; - return GetFileAttributesW(root.c_str()) == INVALID_FILE_ATTRIBUTES; + return GetAttrs(root) == INVALID_FILE_ATTRIBUTES; } // A game on a drive that is not connected now (an unplugged USB drive, an offline share) still has WrongGPU and still uses // the shared data once the drive is back: it counts, though its record cannot be read @@ -329,11 +329,11 @@ size_t RemoveRuntimeFiles(const wstring& dir, const wstring& exeDir, const Recor size_t removed = 0; for (auto& d : dirs) { for (auto& f : ListFiles(d, L"wronggpu-*")) - if (!recorded.count(Lower(FullPath(f))) && DeleteFileW(f.c_str())) ++removed; - if (settings && DeleteFileW(Join(d, L"wronggpu.ini").c_str())) ++removed; + if (!recorded.count(Lower(FullPath(f))) && DeletePath(f)) ++removed; + if (settings && DeletePath(Join(d, L"wronggpu.ini"))) ++removed; if (opti) // logs written by the OptiScaler this installer set up for (auto pat : {L"OptiScaler.log", L"OptiScaler.previous*.log", L"fakenvapi.log"}) - for (auto& f : ListFiles(d, pat)) if (!recorded.count(Lower(FullPath(f))) && DeleteFileW(f.c_str())) ++removed; + for (auto& f : ListFiles(d, pat)) if (!recorded.count(Lower(FullPath(f))) && DeletePath(f)) ++removed; } return removed; } @@ -353,6 +353,8 @@ size_t RemoveRuntimeFiles(const wstring& dir, const wstring& exeDir, const Recor // %LOCALAPPDATA%\WrongGPU, removed with everything in it (empty: other games still use it). static std::atomic g_cleanupMove{nullptr}; // test seam (record.h SetCleanupMoveForTest) void SetCleanupMoveForTest(CleanupMoveFn fn) { g_cleanupMove = fn; } +// MoveFileExW's shape for the cleanup's move (util.h MovePath: through the elevated worker's guard while one is active). +static BOOL WINAPI MoveThroughGuard(LPCWSTR from, LPCWSTR to, DWORD flags) { return MovePath(from, to, flags) ? TRUE : FALSE; } // Returns the line "kept ignore-files.txt ..." when the shared folder's ignore list was put back (convert_ignore.h), else "". wstring StartCleanup(Context& ctx, const wstring& state, const wstring& self, const wstring& appData) { @@ -368,7 +370,7 @@ wstring StartCleanup(Context& ctx, const wstring& state, const wstring& self, co for (int k = 0; k < 64; ++k) { retired = appData + L".cleanup-" + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(GetTickCount64()) + L"-" + std::to_wstring(sequence++); - if (GetFileAttributesW(retired.c_str()) == INVALID_FILE_ATTRIBUTES) break; + if (GetAttrs(retired) == INVALID_FILE_ATTRIBUTES) break; } // Nothing of WrongGPU's holds a file in the folder here (every write closes its handle, the log opens and closes // per line). Another program can, briefly (a scanner reading a file just written): a sharing violation (32) or an @@ -377,7 +379,7 @@ wstring StartCleanup(Context& ctx, const wstring& state, const wstring& self, co bool moved = false; DWORD err = 0; const CleanupMoveFn seam = g_cleanupMove.load(); - const CleanupMoveFn move = seam ? seam : &MoveFileExW; + const CleanupMoveFn move = seam ? seam : &MoveThroughGuard; for (int t = 0; t < kCleanupMoveTries; ++t) { if (move(appData.c_str(), retired.c_str(), MOVEFILE_WRITE_THROUGH)) { moved = true; break; } err = GetLastError(); @@ -496,15 +498,15 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa if (skip.count(k)) { ui.log(L"kept " + e.rel); continue; } wstring t = Target(dir, e.rel), b = BackupPath(dir, e.rel); if (e.action == L"dir") { - if (IsDir(t) && RemoveDirectoryW(t.c_str())) ui.log(L"removed folder " + e.rel); + if (IsDir(t) && RemoveDirPath(t)) ui.log(L"removed folder " + e.rel); } else if (e.action == L"copy" || e.action == L"rename") { // WrongGPU's DLL is still under the game's name (no entry or no backup for it): the renamed file is the // game's only copy. It goes back under its name instead of being removed. const FfxSlot* sl = e.action == L"rename" ? slotOf(e) : nullptr; wstring info; if (sl && Exists(t) && (e.inst.empty() || Sha256File(t) == e.inst) && ClassifySlot(*sl, Join(dir, sl->name), nullptr, info) == FFX_OURS) { - SetFileAttributesW(Join(dir, sl->name).c_str(), FILE_ATTRIBUTE_NORMAL); - if (!MoveFileExW(t.c_str(), Join(dir, sl->name).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) + SetAttrs(Join(dir, sl->name), FILE_ATTRIBUTE_NORMAL); + if (!MovePath(t, Join(dir, sl->name), MOVEFILE_REPLACE_EXISTING)) Fail(L"Cannot put " + wstring(sl->name) + L" back: " + ErrText(GetLastError())); ui.log(L"restored " + wstring(sl->name) + L" from " + e.rel); } @@ -545,7 +547,7 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa if (size_t n = RemoveRuntimeFiles(dir, m.exe.empty() ? L"" : Parent(m.exe), m, !keepState)) ui.log(L"removed " + std::to_wstring(n) + L" settings, log and report file(s) written by WrongGPU"); for (size_t k = m.e.size(); k-- > 0;) // a folder the install made that held only those files - if (m.e[k].action == L"dir" && !skip.count(k) && IsDir(Target(dir, m.e[k].rel)) && RemoveDirectoryW(Target(dir, m.e[k].rel).c_str())) + if (m.e[k].action == L"dir" && !skip.count(k) && IsDir(Target(dir, m.e[k].rel)) && RemoveDirPath(Target(dir, m.e[k].rel))) ui.log(L"removed folder " + m.e[k].rel); } // the game's Engine.ini outside the game folder (rrconfig.h, rr_config_fix=on): its line taken out again @@ -581,7 +583,7 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa if (!kept.empty()) { ui.log(kept); warnings.push_back(kept); } }; if (keepBackup) { warnings.push_back(L"The backup folder was kept: " + Join(state, L"backup")); if (!appData.empty()) cleanup(L"", L""); return warnings; } - if (keepState) { RemoveTree(Join(state, L"backup")); DeleteFileW(RecordPath(dir).c_str()); return warnings; } + if (keepState) { RemoveTree(Join(state, L"backup")); DeletePath(RecordPath(dir)); return warnings; } wstring self = SelfPath(); if (IEq(Parent(self), state)) { RemoveTree(state, self); @@ -605,9 +607,9 @@ bool StateHasSettings(const wstring& dir) { void RemoveStateKeepingSettings(const wstring& dir) { const wstring state = StateDir(dir); for (auto& f : ListFiles(state, L"*")) // never throws (a destructor calls it) - if (!SettingsName(BaseName(f), false)) { SetFileAttributesW(f.c_str(), FILE_ATTRIBUTE_NORMAL); DeleteFileW(f.c_str()); } + if (!SettingsName(BaseName(f), false)) { SetAttrs(f, FILE_ATTRIBUTE_NORMAL); DeletePath(f); } for (auto& d : ListDirs(state)) if (!SettingsName(BaseName(d), true)) RemoveTree(d); - RemoveDirectoryW(state.c_str()); // only when empty + RemoveDirPath(state); // only when empty } // Byte-exact removal of a WrongGPU 0.1.x/0.2.x ("DLSS 4.5 AMD") install from its own record and backup: the same @@ -637,13 +639,13 @@ std::vector LegacyRestore(Context& ctx, const wstring& dir, Ui& ui) { else if (Exists(t)) { ForceDelete(t); ui.log(L"older install: removed " + e.rel); } } else if (!Exists(t)) { CopyChecked(b, t); ui.log(L"older install: restored " + e.rel); } } - for (const wchar_t* d : {L"dlss45-model\\gpu-build", L"dlss45-model\\exposure-build", L"dlss45-model"}) RemoveDirectoryW(Join(dir, d).c_str()); + for (const wchar_t* d : {L"dlss45-model\\gpu-build", L"dlss45-model\\exposure-build", L"dlss45-model"}) RemoveDirPath(Join(dir, d)); std::set recorded; for (auto& e : m.e) recorded.insert(Lower(FullPath(Target(dir, e.rel)))); for (const wstring& d : {dir, GameRoot(dir)}) for (auto pat : {L"dlss45-*.log", L"dlss45-*.log.old", L"dlss45-report.txt", L"dlss45-report.json", L"dlss45-dred.txt", L"dlss45-crash-*.txt", L"dlss45-crash-*.dmp", L"dlss45-capture-*.bin", L"dlss45-capture-*.txt", L"dlss45-capture-*.jpg"}) - for (auto& f : ListFiles(d, pat)) if (!recorded.count(Lower(FullPath(f)))) DeleteFileW(f.c_str()); + for (auto& f : ListFiles(d, pat)) if (!recorded.count(Lower(FullPath(f)))) DeletePath(f); wstring key = m.regkey.empty() ? RegKeyFor(dir, kLegacyKeyPrefix) : m.regkey; RegDeleteKeyW(UninstallHive(), (UninstallRoot() + key).c_str()); wstring legacy = UninstallRoot() + kLegacyKey; diff --git a/clean/installer/src/wg_core/rr.cpp b/clean/installer/src/wg_core/rr.cpp index a7d4d550..bb345e69 100644 --- a/clean/installer/src/wg_core/rr.cpp +++ b/clean/installer/src/wg_core/rr.cpp @@ -11,6 +11,7 @@ #include "optiscaler.h" #include "payload.h" #include "pe.h" +#include "secure_fs.h" #include "settings.h" namespace wg { @@ -67,15 +68,13 @@ RrUse DetectRrUncached(const wstring& exe) { bool frameGen = false; // rc6: the game interface's frame-generation plugin seen (kIfaceFrameGen) while (!stack.empty() && visited < 40000) { auto [dir, depth] = stack.back(); stack.pop_back(); - WIN32_FIND_DATAW fd; - HANDLE h = FindFirstFileExW(Join(dir, L"*").c_str(), FindExInfoBasic, &fd, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH); - if (h == INVALID_HANDLE_VALUE) continue; - do { + std::vector entries; + try { if (!ListEntries(dir, entries)) continue; } catch (const SetupError&) { continue; } // (a folder the worker's guard refuses) + for (auto& en : entries) { ++visited; - const wstring n = fd.cFileName; - if (n == L"." || n == L"..") continue; - if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - if (depth < 9 && !(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && !IEq(n, kStateDirName) && !IEq(n, kLegacyStateDir)) + const wstring& n = en.name; + if (en.attrs & FILE_ATTRIBUTE_DIRECTORY) { + if (depth < 9 && !(en.attrs & FILE_ATTRIBUTE_REPARSE_POINT) && !IEq(n, kStateDirName) && !IEq(n, kLegacyStateDir)) stack.push_back({Join(dir, n), depth + 1}); } else if (IEq(n, kIfaceFrameGen)) { frameGen = true; @@ -85,13 +84,11 @@ RrUse DetectRrUncached(const wstring& exe) { if (IEq(n, kRrIfacePlugin)) { r.uses = true; r.why = rel; - FindClose(h); return known(r); } if (library.empty()) library = rel; } - } while (FindNextFileW(h, &fd)); - FindClose(h); + } } if (frameGen && IEq(BaseName(exe), L"HogwartsLegacy.exe")) { // rc6: the updated Hogwarts Legacy (kIfaceFrameGen) RrUse n; @@ -233,14 +230,15 @@ wstring RrDataFile() { return Join(RrDataDir(), FromUtf8(wgc::kModelFileName)); void RecoverRrData(Context& ctx) { const wstring old = RrDataDir() + L".old"; if (IsDir(RrDataDir()) || !IsDir(old)) return; - if (MoveFileExW(old.c_str(), RrDataDir().c_str(), MOVEFILE_WRITE_THROUGH)) LogLine(ctx, L"RR data: put back from " + old + L" (an earlier swap did not finish)"); + if (MovePath(old, RrDataDir(), 0)) LogLine(ctx, L"RR data: put back from " + old + L" (an earlier swap did not finish)"); } bool RrDataValid(Context& ctx, wstring* why) { if (!LoadFMap(ctx)) { if (why) *why = ctx.fMapError; return false; } if (!IsFile(RrDataFile())) { if (why) *why = L"no converted Ray Reconstruction data on this PC"; return false; } string w; - const bool ok = wgc::verify_model_file(*ctx.fMap.map, std::filesystem::path(RrDataFile()), w); + const ConverterFile in(RrDataFile(), ctx.workRoot); // (the elevated worker: a checked private copy, secure_fs.h) + const bool ok = wgc::verify_model_file(*ctx.fMap.map, std::filesystem::path(in.path()), w); if (why) *why = FromUtf8(w); return ok; } @@ -352,7 +350,8 @@ RrDataState FindRrData(Context& ctx, const GameTarget* t, const wstring& userDll wgc::SearchOptions opt; for (auto& c : cands) { auto conv = std::make_shared(); - const wgc::Result r = wgc::convert_file(*ctx.fMap.map, std::filesystem::path(c.first), opt, *conv, + const ConverterFile in(c.first, ctx.workRoot); + const wgc::Result r = wgc::convert_file(*ctx.fMap.map, std::filesystem::path(in.path()), opt, *conv, [&ctx](const string& s) { LogLine(ctx, L"converter (RR): " + FromUtf8(s)); }); if (r.code == wgc::kOk) { m.ok = true; m.dll = c.first; m.origin = c.second; m.version = FromUtf8(conv->version); m.converted = conv; @@ -387,11 +386,12 @@ bool WriteRrData(Context& ctx, const RrDataState& m, wstring* why) { const wstring side = RrDataDir() + L".new"; if (IsDir(side)) RemoveTree(side); EnsureDir(ModelBaseDir()); - const wgc::Result r = wgc::write_converted(*ctx.fMap.map, *m.converted, std::filesystem::path(side), false, + ConverterDir out(side, ctx.workRoot); // (the elevated worker: written and checked in its private folder: secure_fs.h) + const wgc::Result r = wgc::write_converted(*ctx.fMap.map, *m.converted, std::filesystem::path(out.path()), false, [&ctx](const string& s) { LogLine(ctx, L"converter (RR): " + FromUtf8(s)); }); - const wstring sideFile = Join(side, FromUtf8(wgc::kModelFileName)); + const wstring checkFile = Join(out.path(), FromUtf8(wgc::kModelFileName)); string w; - if (r.code != wgc::kOk || !wgc::verify_model_file(*ctx.fMap.map, std::filesystem::path(sideFile), w)) { + if (r.code != wgc::kOk || !wgc::verify_model_file(*ctx.fMap.map, std::filesystem::path(checkFile), w)) { if (why) *why = r.code != wgc::kOk ? FromUtf8(r.message) : L"the converted Ray Reconstruction data failed its check (" + FromUtf8(w) + L")"; // the converter names no cause: a full disk is the one the player can fix, so it is said when it is the case ULARGE_INTEGER freeBytes{}; @@ -400,6 +400,7 @@ bool WriteRrData(Context& ctx, const RrDataState& m, wstring* why) { RemoveTree(side); return false; } + out.Publish(); const wstring text = L"source\t" + m.dll + L"\r\nversion\t" + m.version + L"\r\norigin\t" + m.origin + L"\r\nconverted\t" + NowStamp(false) + L"\r\nmap\t" + FromUtf8(wgc::to_hex(ctx.fMap.map->file_sha256)) + L"\r\n" + // the source file's SHA-256: a later reuse is checked against the ignore lists with it (FindRrData) @@ -411,7 +412,7 @@ bool WriteRrData(Context& ctx, const RrDataState& m, wstring* why) { const wstring old = RrDataDir() + L".old"; if (IsDir(old)) RemoveTree(old); DWORD moveErr = 0; - for (int i = 0; i < 20 && IsDir(RrDataDir()) && !MoveFileExW(RrDataDir().c_str(), old.c_str(), MOVEFILE_WRITE_THROUGH); ++i) { + for (int i = 0; i < 20 && IsDir(RrDataDir()) && !MovePath(RrDataDir(), old, 0); ++i) { moveErr = GetLastError(); Sleep(150); } @@ -420,9 +421,9 @@ bool WriteRrData(Context& ctx, const RrDataState& m, wstring* why) { RemoveTree(side); return false; } - if (!MoveFileExW(side.c_str(), RrDataDir().c_str(), MOVEFILE_WRITE_THROUGH)) { + if (!MovePath(side, RrDataDir(), 0)) { const DWORD e = GetLastError(); - if (IsDir(old)) MoveFileExW(old.c_str(), RrDataDir().c_str(), MOVEFILE_WRITE_THROUGH); + if (IsDir(old)) MovePath(old, RrDataDir(), 0); if (why) *why = L"the converted Ray Reconstruction data could not be put in place (" + ErrText(e) + L")"; return false; } diff --git a/clean/installer/src/wg_core/rrconfig.cpp b/clean/installer/src/wg_core/rrconfig.cpp index 02f3853b..c1c82523 100644 --- a/clean/installer/src/wg_core/rrconfig.cpp +++ b/clean/installer/src/wg_core/rrconfig.cpp @@ -243,14 +243,14 @@ string RrConfigRemoveText(const string& in, const RrConfigFix& fix) { wstring RrConfigBackupPath(const wstring& dir) { return Join(Join(StateDir(dir), L"rr-config"), L"Engine.ini"); } static bool ReadOnly(const wstring& p) { - const DWORD a = GetFileAttributesW(p.c_str()); + const DWORD a = GetAttrs(p); return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_READONLY); } static void SetReadOnly(const wstring& p, bool on) { - const DWORD a = GetFileAttributesW(p.c_str()); + const DWORD a = GetAttrs(p); if (a == INVALID_FILE_ATTRIBUTES) return; const DWORD b = on ? (a | FILE_ATTRIBUTE_READONLY) : (a & ~(DWORD)FILE_ATTRIBUTE_READONLY); - if (b != a && !SetFileAttributesW(p.c_str(), b)) Fail(L"Cannot change the read-only attribute of " + p + L": " + ErrText(GetLastError())); + if (b != a && !SetAttrs(p, b)) Fail(L"Cannot change the read-only attribute of " + p + L": " + ErrText(GetLastError())); } static bool Utf16(const string& t) { return t.size() >= 2 && (((unsigned char)t[0] == 0xFF && (unsigned char)t[1] == 0xFE) || ((unsigned char)t[0] == 0xFE && (unsigned char)t[1] == 0xFF)); } @@ -384,12 +384,12 @@ void RevertRrConfig(Context& ctx, const wstring& dir, Record& m, std::vector= fix.folder.size() && IsDir(d); d = Parent(d)) { - if (!RemoveDirectoryW(d.c_str())) break; + if (!RemoveDirPath(d)) break; if (IEq(d, fix.folder)) break; } notes.push_back(L"Engine.ini's Ray Reconstruction setting was taken out again (" + file + L")"); - DeleteFileW(RrConfigBackupPath(dir).c_str()); - RemoveDirectoryW(Parent(RrConfigBackupPath(dir)).c_str()); + DeletePath(RrConfigBackupPath(dir)); + RemoveDirPath(Parent(RrConfigBackupPath(dir))); } catch (const SetupError& e) { warnings.push_back(L"Engine.ini could not be put back (" + e.msg + L"): take the line " + RrConfigLineW() + L" out of " + file + L" yourself" + (fix.setReadOnly ? L" and clear its read-only attribute" : L"")); @@ -410,7 +410,7 @@ int RrConfigLineState(Context& ctx, const RrConfigGame& g, wstring* file, wstrin if (!known) return -1; // no file: no line (0); a file that can't be read, or isn't text WrongGPU reads: said as such (3), never "no line", which // would send the player to Fix it again for nothing (r3 #8) - HANDLE h = CreateFileW(f.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr); + HANDLE h = OpenForRead(f, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE); if (h == INVALID_HANDLE_VALUE) { const DWORD e = GetLastError(); if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) return 0; @@ -426,7 +426,7 @@ int RrConfigLineState(Context& ctx, const RrConfigGame& g, wstring* file, wstrin RrConfigAddText(text, fix, &changed, true); // adding the line would change nothing: it is there if (changed) return 0; if (!g.readOnly) return 1; - const DWORD a = GetFileAttributesW(f.c_str()); + const DWORD a = GetAttrs(f); return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_READONLY) ? 1 : 2; } diff --git a/clean/installer/src/wg_core/secure_fs.cpp b/clean/installer/src/wg_core/secure_fs.cpp new file mode 100644 index 00000000..7e2411de --- /dev/null +++ b/clean/installer/src/wg_core/secure_fs.cpp @@ -0,0 +1,743 @@ +// SPDX-License-Identifier: MIT +// The elevated worker's file operations through held handles (secure_fs.h). Written for this project. +// +// The NT open (NtCreateFile) is used for one thing Win32 has no call for: opening a name relative to an open folder's +// handle (OBJECT_ATTRIBUTES.RootDirectory). FILE_OPEN_REPARSE_POINT is the NT form of FILE_FLAG_OPEN_REPARSE_POINT, and +// FILE_DIRECTORY_FILE with FILE_OPEN_FOR_BACKUP_INTENT the NT form of opening a folder with FILE_FLAG_BACKUP_SEMANTICS. +// Everything else is Win32: GetFileInformationByHandleEx, SetFileInformationByHandle (rename, delete, attributes), +// GetFinalPathNameByHandleW. +#include "secure_fs.h" + +#include + +#include "package_snapshot.h" // RandomHex + +#include + +namespace wg { + +namespace { + +// ---- NT open ------------------------------------------------------------------------------------------------------------ +constexpr ULONG kFileOpen = 1, kFileCreate = 2, kFileOpenIf = 3; // CreateDisposition +constexpr ULONG kDirectoryFile = 0x1, kSyncIo = 0x20, kNonDirectoryFile = 0x40, // CreateOptions + kBackupIntent = 0x4000, kOpenReparsePoint = 0x200000; +constexpr ULONG kCaseInsensitive = 0x40; // OBJ_CASE_INSENSITIVE +constexpr ULONG_PTR kFileCreated = 2; // IO_STATUS_BLOCK.Information +constexpr ULONG kShareNoDelete = FILE_SHARE_READ | FILE_SHARE_WRITE; +constexpr ULONG kShareAll = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; +constexpr ACCESS_MASK kDirAccess = FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES; + +using NtCreateFileFn = LONG(NTAPI*)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, PLARGE_INTEGER, ULONG, ULONG, ULONG, ULONG, PVOID, ULONG); +using NtSetInformationFileFn = LONG(NTAPI*)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, ULONG); +using StatusToErrorFn = ULONG(NTAPI*)(LONG); +struct NtCalls { NtCreateFileFn create = nullptr; NtSetInformationFileFn setInfo = nullptr; StatusToErrorFn toError = nullptr; }; +const NtCalls& Nt() { + static const NtCalls calls = [] { + NtCalls c; + if (HMODULE m = GetModuleHandleW(L"ntdll.dll")) { + c.create = reinterpret_cast(reinterpret_cast(GetProcAddress(m, "NtCreateFile"))); + c.setInfo = reinterpret_cast(reinterpret_cast(GetProcAddress(m, "NtSetInformationFile"))); + c.toError = reinterpret_cast(reinterpret_cast(GetProcAddress(m, "RtlNtStatusToDosError"))); + } + return c; + }(); + return calls; +} + +struct H { + HANDLE h = nullptr; + H() = default; + explicit H(HANDLE x) : h(x == INVALID_HANDLE_VALUE ? nullptr : x) {} + ~H() { if (h) CloseHandle(h); } + H(H&& o) noexcept : h(o.h) { o.h = nullptr; } + H& operator=(H&& o) noexcept { if (this != &o) { if (h) CloseHandle(h); h = o.h; o.h = nullptr; } return *this; } + H(const H&) = delete; + H& operator=(const H&) = delete; + HANDLE get() const { return h; } + HANDLE release() { HANDLE x = h; h = nullptr; return x; } + void reset() { if (h) CloseHandle(h); h = nullptr; } + explicit operator bool() const { return h != nullptr; } +}; + +// Opens `name` relative to the folder `dir` (dir null: `name` is an NT path), never following a reparse point at `name` +// itself unless `follow`. 0 or the Win32 error. `created`: whether it was created. +DWORD OpenAt(HANDLE dir, const wstring& name, ACCESS_MASK access, ULONG share, ULONG disposition, ULONG options, H& out, + bool* created = nullptr, PSECURITY_DESCRIPTOR sd = nullptr, bool follow = false) { + if (!Nt().create || !Nt().toError) return ERROR_PROC_NOT_FOUND; + if (name.empty() || name.size() > 32000) return ERROR_INVALID_NAME; + UNICODE_STRING us; + us.Buffer = const_cast(name.c_str()); + us.Length = us.MaximumLength = (USHORT)(name.size() * sizeof(wchar_t)); + OBJECT_ATTRIBUTES oa; + oa.Length = sizeof(oa); + oa.RootDirectory = dir; + oa.ObjectName = &us; + oa.Attributes = kCaseInsensitive; + oa.SecurityDescriptor = sd; + oa.SecurityQualityOfService = nullptr; + IO_STATUS_BLOCK io{}; + HANDLE h = nullptr; + const LONG st = Nt().create(&h, access | SYNCHRONIZE, &oa, &io, nullptr, FILE_ATTRIBUTE_NORMAL, share, disposition, + options | kSyncIo | (follow ? 0 : kOpenReparsePoint), nullptr, 0); + if (st < 0) return Nt().toError(st); + out = H(h); + if (created) *created = io.Information == kFileCreated; + return 0; +} + +// ---- reparse points ----------------------------------------------------------------------------------------------------- +// Reparse points that only store a file differently and lead nowhere else: Windows' file compression (WOF), +// deduplication, OneDrive's files on demand (the cloud tags and the older OneDrive tag). Any other reparse point (a +// junction, a symbolic link, and every tag that redirects a name) is a link. +bool StoresOnly(DWORD tag) { + if (IsReparseTagNameSurrogate(tag)) return false; + return tag == 0x80000017u /*WOF*/ || tag == 0x80000013u /*DEDUP*/ || (tag & 0xFFFF0FFFu) == 0x9000001Au /*CLOUD_n*/ || tag == 0x80000021u /*ONEDRIVE*/; +} +struct Tag { DWORD attrs = 0, tag = 0; }; +bool TagOf(HANDLE h, Tag& t) { + FILE_ATTRIBUTE_TAG_INFO i{}; + if (!GetFileInformationByHandleEx(h, FileAttributeTagInfo, &i, sizeof(i))) return false; + t.attrs = i.FileAttributes; + t.tag = i.ReparseTag; + return true; +} +bool IsLink(const Tag& t) { return (t.attrs & FILE_ATTRIBUTE_REPARSE_POINT) && !StoresOnly(t.tag); } +bool SameFile(HANDLE a, HANDLE b) { + FILE_ID_INFO x{}, y{}; + if (GetFileInformationByHandleEx(a, FileIdInfo, &x, sizeof(x)) && GetFileInformationByHandleEx(b, FileIdInfo, &y, sizeof(y))) + return x.VolumeSerialNumber == y.VolumeSerialNumber && memcmp(&x.FileId, &y.FileId, sizeof(x.FileId)) == 0; + BY_HANDLE_FILE_INFORMATION p{}, q{}; + return GetFileInformationByHandle(a, &p) && GetFileInformationByHandle(b, &q) && p.dwVolumeSerialNumber == q.dwVolumeSerialNumber && + p.nFileIndexHigh == q.nFileIndexHigh && p.nFileIndexLow == q.nFileIndexLow; +} + +// A refusal inside this file; the public operations turn it into SetupError (or AddRoot's `why`). +struct Refusal { wstring msg; }; +[[noreturn]] void Refuse(const wstring& m) { throw Refusal{m}; } +[[noreturn]] void LinkRefused(const wstring& path) { + Refuse(path + L" is a link (a junction, a symbolic link or another reparse point that leads elsewhere); the elevated step does not act through links"); +} + +bool SameName(const wstring& a, const wstring& b) { + return a.size() == b.size() && CompareStringOrdinal(a.c_str(), (int)a.size(), b.c_str(), (int)b.size(), TRUE) == CSTR_EQUAL; +} + +// The final path of `h` must be `expected`. +void CheckFinal(HANDLE h, const wstring& expected) { + const wstring got = FinalPathOfHandle(h); + if (got.empty()) Refuse(L"Windows cannot say where " + expected + L" is; the elevated step stops"); + if (!SameName(got, expected)) Refuse(expected + L" is not where its path says (Windows reports " + got + L"); the elevated step stops"); +} + +// ---- paths -------------------------------------------------------------------------------------------------------------- +struct Parsed { + wstring norm; // NormalPath + wstring dosRoot, ntRoot; // "C:\" and "\??\C:\", or "\\server\share\" and "\??\UNC\server\share\" + std::vector parts; // the components below the root +}; +bool GoodPart(const wstring& s) { + if (s.empty() || s == L"." || s == L"..") return false; + for (wchar_t c : s) if (c < 32 || wcschr(L"<>:\"/\\|?*", c)) return false; // no stream names, no wildcards + return true; +} +bool Parse(const wstring& in, Parsed& p) { + p = Parsed(); + p.norm = NormalPath(in); + if (p.norm.empty()) return false; + wstring rest; + if (p.norm[1] == L':') { + p.dosRoot = p.norm.substr(0, 2) + L"\\"; + p.ntRoot = L"\\??\\" + p.dosRoot; + rest = p.norm.size() > 3 ? p.norm.substr(3) : wstring(); + } else { + const size_t server = p.norm.find(L'\\', 2), share = server == wstring::npos ? wstring::npos : p.norm.find(L'\\', server + 1); + if (server == wstring::npos || server == 2) return false; + const wstring head = share == wstring::npos ? p.norm : p.norm.substr(0, share); + if (head.size() <= server + 1) return false; + p.dosRoot = head + L"\\"; + p.ntRoot = L"\\??\\UNC\\" + head.substr(2) + L"\\"; + rest = share == wstring::npos ? wstring() : p.norm.substr(share + 1); + } + size_t at = 0; + while (at < rest.size()) { + size_t e = rest.find(L'\\', at); + if (e == wstring::npos) e = rest.size(); + const wstring part = rest.substr(at, e - at); + if (!GoodPart(part)) return false; + p.parts.push_back(part); + at = e + 1; + } + return true; +} +wstring PathOf(const Parsed& p, size_t n) { + wstring s = p.dosRoot; + for (size_t i = 0; i < n; ++i) s += (i ? L"\\" : L"") + p.parts[i]; + return n ? s : (p.dosRoot.size() == 3 ? p.dosRoot : p.dosRoot.substr(0, p.dosRoot.size() - 1)); +} + +// The folder `name` below `dir`, held without delete sharing; a link refused; a reparse point that only stores the folder +// differently reopened as the folder itself (checked to be the same). +DWORD OpenDirAt(HANDLE dir, const wstring& name, const wstring& path, H& out) { + DWORD e = OpenAt(dir, name, kDirAccess, kShareNoDelete, kFileOpen, kDirectoryFile | kBackupIntent, out); + if (e == ERROR_ACCESS_DENIED) e = OpenAt(dir, name, FILE_TRAVERSE | FILE_READ_ATTRIBUTES, kShareNoDelete, kFileOpen, kDirectoryFile | kBackupIntent, out); + if (e) return e; + Tag t; + if (!TagOf(out.get(), t)) { out.reset(); return GetLastError(); } + if (IsLink(t)) { out.reset(); LinkRefused(path); } + if ((t.attrs & FILE_ATTRIBUTE_REPARSE_POINT) && dir) { + H again; + if (DWORD e2 = OpenAt(dir, name, kDirAccess, kShareNoDelete, kFileOpen, kDirectoryFile | kBackupIntent, again, nullptr, nullptr, true)) return e2; + if (!SameFile(out.get(), again.get())) Refuse(path + L" changed while it was opened; the elevated step stops"); + out = std::move(again); + } + return 0; +} + +// The volume root and the folders parts[0..n), each held; 0 or the Win32 error (a link: Refusal). +DWORD OpenChain(const Parsed& p, size_t n, std::vector& chain) { + H vol; + DWORD e = OpenAt(nullptr, p.ntRoot, kDirAccess, kShareNoDelete, kFileOpen, kDirectoryFile | kBackupIntent, vol); + if (e == ERROR_ACCESS_DENIED) e = OpenAt(nullptr, p.ntRoot, FILE_TRAVERSE | FILE_READ_ATTRIBUTES, kShareNoDelete, kFileOpen, kDirectoryFile | kBackupIntent, vol); + if (e) return e; + chain.push_back(std::move(vol)); + for (size_t i = 0; i < n; ++i) { + H d; + if ((e = OpenDirAt(chain.back().get(), p.parts[i], PathOf(p, i + 1), d))) return e == ERROR_DIRECTORY ? ERROR_PATH_NOT_FOUND : e; + chain.push_back(std::move(d)); + } + return 0; +} + +// The entries of the open folder `h`. +DWORD ListHandle(HANDLE h, std::vector& out) { + std::vector buf(64 * 1024); + bool first = true; + for (;;) { + if (!GetFileInformationByHandleEx(h, first ? FileFullDirectoryRestartInfo : FileFullDirectoryInfo, buf.data(), (DWORD)buf.size())) { + const DWORD e = GetLastError(); + return e == ERROR_NO_MORE_FILES || e == ERROR_FILE_NOT_FOUND ? 0 : e; + } + first = false; + size_t at = 0; + for (;;) { + const auto* fi = reinterpret_cast(buf.data() + at); + const wstring name(fi->FileName, fi->FileNameLength / sizeof(wchar_t)); + if (name != L"." && name != L"..") { + DWORD attrs = fi->FileAttributes; + if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) && StoresOnly(fi->EaSize)) attrs &= ~FILE_ATTRIBUTE_REPARSE_POINT; // EaSize: the tag + out.push_back({name, attrs, (unsigned long long)fi->EndOfFile.QuadPart}); + } + if (!fi->NextEntryOffset) break; + at += fi->NextEntryOffset; + } + } +} + +// Deletes the open object `h` (it must have DELETE access): its name goes at once where the volume allows it. +DWORD Dispose(HANDLE h) { + struct { ULONG flags; } ex{0x1 | 0x2}; // FILE_DISPOSITION_INFO_EX: DELETE | POSIX_SEMANTICS + if (SetFileInformationByHandle(h, (FILE_INFO_BY_HANDLE_CLASS)21 /*FileDispositionInfoEx*/, &ex, sizeof(ex))) return 0; + const DWORD e = GetLastError(); + if (e != ERROR_INVALID_PARAMETER && e != ERROR_NOT_SUPPORTED && e != ERROR_INVALID_FUNCTION) return e; + FILE_DISPOSITION_INFO d{TRUE}; + return SetFileInformationByHandle(h, FileDispositionInfo, &d, sizeof(d)) ? 0 : GetLastError(); +} +// Renames the open object `h` (DELETE access) to `leaf` in the open folder `dir`. NtSetInformationFile with +// FileRenameInformation: SetFileInformationByHandle(FileRenameInfo) refuses a root directory handle (ERROR_INVALID_PARAMETER), +// so the rename relative to the held folder takes the NT call with the same structure (FILE_RENAME_INFO's layout). +DWORD RenameHandle(HANDLE h, HANDLE dir, const wstring& leaf, bool replace) { + if (!Nt().setInfo || !Nt().toError) return ERROR_PROC_NOT_FOUND; + std::vector buf(sizeof(FILE_RENAME_INFO) + leaf.size() * sizeof(wchar_t)); + auto* ri = reinterpret_cast(buf.data()); + ri->ReplaceIfExists = replace ? TRUE : FALSE; + ri->RootDirectory = dir; + ri->FileNameLength = (DWORD)(leaf.size() * sizeof(wchar_t)); + memcpy(ri->FileName, leaf.data(), leaf.size() * sizeof(wchar_t)); + IO_STATUS_BLOCK io{}; + const LONG st = Nt().setInfo(h, &io, ri, (ULONG)buf.size(), 10 /*FileRenameInformation*/); + return st < 0 ? Nt().toError(st) : 0; +} +DWORD SetAttrsOf(HANDLE h, DWORD attrs) { + FILE_BASIC_INFO bi{}; + attrs &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_TEMPORARY | + FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED; + bi.FileAttributes = attrs ? attrs : FILE_ATTRIBUTE_NORMAL; + return SetFileInformationByHandle(h, FileBasicInfo, &bi, sizeof(bi)) ? 0 : GetLastError(); +} +bool WriteAllTo(HANDLE h, const void* data, size_t size, DWORD& err) { + const char* p = static_cast(data); + size_t done = 0; + while (done < size) { + DWORD wrote = 0; + if (!WriteFile(h, p + done, (DWORD)std::min(size - done, 1u << 24), &wrote, nullptr) || !wrote) { err = GetLastError(); return false; } + done += wrote; + } + return true; +} + +wstring LongFullPath(const wstring& p) { + DWORD n = GetFullPathNameW(p.c_str(), 0, nullptr, nullptr); + if (!n) return L""; + wstring b(n, L'\0'); + n = GetFullPathNameW(p.c_str(), n, &b[0], nullptr); + if (!n || n >= b.size()) return L""; + b.resize(n); + return b; +} + +std::atomic g_active{nullptr}; + +} // namespace + +// ---- paths (public) ----------------------------------------------------------------------------------------------------- +bool ReparseTagIsLink(DWORD tag) { return !StoresOnly(tag); } + +wstring NormalPath(const wstring& in) { + wstring s = in; + for (auto& c : s) if (c == L'/') c = L'\\'; + if (s.rfind(L"\\\\?\\UNC\\", 0) == 0) s = L"\\\\" + s.substr(8); + else if (s.rfind(L"\\\\?\\", 0) == 0) s = s.substr(4); + const bool drive = s.size() >= 3 && iswalpha(s[0]) && s[1] == L':' && s[2] == L'\\'; + const bool unc = s.size() > 4 && s[0] == L'\\' && s[1] == L'\\' && s[2] != L'?' && s[2] != L'.' && s[2] != L'\\'; + if (!drive && !unc) return L""; + s = LongFullPath(s); + if (s.size() < 3 || (s[1] == L':' && s[2] != L'\\') || s.rfind(L"\\\\?\\", 0) == 0 || s.rfind(L"\\\\.\\", 0) == 0) return L""; + while (s.size() > 3 && s.back() == L'\\') s.pop_back(); + if (s[1] == L':') s[0] = (wchar_t)towupper(s[0]); + return s; +} + +wstring FinalPathOfHandle(HANDLE h) { + DWORD n = GetFinalPathNameByHandleW(h, nullptr, 0, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); + if (!n) return L""; + wstring b(n + 1, L'\0'); + n = GetFinalPathNameByHandleW(h, &b[0], (DWORD)b.size(), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); + if (!n || n >= b.size()) return L""; + b.resize(n); + if (b.rfind(L"\\\\?\\UNC\\", 0) == 0) b = L"\\\\" + b.substr(8); + else if (b.rfind(L"\\\\?\\", 0) == 0) b = b.substr(4); + while (b.size() > 3 && b.back() == L'\\') b.pop_back(); + if (b.size() >= 2 && b[1] == L':') b[0] = (wchar_t)towupper(b[0]); + return b; +} + +wstring BoundPath(const wstring& p) { + if (p.empty()) return p; + const wstring norm = NormalPath(p); + if (norm.empty()) return p; + H h(CreateFileW(norm.c_str(), FILE_READ_ATTRIBUTES, kShareAll, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + if (h) { + const wstring f = FinalPathOfHandle(h.get()); + return f.empty() ? norm : f; + } + const wstring parent = Parent(norm); + if (norm.size() <= 3 || parent.empty() || parent.size() >= norm.size() || (parent.size() == 2 && parent[1] == L':')) return norm; + return Join(BoundPath(parent), BaseName(norm)); +} + +// ---- the guard ---------------------------------------------------------------------------------------------------------- +struct FsGuard::Impl { + struct Root { Parsed p; std::vector chain; }; + std::vector> roots; + + // `path` resolved to its parent folder's open handle: below the nearest root's held handle, else (reading only) below + // the volume root. 0 or the error (a folder on the way missing; ERROR_INVALID_NAME: not an absolute path). + struct Walk { + Parsed p; + std::vector chain; // the folders opened for this walk + HANDLE parent = nullptr; // the leaf's folder; the object itself when `leaf` is empty + wstring leaf; // empty: the path is a root (or a volume root) + const Root* root = nullptr; + }; + DWORD WalkTo(const wstring& path, bool write, Walk& w) const { + if (!Parse(path, w.p)) { + if (write) Refuse((path.empty() ? wstring(L"(no path)") : path) + L" is not an absolute path to a file or folder"); + return ERROR_INVALID_NAME; + } + for (auto& r : roots) { + if (!SameName(r->p.dosRoot, w.p.dosRoot) || r->p.parts.size() > w.p.parts.size()) continue; + bool in = true; + for (size_t i = 0; in && i < r->p.parts.size(); ++i) in = SameName(r->p.parts[i], w.p.parts[i]); + if (in && (!w.root || r->p.parts.size() > w.root->p.parts.size())) w.root = r.get(); + } + if (!w.root && write) Refuse(w.p.norm + L" is outside the folders this job may change"); + size_t depth = 0; + HANDLE at = nullptr; + if (w.root) { depth = w.root->p.parts.size(); at = w.root->chain.back().get(); } + else { + if (DWORD e = OpenChain(w.p, 0, w.chain)) return e; + at = w.chain.back().get(); + } + if (depth == w.p.parts.size()) { w.parent = at; return 0; } + for (size_t i = depth; i + 1 < w.p.parts.size(); ++i) { + H d; + if (DWORD e = OpenDirAt(at, w.p.parts[i], PathOf(w.p, i + 1), d)) return e == ERROR_FILE_NOT_FOUND || e == ERROR_DIRECTORY ? ERROR_PATH_NOT_FOUND : e; + at = d.get(); + w.chain.push_back(std::move(d)); + } + w.parent = at; + w.leaf = w.p.parts.back(); + return 0; + } + // The leaf of `w`, never through a link, its final path checked; `data`: a reparse point that only stores the file + // differently is reopened as the file itself (checked to be the same) so that its contents read as usual. + DWORD OpenLeaf(const Walk& w, ACCESS_MASK access, ULONG share, ULONG options, H& out, bool data) const { + if (DWORD e = OpenAt(w.parent, w.leaf, access, share, kFileOpen, options | kBackupIntent, out)) return e; + Tag t; + if (!TagOf(out.get(), t)) { const DWORD e = GetLastError(); out.reset(); return e; } + if (IsLink(t)) { out.reset(); LinkRefused(w.p.norm); } + if (data && (t.attrs & FILE_ATTRIBUTE_REPARSE_POINT)) { + H again; + if (DWORD e = OpenAt(w.parent, w.leaf, access, share, kFileOpen, options | kBackupIntent, again, nullptr, nullptr, true)) return e; + if (!SameFile(out.get(), again.get())) Refuse(w.p.norm + L" changed while it was opened; the elevated step stops"); + out = std::move(again); + } + CheckFinal(out.get(), w.p.norm); + return 0; + } + // A new file next to the leaf of `w` (`leaf` + suffix), for writing; an old one of that name (left by an interrupted + // run) is deleted first. + DWORD CreateTemp(const Walk& w, H& out) const { + const wstring name = w.leaf + kTmpSuffix; + DWORD e = OpenAt(w.parent, name, FILE_GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, 0, kFileCreate, kNonDirectoryFile, out); + if (e == ERROR_ALREADY_EXISTS || e == ERROR_FILE_EXISTS) { + H old; + if (!OpenAt(w.parent, name, DELETE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, kShareAll, kFileOpen, kNonDirectoryFile, old)) { + Tag t; + if (TagOf(old.get(), t) && IsLink(t)) LinkRefused(w.p.norm + kTmpSuffix); + SetAttrsOf(old.get(), FILE_ATTRIBUTE_NORMAL); + Dispose(old.get()); + } + old.reset(); + e = OpenAt(w.parent, name, FILE_GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, 0, kFileCreate, kNonDirectoryFile, out); + } + if (!e) CheckFinal(out.get(), w.p.norm + kTmpSuffix); + return e; + } + // The existing leaf of `w` (if any) made replaceable: a link refused, read-only cleared. + void PrepareTarget(const Walk& w) const { + H old; + if (OpenAt(w.parent, w.leaf, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, kShareAll, kFileOpen, kBackupIntent, old)) return; + Tag t; + if (!TagOf(old.get(), t)) return; + if (IsLink(t)) LinkRefused(w.p.norm); + if (t.attrs & FILE_ATTRIBUTE_READONLY) SetAttrsOf(old.get(), FILE_ATTRIBUTE_NORMAL); + } + // Moves the written temporary file `tmp` over the leaf of `w`. + DWORD Commit(const Walk& w, H& tmp) const { + FlushFileBuffers(tmp.get()); + try { PrepareTarget(w); } catch (const Refusal&) { Dispose(tmp.get()); throw; } + if (DWORD e = RenameHandle(tmp.get(), w.parent, w.leaf, true)) { Dispose(tmp.get()); return e; } + CheckFinal(tmp.get(), w.p.norm); + return 0; + } + void RemoveTreeAt(HANDLE dir, const wstring& path, const wstring& keep) const { + std::vector entries; + if (ListHandle(dir, entries)) return; + for (auto& en : entries) { + const wstring child = Join(path, en.name); + if (en.attrs & FILE_ATTRIBUTE_REPARSE_POINT) continue; // a link: never followed, never removed + H c; + if (OpenAt(dir, en.name, DELETE | FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, kShareAll, kFileOpen, kBackupIntent, c)) continue; + Tag t; + if (!TagOf(c.get(), t) || IsLink(t)) continue; + if (t.attrs & FILE_ATTRIBUTE_DIRECTORY) RemoveTreeAt(c.get(), child, keep); + else if (!keep.empty() && SameName(child, keep)) continue; + else if (t.attrs & FILE_ATTRIBUTE_READONLY) SetAttrsOf(c.get(), FILE_ATTRIBUTE_NORMAL); + Dispose(c.get()); + } + } +}; + +FsGuard::FsGuard() : impl_(new Impl) {} +FsGuard::~FsGuard() { + FsGuard* self = this; + g_active.compare_exchange_strong(self, nullptr); +} + +bool FsGuard::AddRoot(const wstring& path, wstring& why) { + auto r = std::make_unique(); + if (!Parse(path, r->p)) { why = path + L" is not an absolute path to a folder"; return false; } + try { + if (DWORD e = OpenChain(r->p, r->p.parts.size(), r->chain)) { + why = L"the folder " + r->p.norm + L" cannot be opened (" + ErrText(e) + L")"; + return false; + } + CheckFinal(r->chain.back().get(), r->p.norm); + } catch (const Refusal& x) { + why = x.msg; + return false; + } + impl_->roots.push_back(std::move(r)); + return true; +} +std::vector FsGuard::Roots() const { + std::vector out; + for (auto& r : impl_->roots) out.push_back(r->p.norm); + return out; +} + +// Every public operation: a Refusal becomes SetupError (EXIT_REFUSED). +#define WG_GUARDED(...) try { __VA_ARGS__ } catch (const Refusal& x) { Fail(x.msg, EXIT_REFUSED); } + +DWORD FsGuard::Attributes(const wstring& path, unsigned long long* size, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, false, w))) return INVALID_FILE_ATTRIBUTES; + H h; + HANDLE target = w.parent; + if (!w.leaf.empty()) { + if ((err = impl_->OpenLeaf(w, FILE_READ_ATTRIBUTES, kShareAll, 0, h, false))) return INVALID_FILE_ATTRIBUTES; + target = h.get(); + } + Tag t; + if (!TagOf(target, t)) { err = GetLastError(); return INVALID_FILE_ATTRIBUTES; } + if (size) { + FILE_STANDARD_INFO si{}; + *size = GetFileInformationByHandleEx(target, FileStandardInfo, &si, sizeof(si)) ? (unsigned long long)si.EndOfFile.QuadPart : 0; + } + err = 0; + return t.attrs & ~(DWORD)FILE_ATTRIBUTE_REPARSE_POINT; // (a link was refused above) + ) +} + +HANDLE FsGuard::OpenRead(const wstring& path, DWORD share, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, false, w))) return INVALID_HANDLE_VALUE; + if (w.leaf.empty()) { err = ERROR_ACCESS_DENIED; return INVALID_HANDLE_VALUE; } + H h; + if ((err = impl_->OpenLeaf(w, FILE_GENERIC_READ, share, kNonDirectoryFile, h, true))) return INVALID_HANDLE_VALUE; + return h.release(); + ) +} + +HANDLE FsGuard::CreateNew(const wstring& path, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, true, w))) return INVALID_HANDLE_VALUE; + if (w.leaf.empty()) Refuse(w.p.norm + L" is one of the job's folders, not a file"); + H h; + if ((err = OpenAt(w.parent, w.leaf, FILE_GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, 0, kFileCreate, kNonDirectoryFile, h))) return INVALID_HANDLE_VALUE; + CheckFinal(h.get(), w.p.norm); + return h.release(); + ) +} + +bool FsGuard::CreateNewDir(const wstring& path, PSECURITY_DESCRIPTOR sd, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, true, w))) return false; + if (w.leaf.empty()) { err = ERROR_ALREADY_EXISTS; return false; } + H h; + if ((err = OpenAt(w.parent, w.leaf, FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES, kShareAll, kFileCreate, kDirectoryFile | kBackupIntent, h, nullptr, sd))) return false; + CheckFinal(h.get(), w.p.norm); + return true; + ) +} + +void FsGuard::EnsureDir(const wstring& dir, std::vector* created) { + WG_GUARDED( + Impl::Walk w; + if (!Parse(dir, w.p)) Refuse((dir.empty() ? wstring(L"(no path)") : dir) + L" is not an absolute path to a folder"); + // the deepest root above it (outside every root: refused), then each missing folder made below the one before + impl_->WalkTo(dir, true, w); + const Impl::Root* r = w.root; + HANDLE at = r->chain.back().get(); + std::vector chain; + for (size_t i = r->p.parts.size(); i < w.p.parts.size(); ++i) { + const wstring here = PathOf(w.p, i + 1); + H d; + bool made = false; + DWORD e = OpenAt(at, w.p.parts[i], kDirAccess, kShareNoDelete, kFileOpenIf, kDirectoryFile | kBackupIntent, d, &made); + if (e == ERROR_DIRECTORY || e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS) { + H f; + if (!OpenAt(at, w.p.parts[i], FILE_READ_ATTRIBUTES, kShareAll, kFileOpen, kBackupIntent, f)) { + Tag t; + if (TagOf(f.get(), t) && IsLink(t)) LinkRefused(here); + } + Fail(L"A file is in the way of the folder " + here + L". Remove or rename it and run setup again."); + } + if (e) Fail(L"Cannot create folder " + here + L": " + ErrText(e)); + Tag t; + if (!TagOf(d.get(), t) || IsLink(t)) LinkRefused(here); + CheckFinal(d.get(), here); + if (made && created) created->push_back(here); + at = d.get(); + chain.push_back(std::move(d)); + } + ) +} + +void FsGuard::WriteAtomic(const wstring& path, const void* data, size_t size) { + WG_GUARDED( + Impl::Walk w; + if (DWORD e = impl_->WalkTo(path, true, w)) Fail(L"Cannot write " + path + L": " + ErrText(e)); + if (w.leaf.empty()) Refuse(w.p.norm + L" is one of the job's folders, not a file"); + H tmp; + if (DWORD e = impl_->CreateTemp(w, tmp)) Fail(L"Cannot write " + path + L": " + ErrText(e)); + DWORD e = 0; + if (!WriteAllTo(tmp.get(), data, size, e)) { Dispose(tmp.get()); Fail(L"Write failed for " + path + L": " + ErrText(e)); } + if ((e = impl_->Commit(w, tmp))) Fail(L"Cannot replace " + path + L": " + ErrText(e) + L". Is the file in use?"); + ) +} + +bool FsGuard::Copy(const wstring& src, const wstring& dst, DWORD& err) { + WG_GUARDED( + H in(OpenRead(src, FILE_SHARE_READ | FILE_SHARE_DELETE, err)); + if (!in) return false; + Impl::Walk w; + if ((err = impl_->WalkTo(dst, true, w))) return false; + if (w.leaf.empty()) Refuse(w.p.norm + L" is one of the job's folders, not a file"); + H tmp; + if ((err = impl_->CreateTemp(w, tmp))) return false; + std::vector buf(1 << 20); + for (;;) { + DWORD got = 0; + if (!ReadFile(in.get(), buf.data(), (DWORD)buf.size(), &got, nullptr)) { err = GetLastError(); Dispose(tmp.get()); return false; } + if (!got) break; + if (!WriteAllTo(tmp.get(), buf.data(), got, err)) { Dispose(tmp.get()); return false; } + } + // as CopyFileW: the source's attributes and last write time + FILE_BASIC_INFO bi{}; + if (GetFileInformationByHandleEx(in.get(), FileBasicInfo, &bi, sizeof(bi))) { + FILE_BASIC_INFO set{}; + set.LastWriteTime = bi.LastWriteTime; + set.FileAttributes = bi.FileAttributes & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE); + if (!set.FileAttributes) set.FileAttributes = FILE_ATTRIBUTE_NORMAL; + FlushFileBuffers(tmp.get()); + SetFileInformationByHandle(tmp.get(), FileBasicInfo, &set, sizeof(set)); + } + if ((err = impl_->Commit(w, tmp))) return false; + return true; + ) +} + +bool FsGuard::Unlink(const wstring& path, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, true, w))) return false; + if (w.leaf.empty()) Refuse(w.p.norm + L" is one of the job's folders; it is never deleted"); + H h; + if ((err = impl_->OpenLeaf(w, DELETE | FILE_READ_ATTRIBUTES, kShareAll, kNonDirectoryFile, h, false))) return false; + return !(err = Dispose(h.get())); + ) +} + +bool FsGuard::RemoveDir(const wstring& path, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, true, w))) return false; + if (w.leaf.empty()) Refuse(w.p.norm + L" is one of the job's folders; it is never removed"); + H h; + if ((err = impl_->OpenLeaf(w, DELETE | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES, kShareAll, kDirectoryFile, h, false))) return false; + return !(err = Dispose(h.get())); + ) +} + +void FsGuard::RemoveTree(const wstring& dir, const wstring& keepFile) { + WG_GUARDED( + Impl::Walk w; + if (impl_->WalkTo(dir, true, w)) return; + if (w.leaf.empty()) Refuse(w.p.norm + L" is one of the job's folders; it is never removed"); + H h; + if (impl_->OpenLeaf(w, DELETE | FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES, kShareAll, kDirectoryFile, h, false)) return; + const wstring keep = keepFile.empty() ? wstring() : NormalPath(keepFile); + impl_->RemoveTreeAt(h.get(), w.p.norm, keep); + Dispose(h.get()); + ) +} + +bool FsGuard::Move(const wstring& from, const wstring& to, bool replace, bool copyAllowed, DWORD& err) { + WG_GUARDED( + Impl::Walk f, t; + if ((err = impl_->WalkTo(from, true, f))) return false; + if (f.leaf.empty()) Refuse(f.p.norm + L" is one of the job's folders; it is never moved"); + H s; + if ((err = impl_->OpenLeaf(f, DELETE | FILE_READ_ATTRIBUTES, kShareAll, 0, s, false))) return false; + if ((err = impl_->WalkTo(to, true, t))) return false; + if (t.leaf.empty()) Refuse(t.p.norm + L" is one of the job's folders"); + { // a link at the target is refused (a rename would replace the link itself, but nothing is done with links) + H old; + if (!OpenAt(t.parent, t.leaf, FILE_READ_ATTRIBUTES, kShareAll, kFileOpen, kBackupIntent, old)) { + Tag tg; + if (TagOf(old.get(), tg) && IsLink(tg)) LinkRefused(t.p.norm); + if (!replace) { err = ERROR_ALREADY_EXISTS; return false; } + } + } + err = RenameHandle(s.get(), t.parent, t.leaf, replace); + if (err == ERROR_NOT_SAME_DEVICE && copyAllowed) { + Tag tg; + if (!TagOf(s.get(), tg) || (tg.attrs & FILE_ATTRIBUTE_DIRECTORY)) return false; + s.reset(); + if (!Copy(from, to, err)) return false; + return Unlink(from, err); + } + if (err) return false; + CheckFinal(s.get(), t.p.norm); + return true; + ) +} + +bool FsGuard::SetAttributes(const wstring& path, DWORD attrs, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(path, true, w))) return false; + if (w.leaf.empty()) return true; // a root's own attributes are not changed + H own; + if ((err = impl_->OpenLeaf(w, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, kShareAll, 0, own, false))) return false; + return !(err = SetAttrsOf(own.get(), attrs)); + ) +} + +bool FsGuard::List(const wstring& dir, std::vector& out, DWORD& err) { + WG_GUARDED( + Impl::Walk w; + if ((err = impl_->WalkTo(dir, false, w))) return false; + H h; + HANDLE target = w.parent; + if (!w.leaf.empty()) { + if ((err = impl_->OpenLeaf(w, kDirAccess, kShareAll, kDirectoryFile, h, true))) return false; + target = h.get(); + } + return !(err = ListHandle(target, out)); + ) +} + +#undef WG_GUARDED + +// ---- the converter's files ---------------------------------------------------------------------------------------------- +static wstring PrivateSub(const wstring& privateDir, const wchar_t* what) { + if (privateDir.empty()) Fail(L"the elevated step has no private folder for the converter's files"); + return Join(privateDir, wstring(what) + RandomHex()); +} +ConverterFile::ConverterFile(const wstring& file, const wstring& privateDir) : path_(file) { + if (!ActiveFsGuard() || file.empty()) return; + dir_ = PrivateSub(privateDir, L"converter-in-"); + EnsureDir(dir_); + path_ = Join(dir_, BaseName(file)); + CopyPath(file, path_); // (not there: the converter then finds no file, as it would have) +} +ConverterFile::~ConverterFile() { + if (dir_.empty()) return; + try { RemoveTree(dir_); } catch (const SetupError&) {} +} +ConverterDir::ConverterDir(const wstring& dir, const wstring& privateDir) : dir_(dir), path_(dir) { + if (ActiveFsGuard()) path_ = PrivateSub(privateDir, L"converter-out-"); +} +ConverterDir::~ConverterDir() { + if (path_ == dir_) return; + try { RemoveTree(path_); } catch (const SetupError&) {} +} +void ConverterDir::Publish() { + if (path_ == dir_) return; + EnsureDir(dir_); + for (auto& f : ListFiles(path_, L"*")) CopyChecked(f, Join(dir_, BaseName(f))); +} + +FsGuard* ActiveFsGuard() { return g_active.load(); } +ScopedFsGuard::ScopedFsGuard(FsGuard* g) : prev_(g_active.exchange(g)) {} +ScopedFsGuard::~ScopedFsGuard() { g_active.store(prev_); } + +} // namespace wg diff --git a/clean/installer/src/wg_core/secure_fs.h b/clean/installer/src/wg_core/secure_fs.h new file mode 100644 index 00000000..3e6a4071 --- /dev/null +++ b/clean/installer/src/wg_core/secure_fs.h @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: MIT +// The elevated worker's file operations through held handles (elevated_job.h). Written for this project. +// +// While an FsGuard is active (ScopedFsGuard), the file helpers of util.h (Exists, ReadAll, EnsureDir, WriteFileAtomic, +// CopyChecked, MovePath, DeletePath, RemoveTree, ListFiles, ...) act through it instead of by path: +// - the folders the job may change (its roots: the game, the player's local app data and Documents folders, the worker's +// private folder) are opened when the job is checked, from the volume root one component at a time, never following a +// link, and stay open until the job ends: every component is held without delete sharing, so none of them can be +// renamed, replaced or deleted meanwhile; +// - every path is opened the same way, below the nearest root's held handle (a path outside every root, which is only +// ever read, below the volume root); +// - a component that is a link (a junction, a symbolic link or any other reparse point that redirects a name) is refused, +// the leaf too. Reparse points that only store a file differently and lead nowhere else (Windows' file compression, +// OneDrive's files on demand, deduplication) are opened as the file itself and checked to be the same file; +// - after each open, the path Windows reports for the handle (GetFinalPathNameByHandle) must be the path asked for; +// - files are created next to their target under a new name and renamed over it through the handle, renamed and deleted +// through their handle (SetFileInformationByHandle), and created relative to their folder's handle (NtCreateFile with a +// root directory); +// - nothing outside the roots is written. +// A refusal throws SetupError (Fail) with the path and the reason; an ordinary failure (not there, in use) is returned as +// with the path-based helpers. +#pragma once + +#include + +#include "util.h" + +namespace wg { + +class FsGuard { +public: + FsGuard(); + ~FsGuard(); + FsGuard(const FsGuard&) = delete; + FsGuard& operator=(const FsGuard&) = delete; + + // A folder this job may change: opened and held as described above. False with `why` when a component is a link, the + // folder is not there or is not where `path` says (its final path is another). + bool AddRoot(const wstring& path, wstring& why); + std::vector Roots() const; + + // ---- what util.h's helpers do while the guard is active ------------------------------------------------------------- + // Attributes of `path` (INVALID_FILE_ATTRIBUTES with `err` set: not there); `size`: the file's size. + DWORD Attributes(const wstring& path, unsigned long long* size, DWORD& err); + // An open handle (INVALID_HANDLE_VALUE with `err`): to read, or a new file to write (fails when the name exists). + HANDLE OpenRead(const wstring& path, DWORD share, DWORD& err); + HANDLE CreateNew(const wstring& path, DWORD& err); + // A new folder; `sd`: its security descriptor (null: inherited). Fails when the name exists. + bool CreateNewDir(const wstring& path, PSECURITY_DESCRIPTOR sd, DWORD& err); + void EnsureDir(const wstring& dir, std::vector* created); + void WriteAtomic(const wstring& path, const void* data, size_t size); + bool Copy(const wstring& src, const wstring& dst, DWORD& err); + bool Unlink(const wstring& path, DWORD& err); // a file + bool RemoveDir(const wstring& path, DWORD& err); // an empty folder + void RemoveTree(const wstring& dir, const wstring& keepFile); + bool Move(const wstring& from, const wstring& to, bool replace, bool copyAllowed, DWORD& err); + bool SetAttributes(const wstring& path, DWORD attrs, DWORD& err); + struct Entry { wstring name; DWORD attrs; unsigned long long size; }; // attrs: FILE_ATTRIBUTE_REPARSE_POINT only for a link + bool List(const wstring& dir, std::vector& out, DWORD& err); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +// The guard util.h's helpers go through (null: by path, as everywhere but in the elevated worker's jobs). +FsGuard* ActiveFsGuard(); +class ScopedFsGuard { +public: + explicit ScopedFsGuard(FsGuard* g); + ~ScopedFsGuard(); + ScopedFsGuard(const ScopedFsGuard&) = delete; + ScopedFsGuard& operator=(const ScopedFsGuard&) = delete; +private: + FsGuard* prev_; +}; + +// The converter library (wgc) opens its files by name. While a guard is active, a file it reads is first copied through +// the guard into the worker's private folder (ConverterFile), and a folder it writes into is a new folder there whose files +// are then copied through the guard into place (ConverterDir::Publish); so the converter itself only ever opens names in +// the private folder, which only administrators can write. Without a guard both are the paths themselves. +class ConverterFile { +public: + ConverterFile(const wstring& file, const wstring& privateDir); + ~ConverterFile(); + ConverterFile(const ConverterFile&) = delete; + ConverterFile& operator=(const ConverterFile&) = delete; + const wstring& path() const { return path_; } +private: + wstring path_, dir_; +}; +class ConverterDir { +public: + ConverterDir(const wstring& dir, const wstring& privateDir); + ~ConverterDir(); + ConverterDir(const ConverterDir&) = delete; + ConverterDir& operator=(const ConverterDir&) = delete; + const wstring& path() const { return path_; } // where the converter writes + void Publish(); // what it wrote, copied into the folder named (no guard: nothing to do) +private: + wstring dir_, path_; +}; + +// Whether a reparse point with this tag is a link (leads elsewhere), as the guard decides; the others only store a file +// differently (compression, files on demand, deduplication). +bool ReparseTagIsLink(DWORD tag); + +// `p` as an absolute path in its plain form (C:\a\b or \\server\share\a, no \\?\ prefix, no trailing separator except a +// drive's root), or empty when it is not one. +wstring NormalPath(const wstring& p); +// The path Windows reports for the open handle `h`, in NormalPath's form (empty when it cannot say). +wstring FinalPathOfHandle(HANDLE h); +// The launcher's side: the path of the existing folder or file `p` as the worker will find it (links and short names +// resolved by Windows, as the player reaches it); a part that does not exist yet is kept as named. Empty stays empty. +wstring BoundPath(const wstring& p); + +} // namespace wg diff --git a/clean/installer/src/wg_core/util.cpp b/clean/installer/src/wg_core/util.cpp index 0a20f887..f0bde52c 100644 --- a/clean/installer/src/wg_core/util.cpp +++ b/clean/installer/src/wg_core/util.cpp @@ -3,8 +3,16 @@ // this project. #include "util.h" +#include "secure_fs.h" + namespace wg { +// The elevated worker's guard (secure_fs.h): while one is active, every helper below acts through it. +#define WG_GUARD FsGuard* guard = ActiveFsGuard() +// The guard's call `op` (which sets its error argument), as a Win32 call: false with the last error set. (The error is read +// after the call: never as a second argument evaluated next to it.) +template static bool Done(Op op) { DWORD err = 0; const bool ok = op(err); if (!ok) SetLastError(err); return ok; } + [[noreturn]] void Fail(const wstring& m, int code) { throw SetupError{m + L" [WG-SETUP-" + std::to_wstring(code) + L"]", code}; } wstring Lower(wstring s) { for (auto& c : s) c = (wchar_t)towlower(c); return s; } @@ -30,10 +38,66 @@ wstring ShortenMiddle(const wstring& s, size_t max) { if (ts != wstring::npos && ts - from <= tail / 2) tail = s.size() - ts; // and "\Game\BattlEye" return s.substr(0, head) + L"\u2026" + s.substr(s.size() - tail); } -bool Exists(const wstring& p) { return GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES; } -bool IsDir(const wstring& p) { DWORD a = GetFileAttributesW(p.c_str()); return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); } -bool IsFile(const wstring& p) { DWORD a = GetFileAttributesW(p.c_str()); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); } +DWORD GetAttrs(const wstring& p) { + WG_GUARD; + if (!guard) return GetFileAttributesW(p.c_str()); + DWORD e = 0; + const DWORD a = guard->Attributes(p, nullptr, e); + if (a == INVALID_FILE_ATTRIBUTES) SetLastError(e); + return a; +} +bool SetAttrs(const wstring& p, DWORD attrs) { + WG_GUARD; + if (!guard) return SetFileAttributesW(p.c_str(), attrs) != FALSE; + return Done([&](DWORD& e) { return guard->SetAttributes(p, attrs, e); }); +} +bool DeletePath(const wstring& p) { + WG_GUARD; + if (!guard) return DeleteFileW(p.c_str()) != FALSE; + return Done([&](DWORD& e) { return guard->Unlink(p, e); }); +} +bool RemoveDirPath(const wstring& p) { + WG_GUARD; + if (!guard) return RemoveDirectoryW(p.c_str()) != FALSE; + return Done([&](DWORD& e) { return guard->RemoveDir(p, e); }); +} +bool MakeDir(const wstring& p) { + WG_GUARD; + if (!guard) return CreateDirectoryW(p.c_str(), nullptr) != FALSE; + return Done([&](DWORD& e) { return guard->CreateNewDir(p, nullptr, e); }); +} +bool MovePath(const wstring& from, const wstring& to, DWORD flags) { + WG_GUARD; + if (!guard) return MoveFileExW(from.c_str(), to.c_str(), flags | MOVEFILE_WRITE_THROUGH) != FALSE; + return Done([&](DWORD& e) { return guard->Move(from, to, (flags & MOVEFILE_REPLACE_EXISTING) != 0, (flags & MOVEFILE_COPY_ALLOWED) != 0, e); }); +} +bool CopyPath(const wstring& from, const wstring& to) { + WG_GUARD; + if (!guard) return CopyFileW(from.c_str(), to.c_str(), FALSE) != FALSE; + return Done([&](DWORD& e) { return guard->Copy(from, to, e); }); +} +HANDLE OpenForRead(const wstring& path, DWORD share) { + WG_GUARD; + if (!guard) return CreateFileW(path.c_str(), GENERIC_READ, share, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD e = 0; + const HANDLE h = guard->OpenRead(path, share, e); + if (h == INVALID_HANDLE_VALUE) SetLastError(e); + return h; +} +HANDLE CreateNewFile(const wstring& p) { + WG_GUARD; + if (!guard) return CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD e = 0; + const HANDLE h = guard->CreateNew(p, e); + if (h == INVALID_HANDLE_VALUE) SetLastError(e); + return h; +} +bool Exists(const wstring& p) { return GetAttrs(p) != INVALID_FILE_ATTRIBUTES; } +bool IsDir(const wstring& p) { DWORD a = GetAttrs(p); return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); } +bool IsFile(const wstring& p) { DWORD a = GetAttrs(p); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); } unsigned long long FileSize(const wstring& p) { + WG_GUARD; + if (guard) { DWORD e = 0; unsigned long long n = 0; return guard->Attributes(p, &n, e) == INVALID_FILE_ATTRIBUTES ? 0 : n; } WIN32_FILE_ATTRIBUTE_DATA d{}; if (!GetFileAttributesExW(p.c_str(), GetFileExInfoStandard, &d)) return 0; return ((unsigned long long)d.nFileSizeHigh << 32) | d.nFileSizeLow; @@ -68,7 +132,7 @@ wstring FromUtf8(const string& s) { bool ReadAll(const wstring& path, string& out) { // FILE_SHARE_DELETE: a read never stops another thread's move or delete of the file (the launcher's data check hashing // the model file while a conversion swaps it); the read goes on from the handle - HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h = OpenForRead(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE); if (h == INVALID_HANDLE_VALUE) return false; LARGE_INTEGER sz{}; GetFileSizeEx(h, &sz); @@ -106,6 +170,8 @@ bool FileContainsText(const wstring& path, const char* needle, unsigned long lon return ContainsText(f.data, f.size, needle); } void EnsureDir(const wstring& dir, std::vector* created) { + WG_GUARD; + if (guard) { if (!dir.empty()) guard->EnsureDir(dir, created); return; } if (dir.empty() || IsDir(dir)) return; if (dir.size() <= 3 && dir.size() >= 2 && dir[1] == L':') return; EnsureDir(Parent(dir), created); @@ -118,10 +184,12 @@ void EnsureDir(const wstring& dir, std::vector* created) { if (created) created->push_back(dir); } void ForceDelete(const wstring& p) { - SetFileAttributesW(p.c_str(), FILE_ATTRIBUTE_NORMAL); - if (!DeleteFileW(p.c_str()) && GetLastError() != ERROR_FILE_NOT_FOUND) Fail(L"Cannot delete " + p + L": " + ErrText(GetLastError())); + SetAttrs(p, FILE_ATTRIBUTE_NORMAL); + if (!DeletePath(p) && GetLastError() != ERROR_FILE_NOT_FOUND) Fail(L"Cannot delete " + p + L": " + ErrText(GetLastError())); } void WriteFileAtomic(const wstring& path, const void* data, size_t size) { + WG_GUARD; + if (guard) { guard->WriteAtomic(path, data, size); return; } wstring tmp = path + kTmpSuffix; HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) Fail(L"Cannot write " + path + L": " + ErrText(GetLastError())); @@ -145,10 +213,12 @@ void WriteFileAtomic(const wstring& path, const void* data, size_t size) { } void CopyChecked(const wstring& src, const wstring& dst) { EnsureDir(Parent(dst)); - if (Exists(dst)) SetFileAttributesW(dst.c_str(), FILE_ATTRIBUTE_NORMAL); - if (!CopyFileW(src.c_str(), dst.c_str(), FALSE)) Fail(L"Cannot copy " + src + L" to " + dst + L": " + ErrText(GetLastError())); + if (Exists(dst)) SetAttrs(dst, FILE_ATTRIBUTE_NORMAL); + if (!CopyPath(src, dst)) Fail(L"Cannot copy " + src + L" to " + dst + L": " + ErrText(GetLastError())); } void RemoveTree(const wstring& dir, const wstring& keepFile) { + WG_GUARD; + if (guard) { guard->RemoveTree(dir, keepFile); return; } // Check the root too: enumerating dir\* would otherwise follow a root junction into its target. const DWORD attrs = GetFileAttributesW(dir.c_str()); if (attrs == INVALID_FILE_ATTRIBUTES) return; @@ -172,9 +242,58 @@ void RemoveTree(const wstring& dir, const wstring& keepFile) { } RemoveDirectoryW(dir.c_str()); } +// A name against a wildcard pattern (* and ?, case-insensitive; "*.*" is every name), as the guard's listings use it. +static bool WildMatch(const wchar_t* p, const wchar_t* s) { + if (wcscmp(p, L"*.*") == 0) p = L"*"; + const wchar_t *star = nullptr, *mark = nullptr; + while (*s) { + if (*p == L'*') { star = p++; mark = s; continue; } + if (*p == L'?' || towlower(*p) == towlower(*s)) { ++p; ++s; continue; } + if (!star) return false; + p = star + 1; s = ++mark; + } + while (*p == L'*') ++p; + return !*p; +} +// The entries of `dir` through the guard (empty when it is not there). +static std::vector GuardList(FsGuard* guard, const wstring& dir) { + std::vector out; + DWORD e = 0; + guard->List(dir, out, e); + return out; +} +bool ListEntries(const wstring& dir, std::vector& out) { + WG_GUARD; + if (guard) { + std::vector es; + DWORD e = 0; + if (!guard->List(dir, es, e)) { SetLastError(e); return false; } + for (auto& en : es) out.push_back({en.name, en.attrs, en.size}); + return true; + } + WIN32_FIND_DATAW fd; + HANDLE h = FindFirstFileExW(Join(dir, L"*").c_str(), FindExInfoBasic, &fd, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH); + if (h == INVALID_HANDLE_VALUE) return false; + do { + const wstring n = fd.cFileName; + if (n == L"." || n == L"..") continue; + DWORD attrs = fd.dwFileAttributes; + if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) && !ReparseTagIsLink(fd.dwReserved0)) attrs &= ~FILE_ATTRIBUTE_REPARSE_POINT; // dwReserved0: the tag + out.push_back({n, attrs, ((unsigned long long)fd.nFileSizeHigh << 32) | fd.nFileSizeLow}); + } while (FindNextFileW(h, &fd)); + FindClose(h); + return true; +} // Files (not folders) in dir whose name matches the wildcard pattern. std::vector ListFiles(const wstring& dir, const wchar_t* pattern) { std::vector r; + WG_GUARD; + if (guard) { + for (auto& en : GuardList(guard, dir)) + if (!(en.attrs & FILE_ATTRIBUTE_DIRECTORY) && WildMatch(pattern, en.name.c_str())) r.push_back(Join(dir, en.name)); + std::sort(r.begin(), r.end(), [](const wstring& a, const wstring& b) { return Lower(a) < Lower(b); }); + return r; + } WIN32_FIND_DATAW fd; HANDLE h = FindFirstFileW(Join(dir, pattern).c_str(), &fd); if (h == INVALID_HANDLE_VALUE) return r; @@ -185,6 +304,13 @@ std::vector ListFiles(const wstring& dir, const wchar_t* pattern) { } std::vector ListDirs(const wstring& dir) { std::vector r; + WG_GUARD; + if (guard) { + for (auto& en : GuardList(guard, dir)) + if ((en.attrs & FILE_ATTRIBUTE_DIRECTORY) && !(en.attrs & FILE_ATTRIBUTE_REPARSE_POINT)) r.push_back(Join(dir, en.name)); + std::sort(r.begin(), r.end(), [](const wstring& a, const wstring& b) { return Lower(a) < Lower(b); }); + return r; + } WIN32_FIND_DATAW fd; HANDLE h = FindFirstFileW(Join(dir, L"*").c_str(), &fd); if (h == INVALID_HANDLE_VALUE) return r; @@ -202,7 +328,21 @@ std::vector FindFilesNamed(const wstring& root, const wchar_t* name, si std::vector out; std::vector> stack{{root, 0}}; size_t visited = 0; - while (!stack.empty() && visited < budget) { + WG_GUARD; + while (guard && !stack.empty() && visited < budget) { + // a search: a folder the guard refuses (a link on the way) is left out like a link below it + auto [dir, depth] = stack.back(); stack.pop_back(); + std::vector entries; + try { entries = GuardList(guard, dir); } catch (const SetupError&) { continue; } + for (auto& en : entries) { + ++visited; + if (en.attrs & FILE_ATTRIBUTE_DIRECTORY) { + if (depth < maxDepth && !(en.attrs & FILE_ATTRIBUTE_REPARSE_POINT) && !IEq(en.name, kStateDirName) && !IEq(en.name, kLegacyStateDir)) + stack.push_back({Join(dir, en.name), depth + 1}); + } else if (IEq(en.name, name)) out.push_back(Join(dir, en.name)); + } + } + while (!guard && !stack.empty() && visited < budget) { auto [dir, depth] = stack.back(); stack.pop_back(); WIN32_FIND_DATAW fd; HANDLE h = FindFirstFileW(Join(dir, L"*").c_str(), &fd); diff --git a/clean/installer/src/wg_core/util.h b/clean/installer/src/wg_core/util.h index e773f157..f120501f 100644 --- a/clean/installer/src/wg_core/util.h +++ b/clean/installer/src/wg_core/util.h @@ -8,12 +8,15 @@ namespace wg { struct SetupError { wstring msg; int code = EXIT_FAILED; }; +// CreateFileW(path, GENERIC_READ, share, OPEN_EXISTING), through the elevated worker's guard while one is active +// (secure_fs.h). INVALID_HANDLE_VALUE with the last error set. +HANDLE OpenForRead(const wstring& path, DWORD share); // Read-only view of a whole file (large files are scanned without copying them). struct MappedFile { HANDLE file = INVALID_HANDLE_VALUE, map = nullptr; const uint8_t* data = nullptr; size_t size = 0; explicit MappedFile(const wstring& path, unsigned long long limit = 1ull << 30) { - file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + file = OpenForRead(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE); if (file == INVALID_HANDLE_VALUE) return; LARGE_INTEGER sz{}; if (!GetFileSizeEx(file, &sz) || sz.QuadPart == 0 || (unsigned long long)sz.QuadPart > limit) return; @@ -56,6 +59,21 @@ void ForceDelete(const wstring& p); void WriteFileAtomic(const wstring& path, const void* data, size_t size); void CopyChecked(const wstring& src, const wstring& dst); void RemoveTree(const wstring& dir, const wstring& keepFile = L""); +// The modules' other path-based Win32 calls, through the elevated worker's guard while one is active (secure_fs.h; its +// refusals throw SetupError). Each returns what the Win32 call returns and sets the last error as it does. +DWORD GetAttrs(const wstring& p); // GetFileAttributesW +bool SetAttrs(const wstring& p, DWORD attrs); // SetFileAttributesW +bool DeletePath(const wstring& p); // DeleteFileW +bool RemoveDirPath(const wstring& p); // RemoveDirectoryW (an empty folder) +bool MakeDir(const wstring& p); // CreateDirectoryW(p, nullptr) +bool MovePath(const wstring& from, const wstring& to, DWORD flags); // MoveFileExW (MOVEFILE_REPLACE_EXISTING, _COPY_ALLOWED; written through) +bool CopyPath(const wstring& from, const wstring& to); // CopyFileW(from, to, FALSE) +HANDLE CreateNewFile(const wstring& p); // CreateFileW(GENERIC_WRITE, no sharing, CREATE_NEW) +// The entries of `dir` (no "." or ".."); false (last error set) when it cannot be listed. Links are marked +// FILE_ATTRIBUTE_REPARSE_POINT; reparse points that only store a file differently (secure_fs.h) are not. Through the +// elevated worker's guard while one is active. +struct DirEntry { wstring name; DWORD attrs; unsigned long long size; }; +bool ListEntries(const wstring& dir, std::vector& out); std::vector ListFiles(const wstring& dir, const wchar_t* pattern); std::vector ListDirs(const wstring& dir); std::vector FindFilesNamed(const wstring& root, const wchar_t* name, size_t budget = 60000, int maxDepth = 10); diff --git a/clean/installer/tests/elevated_worker.py b/clean/installer/tests/elevated_worker.py new file mode 100644 index 00000000..1858f0c9 --- /dev/null +++ b/clean/installer/tests/elevated_worker.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: MIT +"""The launcher's side of the elevated step, for the Python suites that run the worker directly (elevated_job.h). + +Written for this project; Python standard library only (ctypes, Windows). run_worker writes the job files and the batch +file, makes the reply pipe, runs "WrongGPU.exe apply --batch= --sha256= --pipe=" through the suite's +own run function and returns the worker's exit code and what it sent over the pipe. +""" +import ctypes +import ctypes.wintypes as wt +import hashlib +import os +import secrets +import struct +import threading + +_k32 = ctypes.WinDLL("kernel32", use_last_error=True) +_k32.CreateNamedPipeW.restype = wt.HANDLE +_k32.CreateNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, ctypes.c_void_p] +_k32.ConnectNamedPipe.argtypes = [wt.HANDLE, ctypes.c_void_p] +_k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.c_void_p] +_k32.CreateFileW.restype = wt.HANDLE +_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE] +_k32.CloseHandle.argtypes = [wt.HANDLE] +_INVALID = wt.HANDLE(-1).value +_ERROR_PIPE_CONNECTED, _ERROR_NO_DATA = 535, 232 + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def package_digest(path): + """The OptiScaler package's digest as the launcher puts it in a job (package_snapshot.h): the SHA-256 of a manifest of + each file's relative path and SHA-256; an archive is its one file, a folder (or the OptiScaler.dll in it) every file in + it and its subfolders, links left out, sorted by the lower-case relative path.""" + if os.path.isfile(path) and path.lower().endswith((".7z", ".zip")): + kind, root, files = "archive", os.path.dirname(path), [os.path.basename(path)] + else: + root = os.path.dirname(path) if os.path.isfile(path) else path + kind, files = "folder", [] + for d, dirs, names in os.walk(root): + dirs[:] = [n for n in dirs if not os.path.islink(os.path.join(d, n)) and not _is_junction(os.path.join(d, n))] + files += [os.path.relpath(os.path.join(d, n), root) for n in names if not os.path.islink(os.path.join(d, n))] + files.sort(key=lambda r: r.lower()) + manifest = "; WrongGPU OptiScaler package\r\nkind=%s\r\n" % kind + for rel in files: + with open(os.path.join(root, rel), "rb") as f: + manifest += "file=%s\r\nsha256=%s\r\n" % (rel, sha(f.read())) + return sha(manifest.encode("utf-8")) + + +def _is_junction(p): + try: + return os.path.isjunction(p) # Python 3.12 + except AttributeError: + return False + + +class Reply: + """What the worker sent: results {job number: result text}, refused (the refusal's text or None), log lines, complete.""" + + def __init__(self): + self.results, self.refused, self.log, self.complete = {}, None, [], False + + +def _parse(data): + rep, at = Reply(), 0 + while at + 9 <= len(data): + kind, n, size = struct.unpack_from(" exit code: the suite's own (WrongGPU.exe ...). job_texts: str or bytes, one per job, in order. + batch_sha: another --sha256 than the batch file's. change(batch, jobs): changes files after they were written. + Returns (exit code, Reply). The job and batch files are removed afterwards.""" + stamp = secrets.token_hex(4) + jobs = [os.path.join(folder, "job-%s-%d.txt" % (stamp, i + 1)) for i in range(len(job_texts))] + for path, text in zip(jobs, job_texts): + with open(path, "wb") as f: + f.write(text.encode("utf-8") if isinstance(text, str) else text) + batch = os.path.join(folder, "batch-%s.txt" % stamp) + listing = ("stop=1\r\n" if stop else "") + "".join("job=%s\r\nsha256=%s\r\n" % (j, sha(open(j, "rb").read())) for j in jobs) + with open(batch, "wb") as f: + f.write(listing.encode("utf-8")) + digest = batch_sha or sha(listing.encode("utf-8")) + if change: + change(batch, jobs) + name = "\\\\.\\pipe\\WrongGPU-reply-" + secrets.token_hex(16) + pipe = _k32.CreateNamedPipeW(name, 1, 0, 1, 65536, 65536, 0, None) # inbound, byte mode, one instance + if pipe == _INVALID: + raise OSError("CreateNamedPipeW failed (%d)" % ctypes.get_last_error()) + got = bytearray() + + def reader(): + if not _k32.ConnectNamedPipe(pipe, None) and ctypes.get_last_error() not in (_ERROR_PIPE_CONNECTED, _ERROR_NO_DATA): + return + buf, n = ctypes.create_string_buffer(65536), wt.DWORD() + while _k32.ReadFile(pipe, buf, len(buf), ctypes.byref(n), None) and n.value: + got.extend(buf.raw[:n.value]) + + th = threading.Thread(target=reader, daemon=True) + th.start() + try: + rc = run("apply", "--batch=" + batch, "--sha256=" + digest, "--pipe=" + name) + th.join(5) + if th.is_alive(): # the worker never connected: connect once ourselves so the reader returns + h = _k32.CreateFileW(name, 0x40000000, 0, None, 3, 0, None) + if h != _INVALID: + _k32.CloseHandle(h) + th.join(5) + finally: + _k32.CloseHandle(pipe) + for path in jobs + [batch]: + if os.path.exists(path): + os.remove(path) + return rc, _parse(bytes(got)) diff --git a/clean/installer/tests/launcher_core_tests.cpp b/clean/installer/tests/launcher_core_tests.cpp index 77d8d405..88b576c3 100644 --- a/clean/installer/tests/launcher_core_tests.cpp +++ b/clean/installer/tests/launcher_core_tests.cpp @@ -6,22 +6,28 @@ // it), the log-tail parser on synthetic logs, the job and result files, the update reply, the game environment, Ray // Reconstruction (its settings, the RR settings file round trip, which games use it, the RR log). // Written for this project. Run by ctest ("launcher-core"). +#include #include +#include #include #include +#include #include "app/ui_palette.h" #include "wg_core/detect.h" +#include "wg_core/elevated_job.h" #include "wg_core/gamerules.h" #include "wg_core/launcher.h" #include "wg_core/logs.h" #include "wg_core/logtail.h" #include "wg_core/optiedition.h" +#include "wg_core/package_snapshot.h" #include "wg_core/pe.h" #include "wg_core/profile.h" #include "wg_core/record.h" #include "wg_core/rr.h" #include "wg_core/rrconfig.h" +#include "wg_core/secure_fs.h" #include "wg_core/settings.h" using namespace wg; @@ -32,6 +38,7 @@ void require(bool ok, const char* what) { if (!ok) throw std::runtime_error(what); ++checks; } +void require(bool ok, const string& what) { require(ok, what.c_str()); } wstring TempFolder() { wchar_t tmp[MAX_PATH] = {}; GetTempPathW(MAX_PATH, tmp); @@ -41,6 +48,406 @@ wstring TempFolder() { return dir; } string OptionsOf(const string& ini) { string v, s; IniGetFrontEnd(ini, "runtime_options", &v, &s); return v; } + +// ---- the elevated step (elevated_job.h): the launcher's side and the worker, in this process, without elevation ---------- +void Put(const wstring& path, const string& text) { WriteFileAtomic(path, text.data(), text.size()); } +string Get(const wstring& path) { string s; ReadAll(path, s); return s; } +wstring Hash(const string& text) { return Sha256Bytes(text.data(), text.size()); } +size_t Entries(const wstring& dir) { return ListFiles(dir, L"*").size() + ListDirs(dir).size(); } +// One argument of the worker's command line (--batch="..." is quoted; the others end at a space). +wstring ArgOf(const wstring& args, const wstring& key) { + size_t p = args.find(key); + if (p == wstring::npos) return L""; + p += key.size(); + const size_t e = args.find_first_of(L"\" ", p); + return args.substr(p, e == wstring::npos ? wstring::npos : e - p); +} + +// ---- the elevated worker's file operations through held handles (secure_fs.h) --------------------------------------------- +// A junction `link` -> `target` (an existing folder), made here (no privilege needed); false when the volume refuses one. +bool MakeJunction(const wstring& link, const wstring& target) { + if (!CreateDirectoryW(link.c_str(), nullptr)) return false; + HANDLE h = CreateFileW(link.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + if (h == INVALID_HANDLE_VALUE) { RemoveDirectoryW(link.c_str()); return false; } + const wstring sub = L"\\??\\" + target, print = target; + const size_t names = (sub.size() + 1 + print.size() + 1) * sizeof(wchar_t), data = 8 + names; + std::vector b(8 + data, 0); + auto put16 = [&](size_t at, size_t v) { b[at] = (unsigned char)(v & 0xff); b[at + 1] = (unsigned char)(v >> 8); }; + const DWORD tag = IO_REPARSE_TAG_MOUNT_POINT; + memcpy(&b[0], &tag, 4); + put16(4, data); + put16(8, 0); put16(10, sub.size() * 2); put16(12, (sub.size() + 1) * 2); put16(14, print.size() * 2); + memcpy(&b[16], sub.c_str(), (sub.size() + 1) * 2); + memcpy(&b[16 + (sub.size() + 1) * 2], print.c_str(), (print.size() + 1) * 2); + DWORD got = 0; + const bool ok = DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, b.data(), (DWORD)b.size(), nullptr, 0, &got, nullptr) != FALSE; + CloseHandle(h); + if (!ok) RemoveDirectoryW(link.c_str()); + return ok; +} +// Whether `f` throws SetupError whose message has `says`. +bool Refused(const std::function& f, const wchar_t* says) { + try { f(); } catch (const SetupError& e) { return e.msg.find(says) != wstring::npos; } + return false; +} +// A drive letter no volume uses here, mapped onto `folder` for this logon session (DefineDosDevice); empty when none is free. +wstring MapDriveOnto(const wstring& folder) { + const DWORD used = GetLogicalDrives(); + for (wchar_t c = L'Z'; c >= L'K'; --c) { + if (used & (1u << (c - L'A'))) continue; + const wstring d = wstring(1, c) + L":"; + if (DefineDosDeviceW(0, d.c_str(), folder.c_str())) return d; + } + return L""; +} +// Looked at by path, past any guard (what really happened on disk). +bool IsFileUnguarded(const wstring& p) { const DWORD a = GetFileAttributesW(p.c_str()); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); } +string GetUnguarded(const wstring& p) { ScopedFsGuard none(nullptr); return Get(p); } +const wchar_t* const kLink = L"is a link"; +const wchar_t* const kElsewhere = L"is not where its path says"; +const wchar_t* const kOutside = L"outside the folders this job may change"; + +void GuardTests(const wstring& base) { + EnsureDir(base + L"-guard"); + const wstring t = BoundPath(base + L"-guard"); // the folder's own path (CI's temp folder has a short name in it) + const wstring game = Join(t, L"a\\b\\game"), evil = Join(t, L"evil\\b\\game"), outside = Join(t, L"outside"); + for (auto& d : {game, evil, outside}) EnsureDir(d); + Put(Join(game, L"game.exe"), "exe"); + { // the normal operations through the guard, inside its root + FsGuard g; + wstring why; + require(g.AddRoot(game, why), "guard: a folder without links is a root"); + ScopedFsGuard active(&g); + std::vector made; + EnsureDir(Join(game, L"sub\\deep"), &made); + Put(Join(game, L"sub\\deep\\x.txt"), "one"); + Put(Join(game, L"sub\\deep\\x.txt"), "two"); // replaced + require(made.size() == 2 && Get(Join(game, L"sub\\deep\\x.txt")) == "two" && IsDir(Join(game, L"sub")) && IsFile(Join(game, L"game.exe")) && + FileSize(Join(game, L"game.exe")) == 3, "guard: folders made, a file written and replaced, read back, its attributes and size"); + CopyChecked(Join(game, L"sub\\deep\\x.txt"), Join(game, L"copy.txt")); + require(MovePath(Join(game, L"copy.txt"), Join(game, L"moved.txt"), 0) && Get(Join(game, L"moved.txt")) == "two" && !Exists(Join(game, L"copy.txt")), + "guard: copied and renamed through handles"); + require(SetAttrs(Join(game, L"moved.txt"), FILE_ATTRIBUTE_READONLY) && (GetAttrs(Join(game, L"moved.txt")) & FILE_ATTRIBUTE_READONLY) && + !DeletePath(Join(game, L"moved.txt")), "guard: attributes set; a read-only file is not deleted (as DeleteFileW)"); + ForceDelete(Join(game, L"moved.txt")); + const std::vector files = ListFiles(game, L"*.exe"), dirs = ListDirs(game); + require(!Exists(Join(game, L"moved.txt")) && files.size() == 1 && dirs.size() == 1, "guard: deleted; folder listings"); + require(!RemoveDirPath(Join(game, L"sub")) && GetLastError() == ERROR_DIR_NOT_EMPTY && IsDir(Join(game, L"sub\\deep")), + "guard: a folder with files in it is not removed (ERROR_DIR_NOT_EMPTY, as RemoveDirectoryW)"); + RemoveTree(Join(game, L"sub")); + require(!Exists(Join(game, L"sub")), "guard: a folder tree removed through handles"); + require(Refused([&] { Put(Join(outside, L"x.txt"), "x"); }, kOutside) && !Exists(Join(outside, L"x.txt")), + "guard: nothing outside its roots is written (refused, with the path)"); + require(Refused([&] { Put(L"relative.txt", "x"); }, L"not an absolute path"), "guard: a relative path is refused"); + require(Refused([&] { RemoveTree(game); }, L"never removed"), "guard: a root itself is never removed"); + } + { // an ancestor of a held root cannot be swapped while the guard holds it; the files still go to the folder opened + FsGuard g; + wstring why; + require(g.AddRoot(game, why), "guard: root for the hold check"); + ScopedFsGuard active(&g); + const bool swapped = MoveFileW(Join(t, L"a").c_str(), Join(t, L"a-moved").c_str()) != FALSE; + if (swapped) MoveFileW(Join(t, L"a-moved").c_str(), Join(t, L"a").c_str()); + Put(Join(game, L"held.txt"), "held"); + require(!swapped && Get(Join(game, L"held.txt")) == "held" && !Exists(Join(evil, L"held.txt")), + "guard: an ancestor of a held root can't be renamed while it is held (the swap fails); the write lands in the folder opened"); + } + { // a junction swapped into an ancestor after validation (the path string unchanged): refused, nothing written there + require(MoveFileW(Join(t, L"a").c_str(), Join(t, L"a-real").c_str()) != FALSE, "guard test: the real ancestor moved aside"); + require(MakeJunction(Join(t, L"a"), Join(t, L"evil")), "guard test: a junction made where the ancestor was"); + FsGuard g; + wstring why; + require(!g.AddRoot(game, why) && why.find(kLink) != wstring::npos && why.find(Join(t, L"a")) != wstring::npos, + "guard: a junction swapped into a root's ancestor after validation is refused (it names the link)"); + FsGuard parent; + require(parent.AddRoot(t, why), "guard: the folder above is a root"); + ScopedFsGuard active(&parent); + require(Refused([&] { Put(Join(game, L"z.txt"), "z"); }, kLink) && !IsFileUnguarded(Join(evil, L"z.txt")), + "guard: a junction swapped in below a held root is refused at the next write; nothing reaches its target"); + require(Refused([&] { (void)Exists(Join(game, L"game.exe")); }, kLink), "guard: reading through it is refused too"); + RemoveDirectoryW(Join(t, L"a").c_str()); + MoveFileW(Join(t, L"a-real").c_str(), Join(t, L"a").c_str()); + } + { // a link at the leaf: a junction inside the root, used as a folder, a target, or removed + FsGuard g; + wstring why; + require(g.AddRoot(game, why), "guard: root for the leaf checks"); + const wstring link = Join(game, L"link"); + require(MakeJunction(link, outside), "guard test: a junction inside the root"); + ScopedFsGuard active(&g); + require(Refused([&] { (void)IsDir(link); }, kLink), "guard: a link as the leaf is refused (a query)"); + require(Refused([&] { Put(Join(link, L"f.txt"), "f"); }, kLink) && !IsFileUnguarded(Join(outside, L"f.txt")), "guard: a write through a leaf link is refused"); + require(Refused([&] { RemoveTree(link); }, kLink) && Refused([&] { RemoveDirPath(link); }, kLink), "guard: a leaf link is not removed"); + Put(Join(game, L"m.txt"), "m"); + require(Refused([&] { MovePath(Join(game, L"m.txt"), link, MOVEFILE_REPLACE_EXISTING); }, kLink), "guard: a rename onto a link is refused"); + require(ListDirs(game).size() == 0, "guard: a link is not listed as a folder"); + EnsureDir(Join(game, L"tree")); + require(MakeJunction(Join(game, L"tree\\inner"), outside), "guard test: a junction inside a folder to remove"); + { ScopedFsGuard none(nullptr); Put(Join(outside, L"keep.txt"), "keep"); } // (outside the root: written by the test itself) + RemoveTree(Join(game, L"tree")); + require(IsFileUnguarded(Join(outside, L"keep.txt")), "guard: removing a folder never follows a link in it"); + const wstring sym = Join(game, L"sym.txt"); + if (CreateSymbolicLinkW(sym.c_str(), Join(outside, L"keep.txt").c_str(), SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) { + require(Refused([&] { Put(sym, "over"); }, kLink) && Refused([&] { string s; ReadAll(sym, s); }, kLink) && + GetUnguarded(Join(outside, L"keep.txt")) == "keep", + "guard: a symbolic link to a file is neither written through nor read"); + } else { + std::printf("launcher-core: symbolic link not made here (error %lu): that check is skipped\n", GetLastError()); + } + } + { // a final path other than the path named: the same folder under a drive letter mapped onto it + const wstring drive = MapDriveOnto(t); + if (!drive.empty()) { + FsGuard g; + wstring why; + const wstring viaDrive = drive + L"\\a\\b\\game"; + require(!g.AddRoot(viaDrive, why) && why.find(kElsewhere) != wstring::npos && why.find(game) != wstring::npos, + "guard: a root whose final path is another (a mapped drive letter) is refused, with both paths"); + FsGuard reader; + ScopedFsGuard active(&reader); + require(Refused([&] { string s; ReadAll(viaDrive + L"\\game.exe", s); }, kElsewhere), "guard: a read whose final path is another is refused"); + DefineDosDeviceW(DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE, drive.c_str(), t.c_str()); + } else { + require(false, "guard test: no free drive letter for the final-path check"); + } + } + RemoveTree(t); +} + +void ElevatedJobTests(const wstring& base) { + RemoveTree(base + L"-elevated"); + EnsureDir(base + L"-elevated"); + // the folder's own path, as the launcher binds a job's paths (secure_fs.h BoundPath; CI's temp folder has a short name) + const wstring root = BoundPath(base + L"-elevated"), jobs = Join(root, L"jobs"), priv = Join(root, L"private"), pkg = Join(root, L"package"); + const wstring lad = Join(root, L"lad"); + for (auto& d : {jobs, priv, Join(pkg, L"sub"), lad, Join(root, L"game1"), Join(root, L"game2")}) EnsureDir(d); + Put(Join(Join(root, L"game2"), L"g.exe"), "exe"); + Put(Join(pkg, L"OptiScaler.dll"), "dll bytes"); + Put(Join(pkg, L"OptiScaler.ini"), "[Libraries]\r\nFfxDx12SRPath=auto\r\n"); + Put(Join(Join(pkg, L"sub"), L"extra.txt"), "extra"); + const wstring archive = Join(root, L"Opti.7z"); + Put(archive, "archive bytes"); + + Context ctx; + int runs = 0; + std::vector seen; + std::vector copied; // the package copy's OptiScaler.ini, as the run saw it + std::function during; // what a job does in the worker (through its guard), null: nothing + const WorkerRunFn run = [&](const WorkerJob& w) { + ++runs; seen.push_back(w); + if (during) during(w); + if (!w.r.optiPackage.empty()) copied.push_back(IsDir(w.r.optiPackage) ? Get(Join(w.r.optiPackage, L"OptiScaler.ini")) : Get(w.r.optiPackage)); + LogLine(ctx, L"job ran"); + OpResult r; r.message = L"ran"; return r; + }; + // the worker run here as the started process; `before` changes files after the launcher wrote them (null: nothing) + std::function before; + ProcessIdentity reported; // the identity the start reports (empty: this process) + bool startIt = true, runWorker = true; + const StartWorkerFn start = [&](const wstring& args, DWORD& code, ProcessIdentity& who) { + if (!startIt) return false; + if (before) before(ArgOf(args, L"--batch=")); + WorkerArgs wa; + wa.batch = ArgOf(args, L"--batch="); wa.sha256 = ArgOf(args, L"--sha256="); wa.pipe = ArgOf(args, L"--pipe="); + code = runWorker ? (DWORD)RunWorker(wa, ctx, run, priv).last.code : 0; + who = reported.pid ? reported : IdentityOf(GetCurrentProcess()); + return true; + }; + std::vector logged; + const LogFn log = [&](const wstring& s) { logged.push_back(s); }; + auto reset = [&] { runs = 0; seen.clear(); copied.clear(); logged.clear(); before = nullptr; during = nullptr; reported = ProcessIdentity(); startIt = runWorker = true; }; + OpRequest ap; ap.op = Op::Apply; ap.dir = Join(root, L"game1"); + OpRequest in; in.op = Op::Install; in.exe = Join(Join(root, L"game2"), L"g.exe"); in.optiPackage = pkg; + wstring why; + require(PackageDigest(pkg, in.optiDigest, why), "package digest of a folder"); + auto texts = [&](std::vector rs) { std::vector t; for (auto& r : rs) t.push_back(JobText(r, lad)); return t; }; + // a job file of the batch the worker was given + auto jobFile = [](const wstring& batch, size_t n) { + std::vector> listed; bool stop = false; + ParseBatch(Get(batch), listed, stop); + return n < listed.size() ? listed[n].first : wstring(); + }; + auto allRefused = [&](const std::vector& rs, const wchar_t* says) { + for (auto& r : rs) if (r.code != EXIT_USAGE || r.message.find(says) == wstring::npos) return false; + return runs == 0; + }; + + { // the normal flow: every job runs; the results and the log lines come back over the pipe; nothing stays in the jobs folder + reset(); + const std::vector rs = RunElevatedJobs(texts({ap, in}), jobs, true, start, log); + require(rs.size() == 2 && rs[0].code == 0 && rs[0].message == L"ran" && rs[1].code == 0 && runs == 2 && seen[0].r.dir == ap.dir && seen[0].localAppData == lad, + "elevated step: the launcher's jobs run in order and their results come back"); + require(std::find(logged.begin(), logged.end(), L"elevated step: job ran") != logged.end(), "elevated step: the worker's log lines reach the launcher's log"); + require(Entries(jobs) == 0, "elevated step: the jobs folder is empty afterwards (no result or log file)"); + require(seen[1].r.optiPackage != pkg && StartsWithI(seen[1].r.optiPackage, priv) && copied.size() == 1 && copied[0] == Get(Join(pkg, L"OptiScaler.ini")), + "elevated step: the install uses the worker's checked copy of the OptiScaler package"); + require(seen[0].r.optiPackage.empty(), "elevated step: an operation that takes no package gets none"); + require(Entries(priv) == 0, "elevated step: the worker's private folder is removed afterwards"); + } + { // an archive package + reset(); + OpRequest ar = in; ar.optiPackage = archive; + require(PackageDigest(archive, ar.optiDigest, why), "package digest of an archive"); + const std::vector rs = RunElevatedJobs(texts({ar}), jobs, false, start, log); + require(rs[0].code == 0 && runs == 1 && copied.size() == 1 && copied[0] == "archive bytes" && StartsWithI(seen[0].r.optiPackage, priv), + "elevated step: an archive package is installed from the worker's checked copy"); + } + // one job field changed after the launcher wrote the job: nothing runs + struct Field { const char* name; string from, to; }; + const std::vector fields = {{"operation", "op=install", "op=uninstall"}, + {"target", "exe=" + ToUtf8(in.exe), "exe=" + ToUtf8(Join(Join(root, L"other"), L"g.exe"))}, + {"package path", "opti=" + ToUtf8(pkg), "opti=" + ToUtf8(Join(root, L"other"))}, + {"package digest", "optisha256=" + ToUtf8(in.optiDigest), "optisha256=" + string(64, 'c')}}; + for (auto& f : fields) { + reset(); + before = [&](const wstring& batch) { + const wstring j = jobFile(batch, 1); + string t = Get(j); + const size_t at = t.find(f.from); + if (at != string::npos) t.replace(at, f.from.size(), f.to); + Put(j, t); + }; + const std::vector rs = RunElevatedJobs(texts({ap, in}), jobs, false, start, log); + require(allRefused(rs, L"SHA-256 mismatch"), string("elevated step: a job whose ") + f.name + " was changed is refused; no job runs"); + } + { // the package's content changed after the launcher took its digest: nothing runs + reset(); + before = [&](const wstring&) { Put(Join(pkg, L"OptiScaler.ini"), "[Libraries]\r\nFfxDx12SRPath=other\r\n"); }; + const std::vector rs = RunElevatedJobs(texts({ap, in}), jobs, false, start, log); + require(allRefused(rs, L"its files changed"), "elevated step: a package whose content changed is refused; no job runs"); + Put(Join(pkg, L"OptiScaler.ini"), "[Libraries]\r\nFfxDx12SRPath=auto\r\n"); + } + { // another folder at the package's path: nothing runs + reset(); + const wstring moved = Join(root, L"package-moved"); + before = [&](const wstring&) { + MoveFileW(pkg.c_str(), moved.c_str()); + EnsureDir(pkg); + Put(Join(pkg, L"OptiScaler.dll"), "other dll"); Put(Join(pkg, L"OptiScaler.ini"), "[Libraries]\r\nFfxDx12SRPath=auto\r\n"); + }; + const std::vector rs = RunElevatedJobs(texts({ap, in}), jobs, false, start, log); + require(allRefused(rs, L"its files changed"), "elevated step: another folder at the package's path is refused; no job runs"); + RemoveTree(pkg); MoveFileW(moved.c_str(), pkg.c_str()); + } + { // a package named without its digest: nothing runs + reset(); + OpRequest nd = in; nd.optiDigest.clear(); + require(allRefused(RunElevatedJobs(texts({ap, nd}), jobs, false, start, log), L"no digest"), "elevated step: a package without its digest is refused; no job runs"); + } + { // a bad second job: the first does not run either + reset(); + OpRequest bad = ap; bad.dir = L"relative\\folder"; + const std::vector rs = RunElevatedJobs(texts({ap, bad}), jobs, true, start, log); + require(allRefused(rs, L"not an absolute path"), "elevated step: a batch with a bad second job runs no job (the first is not run)"); + reset(); + before = [&](const wstring& batch) { Put(jobFile(batch, 1), Get(jobFile(batch, 1)) + "force=1\r\n"); }; + require(allRefused(RunElevatedJobs(texts({ap, ap}), jobs, true, start, log), L"SHA-256 mismatch"), + "elevated step: a batch whose second job file was changed runs no job (the first is not run)"); + reset(); + before = [&](const wstring& batch) { Put(batch, Get(batch) + "stop=1\r\n"); }; + require(allRefused(RunElevatedJobs(texts({ap}), jobs, false, start, log), L"SHA-256 mismatch"), "elevated step: a changed batch file runs no job"); + } + { // results only from this run's pipe: result files on disk are never read + reset(); + runWorker = false; + for (int i = 1; i <= 3; ++i) Put(Join(jobs, L"result-" + std::to_wstring(i) + L".txt"), "code=0\r\nmessage=done\r\n"); + const std::vector rs = RunElevatedJobs(texts({ap, ap}), jobs, false, start, log); + require(rs[0].code == EXIT_FAILED && rs[1].code == EXIT_FAILED && rs[0].message.find(L"did not report") != wstring::npos && runs == 0, + "elevated step: result files on disk are ignored; a job not reported on the pipe is a failure that says so"); + for (int i = 1; i <= 3; ++i) DeleteFileW(Join(jobs, L"result-" + std::to_wstring(i) + L".txt").c_str()); + } + { // a reply from a process other than the one started is not taken + reset(); + reported.pid = GetCurrentProcessId() + 4; reported.started = 1; + const std::vector rs = RunElevatedJobs(texts({ap}), jobs, false, start, log); + require(rs[0].code == EXIT_FAILED && rs[0].message.find(L"did not report") != wstring::npos, "elevated step: only the started process's reply is taken"); + } + { // permission not given: nothing runs, the launcher says so + reset(); + startIt = false; + const std::vector rs = RunElevatedJobs(texts({ap, ap}), jobs, false, start, log); + require(rs[0].code == EXIT_REFUSED && rs[1].message == kElevationNotGranted && runs == 0 && Entries(jobs) == 0, "elevated step: permission not given: nothing runs"); + } + { // the worker without a reply pipe: nothing runs and nothing is written + reset(); + const string jt = JobText(ap, lad); + Put(Join(jobs, L"job-p-1.txt"), jt); + const string bt = BatchText({{Join(jobs, L"job-p-1.txt"), Hash(jt)}}, false); + Put(Join(jobs, L"batch-p.txt"), bt); + const wstring other = Join(root, L"other.txt"); + for (const wstring& pipe : {wstring(), wstring(L"\\\\.\\pipe\\WrongGPU-reply-") + wstring(32, L'0'), other, wstring(L"\\\\.\\pipe\\something-else")}) { + const WorkerRun wr = RunWorker({Join(jobs, L"batch-p.txt"), Hash(bt), pipe}, ctx, run, priv); + require(wr.refused && runs == 0 && wr.last.code == EXIT_USAGE && !Exists(other) && Entries(priv) == 0, + "elevated step: the worker without the launcher's reply pipe runs nothing and writes nothing"); + } + require(!ctx.logSink && ctx.workRoot.empty(), "elevated step: the worker leaves the log and the temporary folder as they were"); + DeleteFileW(Join(jobs, L"job-p-1.txt").c_str()); DeleteFileW(Join(jobs, L"batch-p.txt").c_str()); + } + // ---- the job's folders held and opened without following links (secure_fs.h) ---- + { // a junction swapped into an ancestor of a job's game folder after the launcher wrote the job: no job runs + reset(); + const wstring lib = Join(root, L"lib"), real = Join(root, L"lib-real"), evilLib = Join(root, L"evil-lib"); + EnsureDir(Join(lib, L"g3")); + EnsureDir(Join(evilLib, L"g3")); + OpRequest a3 = ap; a3.dir = Join(lib, L"g3"); + bool swapped = false; + before = [&](const wstring&) { swapped = MoveFileW(lib.c_str(), real.c_str()) && MakeJunction(lib, evilLib); }; + const std::vector rs = RunElevatedJobs(texts({ap, a3}), jobs, false, start, log); + require(swapped && allRefused(rs, kLink) && rs[1].message.find(lib) != wstring::npos && Entries(Join(evilLib, L"g3")) == 0, + "elevated step: a junction swapped into a job folder's ancestor after the request is refused, naming it; no job runs"); + RemoveDirectoryW(lib.c_str()); + MoveFileW(real.c_str(), lib.c_str()); + } + { // a job folder that is itself a junction: no job runs + reset(); + const wstring link = Join(root, L"game-link"); + require(MakeJunction(link, Join(root, L"game1")), "elevated step test: a junction to a game folder"); + OpRequest l = ap; l.dir = link; + require(allRefused(RunElevatedJobs(texts({l}), jobs, false, start, log), kLink), "elevated step: a job folder that is a link is refused; no job runs"); + RemoveDirectoryW(link.c_str()); + } + { // a job folder whose final path is another (the same folder under a drive letter mapped onto the one above): no job runs + reset(); + const wstring drive = MapDriveOnto(root); + require(!drive.empty(), "elevated step test: a free drive letter"); + OpRequest viaDrive = ap; viaDrive.dir = drive + L"\\game1"; + require(allRefused(RunElevatedJobs(texts({viaDrive}), jobs, false, start, log), kElsewhere), + "elevated step: a job folder whose final path is not its path is refused; no job runs"); + DefineDosDeviceW(DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE, drive.c_str(), root.c_str()); + } + { // while a job runs: its folders are held (the game folder can't be renamed), it writes into them, nothing outside them + reset(); + bool renamed = true, outsideRefused = false; + during = [&](const WorkerJob& w) { + renamed = MoveFileW(w.r.dir.c_str(), (w.r.dir + L"-moved").c_str()) != FALSE; + if (renamed) MoveFileW((w.r.dir + L"-moved").c_str(), w.r.dir.c_str()); + Put(Join(w.r.dir, L"written.txt"), "w"); + outsideRefused = Refused([&] { Put(Join(root, L"elsewhere.txt"), "x"); }, kOutside); + }; + const std::vector rs = RunElevatedJobs(texts({ap}), jobs, false, start, log); + require(rs[0].code == 0 && !renamed && GetUnguarded(Join(ap.dir, L"written.txt")) == "w" && outsideRefused && !IsFileUnguarded(Join(root, L"elsewhere.txt")), + "elevated step: a running job's folder is held (not renamed), its writes land there, a write outside its folders is refused"); + reset(); + during = [&](const WorkerJob&) { Put(Join(root, L"elsewhere.txt"), "x"); }; + const std::vector out = RunElevatedJobs(texts({ap}), jobs, false, start, log); + require(out[0].code == EXIT_REFUSED && out[0].message.find(kOutside) != wstring::npos && !IsFileUnguarded(Join(root, L"elsewhere.txt")), + "elevated step: a job that writes outside its folders fails with the refusal as its result"); + } + { // the package digest: the same for the same files, another when a file changes; a private folder is new every time + wstring d1, d2, d3; + require(PackageDigest(pkg, d1, why) && PackageDigest(Join(pkg, L"OptiScaler.dll"), d2, why) && d1 == d2 && d1 == in.optiDigest, + "package digest: a folder and the OptiScaler.dll in it give the same digest, the same every time"); + Put(Join(Join(pkg, L"sub"), L"extra.txt"), "changed"); + require(PackageDigest(pkg, d3, why) && d3 != d1, "package digest: changes with any file of the package"); + require(!PackageDigest(Join(root, L"none.zip"), d3, why), "package digest: a missing package has none"); + wstring a, b; + require(MakePrivateFolder(priv, a, why) && MakePrivateFolder(priv, b, why) && a != b && IsDir(a) && IsDir(b), "private folder: a new one every time"); + RemoveDirectoryW(a.c_str()); RemoveDirectoryW(b.c_str()); + require(IsReplyPipeName(L"\\\\.\\pipe\\WrongGPU-reply-" + RandomHex()) && !IsReplyPipeName(L"C:\\x") && !IsReplyPipeName(L"\\\\.\\pipe\\WrongGPU-reply-XYZ"), + "reply pipe names: only the launcher's form"); + } + RemoveTree(root); +} } // namespace int main() { @@ -461,26 +868,44 @@ int main() { // ---- job and result files ----------------------------------------------------------------------------------------- OpRequest job; job.op = Op::Update; job.exe = L"C:\\Games\\X\\x.exe"; job.dir = L"C:\\Games\\X"; job.optiPackage = L"C:\\dl\\Opti.7z"; job.moveMods = true; job.hasProfile = true; job.profile = DefaultProfile(); SetSetting(job.profile, "executor", "hip", nullptr); - const string jt = JobText(job, L"C:\\Users\\p\\AppData\\Local", L"C:\\log.txt"); - OpRequest back; wstring lad, lf; - require(ParseJob(jt, back, lad, lf, &why) && back.op == Op::Update && back.exe == job.exe && back.dir == job.dir && back.moveMods && !back.removeOld && - back.hasProfile && back.profile.get("executor") == "hip" && lad == L"C:\\Users\\p\\AppData\\Local" && lf == L"C:\\log.txt", "job file round trip"); + job.optiDigest = wstring(64, L'b'); + const string jt = JobText(job, L"C:\\Users\\p\\AppData\\Local"); + OpRequest back; wstring lad; + require(ParseJob(jt, back, lad, &why) && back.op == Op::Update && back.exe == job.exe && back.dir == job.dir && back.moveMods && !back.removeOld && + back.hasProfile && back.profile.get("executor") == "hip" && lad == L"C:\\Users\\p\\AppData\\Local" && back.optiPackage == job.optiPackage && + back.optiDigest == job.optiDigest, "job file round trip (the OptiScaler package and its digest included)"); { // the player's account and whether a new install gets its own entry: carried to the worker (another account may run it) wstring sid; int per = 7; - require(ParseJob(JobText(job, L"C:\\Users\\p\\AppData\\Local", L"", L"S-1-5-21-1-2-3-1001", 0), back, lad, lf, &why, &sid, &per) && sid == L"S-1-5-21-1-2-3-1001" && per == 0 && - ParseJob(jt, back, lad, lf, &why, &sid, &per) && sid.empty() && per == -1, "job file: usersid and perentry round trip (absent: empty, -1)"); + require(ParseJob(JobText(job, L"C:\\Users\\p\\AppData\\Local", L"S-1-5-21-1-2-3-1001", 0), back, lad, &why, &sid, &per) && sid == L"S-1-5-21-1-2-3-1001" && per == 0 && + ParseJob(jt, back, lad, &why, &sid, &per) && sid.empty() && per == -1, "job file: usersid and perentry round trip (absent: empty, -1)"); OpRequest d; d.op = Op::Detach; d.dir = L"C:\\Games\\X"; - require(ParseJob(JobText(d, L"C:\\x", L""), back, lad, lf, &why) && back.op == Op::Detach, "job file: the detach operation (the launcher's uninstall, games kept)"); + require(ParseJob(JobText(d, L"C:\\x"), back, lad, &why) && back.op == Op::Detach, "job file: the detach operation (the launcher's uninstall, games kept)"); OpRequest o; o.op = Op::Apply; o.dir = job.dir; o.optiKeep = o.optiOnly = true; - require(ParseJob(JobText(o, lad, L""), back, lad, lf, &why) && back.optiKeep && back.optiOnly && !back.hasProfile && - ParseJob(jt, back, lad, lf, &why) && !back.optiOnly, "job file: an OptiScaler-only apply round trip (absent: the profile is applied too)"); + require(ParseJob(JobText(o, lad), back, lad, &why) && back.optiKeep && back.optiOnly && !back.hasProfile && + ParseJob(jt, back, lad, &why) && !back.optiOnly, "job file: an OptiScaler-only apply round trip (absent: the profile is applied too)"); } - require(!ParseJob("op=install\r\nexe=relative\\x.exe\r\nlocalappdata=C:\\x\r\n", back, lad, lf, &why), "a job with a relative path is refused"); - require(!ParseJob("op=format\r\nlocalappdata=C:\\x\r\n", back, lad, lf, &why) && !ParseJob("exe=C:\\x.exe\r\n", back, lad, lf, &why), "unknown or missing operation refused"); - require(!ParseJob("op=apply\r\ndir=C:\\g\r\nlocalappdata=C:\\x\r\nprofile.executor=warp\r\n", back, lad, lf, &why), "a job with a bad setting is refused"); + require(!ParseJob("op=install\r\nexe=relative\\x.exe\r\nlocalappdata=C:\\x\r\n", back, lad, &why), "a job with a relative path is refused"); + for (const char* field : {"exe", "dir", "opti", "model", "localappdata", "documents"}) + for (const char* path : {"relative\\x", "\\\\?\\C:\\x", "\\\\.\\C:", "\\x", "C:x"}) + require(!ParseJob(string("op=install\r\nlocalappdata=C:\\x\r\n") + field + "=" + path + "\r\n", back, lad, &why), + string("a job whose ") + field + " path is not a plain absolute path is refused (" + path + ")"); + require(ParseJob("op=install\r\nexe=\\\\server\\share\\x.exe\r\nopti=C:/dl/o.7z\r\nmodel=C:\\m\\x.dll\r\nlocalappdata=C:\\x\r\n", back, lad, &why), + "job paths: drive and \\\\server\\share paths are accepted"); + require(!ParseJob("op=format\r\nlocalappdata=C:\\x\r\n", back, lad, &why) && !ParseJob("exe=C:\\x.exe\r\n", back, lad, &why), "unknown or missing operation refused"); + require(!ParseJob("op=apply\r\ndir=C:\\g\r\nlocalappdata=C:\\x\r\nprofile.executor=warp\r\n", back, lad, &why), "a job with a bad setting is refused"); OpResult res; res.code = 6; res.message = L"switch?"; res.warnings = {L"w1"}; res.notes = {L"n1", L"n2"}; OpResult rb; require(ParseResult(ResultText(res), rb) && rb.code == 6 && rb.message == L"switch?" && rb.warnings.size() == 1 && rb.notes.size() == 2, "result file round trip"); + { // the batch file: job= / sha256= pairs; result= lines and a job without its SHA-256 are refused + std::vector> bj; bool stop = false; + const wstring h(64, L'a'); + require(ParseBatch(BatchText({{L"C:\\j\\job-1.txt", h}, {L"C:\\j\\job-2.txt", h}}, true), bj, stop) && bj.size() == 2 && stop && bj[1].second == h, + "batch file round trip (job and its SHA-256)"); + require(!ParseBatch("job=C:\\j\\job-1.txt\r\nresult=C:\\x.txt\r\n", bj, stop) && !ParseBatch("job=C:\\j\\job-1.txt\r\n", bj, stop) && + !ParseBatch("job=C:\\j\\job-1.txt\r\nsha256=abc\r\n", bj, stop), "batch file: result=, a missing or short SHA-256: refused"); + } + GuardTests(TempFolder()); + ElevatedJobTests(TempFolder()); // ---- update reply ----------------------------------------------------------------------------------------------- wstring ver, page; diff --git a/clean/installer/tests/run_coexist_tests.py b/clean/installer/tests/run_coexist_tests.py index 75f8323e..8afc8911 100644 --- a/clean/installer/tests/run_coexist_tests.py +++ b/clean/installer/tests/run_coexist_tests.py @@ -27,6 +27,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import coexist_fixtures as fx # noqa: E402 +import elevated_worker as ew # noqa: E402 (the elevated worker run directly: job files, batch, reply pipe) import run_installer_tests as suite # noqa: E402 import run_launcher_tests as lt # noqa: E402 from run_installer_tests import diff, read, sha, snapshot, write # noqa: E402 @@ -377,10 +378,8 @@ def test_opti_tab(t, full): t.check("update: the OptiScaler tab's values carried over to the new ini, the journal kept", rc == 0 and b"ShortcutKey = 0x2E" in now and b"EnableXeSSInputs=false" in now and b"DxgiFactoryWrapping=true" in now and sum(1 for l in rec_lines(b) if l.startswith("inikey\t")) == 3, (rc, t.j.get("message"), now[-400:])) # the elevated worker's job carries OptiScaler edits too - job, result = os.path.join(t.work, "job-opti.txt"), os.path.join(t.work, "result-opti.txt") - write(job, "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\noptikey.Menu.FpsOverlayType=2\r\n" % (b, t.env["LOCALAPPDATA"])) - rc = t.run("apply", "--job=" + job, "--result=" + result) - t.check("apply --job: optikey lines applied", rc == 0 and b"FpsOverlayType=2" in read(os.path.join(b, "OptiScaler.ini")), (rc, read(result) if os.path.isfile(result) else "")) + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=%s\r\nlocalappdata=%s\r\noptikey.Menu.FpsOverlayType=2\r\n" % (b, t.env["LOCALAPPDATA"])]) + t.check("apply (the elevated worker): optikey lines applied", rc == 0 and b"FpsOverlayType=2" in read(os.path.join(b, "OptiScaler.ini")), (rc, vars(rep))) rc = t.run("opti", exe, "--reset") t.check("--reset: the editable keys back byte for byte to what the install wrote", rc == 0 and read(os.path.join(b, "OptiScaler.ini")) == installed and not any(l.startswith("inikey\t") and "\tMenu\tShowFps\t" not in l for l in rec_lines(b)), (rc, t.j.get("message"))) diff --git a/clean/installer/tests/run_launcher_tests.py b/clean/installer/tests/run_launcher_tests.py index 235175f8..3b1ae785 100644 --- a/clean/installer/tests/run_launcher_tests.py +++ b/clean/installer/tests/run_launcher_tests.py @@ -24,8 +24,10 @@ sys.path.insert(0, HERE) import mockpe # noqa: E402 (synthetic PE files with a version resource) import run_installer_tests as suite # noqa: E402 (mock content, snapshots, the synthetic model case) +import elevated_worker as ew # noqa: E402 (the elevated worker run directly: job files, batch, reply pipe) from run_installer_tests import read, sha, snapshot, diff, write # noqa: E402 + OPTI_INI = ("[Upscalers]\nDx12Upscaler=auto\n[Libraries]\nFfxDx12SRPath=auto\n[FSR]\nFsr4Update=auto\nUpscalerIndex=auto\n" "[Menu]\nShortcutKey=auto\nShowFps=auto\n") @@ -43,6 +45,9 @@ def __init__(self, exe, work, model, hip): for k in [k for k in self.env if k.upper().startswith("WG_") or k.upper() in ("HIP_PATH", "ROCM_PATH", "LLVM_PATH", "HIP_DEVICE_LIB_PATH")]: self.env.pop(k) os.makedirs(self.env["LOCALAPPDATA"], exist_ok=True) + # the elevated worker's private folder (its checked package copy, its temporary files) in the work folder + self.env["WRONGGPU_TEST_PRIVATE_DIR"] = os.path.join(work, "worker-private") + os.makedirs(self.env["WRONGGPU_TEST_PRIVATE_DIR"], exist_ok=True) self.uninstall = suite.uninstall_root(self.env["LOCALAPPDATA"]) # this run's Apps & features root (the build's own) self.j = {} @@ -413,41 +418,61 @@ def test_install_settings_uninstall(t, opti): rc = t.run("repair", exe, "--opti=" + opti, "--noscan", "--force") t.check("repair of an older version: wronggpu.ini back with the settings, the message says it updated from 0.5.1", rc == 0 and "output_filter=quality9" in (options_line(ini(b)) or "") and "updated from 0.5.1 to" in t.j.get("message", ""), (rc, t.j.get("message"))) - # the elevated worker's job (run here without elevation: the same code path) - job = os.path.join(t.work, "job.txt") - result = os.path.join(t.work, "result.txt") - write(job, "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=analytic\r\nprofile.fps_overlay=off\r\n" % (b, t.env["LOCALAPPDATA"])) - rc = t.run("apply", "--job=" + job, "--result=" + result) - res = read(result).decode("utf-8", "replace") if os.path.isfile(result) else "" - t.check("apply --job: the worker writes the result; the job's settings are in the files", rc == 0 and "code=0" in res and - "output_filter=analytic" in (options_line(ini(b)) or "") and "ShowFps=false" in ini(b, "OptiScaler.ini"), (rc, res)) - write(job, "op=apply\r\ndir=relative\\folder\r\nlocalappdata=%s\r\n" % t.env["LOCALAPPDATA"]) - rc = t.run("apply", "--job=" + job, "--result=" + result) - t.check("apply --job with a relative path: refused (exit 10)", rc == 10 and "code=10" in read(result).decode(), rc) - # several jobs in one worker run (the window's one permission prompt for every protected folder): each writes its result, in order + # the elevated worker (run here without elevation: the same code path): the batch's SHA-256 on the command line, each + # job's in the batch; its results and log lines come back over the reply pipe, and it writes no file of its own lad = t.env["LOCALAPPDATA"] - jobs = [os.path.join(t.work, "batch-job-%d.txt" % i) for i in (1, 2)] - results = [os.path.join(t.work, "batch-result-%d.txt" % i) for i in (1, 2)] - batch = os.path.join(t.work, "batch.txt") - for f in results: - if os.path.exists(f): - os.remove(f) - write(jobs[0], "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=quality5\r\n" % (b, lad)) - write(jobs[1], "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=analytic\r\nprofile.fps_overlay=off\r\n" % (b, lad)) - write(batch, "stop=1\r\n" + "".join("job=%s\r\nresult=%s\r\n" % (j, r) for j, r in zip(jobs, results))) - rc = t.run("apply", "--batch=" + batch) - res = [read(f).decode("utf-8", "replace") if os.path.isfile(f) else "" for f in results] - t.check("apply --batch: both jobs run in order, each writes its result (the last one's settings are in the files)", - rc == 0 and all("code=0" in r for r in res) and t.j.get("ran") == 2 and "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, res, t.j)) - for f in results: - if os.path.exists(f): - os.remove(f) - write(jobs[0], "op=apply\r\ndir=relative\\folder\r\nlocalappdata=%s\r\n" % lad) - write(jobs[1], "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=quality5\r\n" % (b, lad)) - rc = t.run("apply", "--batch=" + batch) - res = [read(f).decode("utf-8", "replace") if os.path.isfile(f) else "" for f in results] - t.check("apply --batch with stop=1: the first fails (exit 10), the second is not run and its result says so (code -1, the files unchanged)", - rc == 10 and "code=10" in res[0] and "code=-1" in res[1] and t.j.get("ran") == 1 and "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, res, t.j)) + + def work_files(): # the work folder without the suite's own JSON output (t.run deletes it before each run) + return sorted(n for n in os.listdir(t.work) if n != os.path.basename(t.out)) + + before_work = work_files() + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=analytic\r\nprofile.fps_overlay=off\r\n" % (b, lad)]) + t.check("apply: the worker's result comes back over the pipe; the job's settings are in the files", rc == 0 and "code=0" in rep.results.get(1, "") and + rep.complete and "output_filter=analytic" in (options_line(ini(b)) or "") and "ShowFps=false" in ini(b, "OptiScaler.ini"), (rc, vars(rep))) + t.check("apply: the worker's log lines come back over the pipe; it writes no file next to the jobs", + any("elevated worker: apply" in line for line in rep.log) and work_files() == before_work, (rep.log[:5], work_files())) + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=relative\\folder\r\nlocalappdata=%s\r\n" % lad]) + t.check("apply with a relative path: refused (exit 10), the refusal comes back", rc == 10 and rep.refused and "code=10" in rep.refused and not rep.results, (rc, vars(rep))) + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=%s\r\nlocalappdata=%s\r\n" % (b, lad)], batch_sha="0" * 64) + t.check("apply with another SHA-256: refused (exit 10), nothing run", rc == 10 and rep.refused and "SHA-256 mismatch" in rep.refused and not rep.results, (rc, vars(rep))) + rc = t.run("apply", "--batch=" + os.path.join(t.work, "batch-none.txt"), "--sha256=" + "0" * 64) + t.check("apply without the reply pipe: refused (exit 10), nothing written", rc == 10 and work_files() == before_work, (rc, work_files())) + # several jobs in one worker run (the window's one permission prompt for every protected folder): a result each, in order + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=quality5\r\n" % (b, lad), + "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=analytic\r\nprofile.fps_overlay=off\r\n" % (b, lad)], stop=True) + t.check("apply, two jobs: both run in order, a result each (the last one's settings are in the files)", + rc == 0 and all("code=0" in rep.results.get(n, "") for n in (1, 2)) and "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, vars(rep))) + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=relative\\folder\r\nlocalappdata=%s\r\n" % lad, + "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=quality5\r\n" % (b, lad)], stop=True) + t.check("apply, two jobs, the first one bad: the batch is refused (exit 10) and neither runs (the files unchanged)", + rc == 10 and rep.refused and not rep.results and "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, vars(rep))) + missing = os.path.join(t.work, "not-installed") + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=%s\r\nlocalappdata=%s\r\n" % (missing, lad), + "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\nprofile.output_filter=quality5\r\n" % (b, lad)], stop=True) + t.check("apply, two jobs with stop=1: the first fails when it runs, the second is not run and its result says so (code -1, the files unchanged)", + rc != 0 and not rep.refused and "code=0" not in rep.results.get(1, "code=0") and "code=-1" in rep.results.get(2, "") and + "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, vars(rep))) + # the OptiScaler package of a repair through the worker: its digest in the job; the worker installs from its own + # checked copy and leaves no copy behind; a package changed after the digest was taken is refused, nothing run + private = t.env["WRONGGPU_TEST_PRIVATE_DIR"] + repair = "op=repair\r\nexe=%s\r\nopti=%s\r\noptisha256=%s\r\nlocalappdata=%s\r\nforce=1\r\nnoscan=1\r\n" + rc, rep = ew.run_worker(t.run, t.work, [repair % (exe, opti, ew.package_digest(opti), lad)]) + t.check("repair through the worker: the package is checked and installed from the worker's copy, none left behind", + rc == 0 and "code=0" in rep.results.get(1, "") and any("OptiScaler package" in line and "checked" in line for line in rep.log) and + read(os.path.join(b, "OptiScaler.ini")) is not None and os.listdir(private) == [], (rc, vars(rep), os.listdir(private))) + digest = ew.package_digest(opti) + ini_before = read(os.path.join(b, "wronggpu.ini")) + + def change_package(batch, jobs): + write(os.path.join(opti, "OptiScaler.dll"), b"MZ another OptiScaler (synthetic)") + + rc, rep = ew.run_worker(t.run, t.work, [repair % (exe, opti, digest, lad)], change=change_package) + t.check("repair through the worker, the package changed after its digest was taken: refused (exit 10), nothing run", + rc == 10 and rep.refused and "changed" in rep.refused and not rep.results and read(os.path.join(b, "wronggpu.ini")) == ini_before and + os.listdir(private) == [], (rc, vars(rep))) + write(os.path.join(opti, "OptiScaler.dll"), b"MZ mock OptiScaler (synthetic)") + rc, rep = ew.run_worker(t.run, t.work, [repair % (exe, opti, "", lad)]) + t.check("repair through the worker without the package's digest: refused (exit 10)", rc == 10 and rep.refused and not rep.results, (rc, vars(rep))) # collect logs zpath = os.path.join(t.work, "support.zip") rc = t.run("collect", exe, "--zip=" + zpath) @@ -2032,7 +2057,7 @@ def rr_data_ready(): t.check("...Fix it for me: the elevated worker saves the choice at once (one permission prompt, its apply job), on in the profile, nothing in " "Engine.ini or the record, the card waits for the first start (r6 #7)", ff.get("busy_started") is True and ff.get("done") is True and ff.get("saved") == "on" and ff.get("state") == -1 and - ff.get("notice") == "" and len(asks()) == 1 and "apply" in asks()[0] and "--job=" in asks()[0] and get_fix(exe)[1].get("profile") == "on" and + ff.get("notice") == "" and len(asks()) == 1 and "apply" in asks()[0] and "--batch=" in asks()[0] and "--pipe=" in asks()[0] and get_fix(exe)[1].get("profile") == "on" and not os.listdir(docs) and "rrconfig\t" not in record_text(b), (ff, asks(), os.listdir(docs))) write(bl4_gus, b"[ScalabilityGroups]\r\n") # the game's first start rx, pg, rcf = rr_page("protected-fixforme-then", prot_env, extra=("--apply=rrdue",)) @@ -2155,7 +2180,7 @@ def set_no_docs(*kv): gd.get("fix_button") == "Fix Engine.ini now", gd) rec = record_text(b) t.check("...Fix it now, the player's click: one permission prompt (the elevated worker's job), the line added (45-byte file, read-only), recorded, the toast says so (r2c)", - fx.get("done") is True and fx.get("asks") == 1 and len(asks()) == 1 and "apply" in asks()[0] and "--job=" in asks()[0] and + fx.get("done") is True and fx.get("asks") == 1 and len(asks()) == 1 and "apply" in asks()[0] and "--batch=" in asks()[0] and "--pipe=" in asks()[0] and fx.get("state") == 1 and fx.get("fixed") is True and "has the Ray Reconstruction setting now" in fx.get("toast", "") and read(bl4_ini) == new_file and read_only(bl4_ini) and re.search(r"(?m)^rrconfig\t" + re.escape(bl4_ini) + r"\tcr\tabsent\t-\r?$", rec) is not None, @@ -2526,12 +2551,10 @@ def set_no_docs(*kv): t.run("install", exe, "--opti=" + opti, "--noscan", "--force", "--experimental") job_cfg = os.path.join(docs2, "My Games", "Borderlands 4", "Saved", "Config", "Windows") write(os.path.join(job_cfg, "GameUserSettings.ini"), b"[ScalabilityGroups]\r\n") # the game's settings folder there - job, res = os.path.join(t.work, "job-rrconfig.txt"), os.path.join(t.work, "result-rrconfig.txt") - write(job, "op=apply\r\ndir=%s\r\nlocalappdata=%s\r\ndocuments=%s\r\nprofile.rr_config_fix=on\r\n" % (b, t.env["LOCALAPPDATA"], docs2)) - rc = t.run("apply", "--job=" + job, "--result=" + res) + rc, rep = ew.run_worker(t.run, t.work, ["op=apply\r\ndir=%s\r\nlocalappdata=%s\r\ndocuments=%s\r\nprofile.rr_config_fix=on\r\n" % (b, t.env["LOCALAPPDATA"], docs2)]) job_ini = os.path.join(docs2, "My Games", "Borderlands 4", "Saved", "Config", "Windows", "Engine.ini") t.check("elevated job with documents=: Engine.ini in the job's Documents folder, none in this process's", rc == 0 and os.path.isfile(job_ini) and - read(job_ini) == new_file and not os.listdir(docs), (rc, read(res) if os.path.exists(res) else b"", os.listdir(docs))) + read(job_ini) == new_file and not os.listdir(docs), (rc, vars(rep), os.listdir(docs))) rc = t.run("uninstall", exe) t.check("...and the uninstall takes it out there (the record's path)", rc == 0 and os.listdir(job_cfg) == ["GameUserSettings.ini"], (rc, os.listdir(job_cfg))) # 10. a test build without a Documents test root refuses (never this PC's Documents)