Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(windows): install and run Linger as administrator
VecSzn99bc01628e1b
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex 91390600..648d1d22 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -348,7 +348,10 @@ sandbox may hold that right on a parent, such as AppData. The sandbox actsthrough the `CodexSandboxUsers` group and the capability SIDs in`%USERPROFILE%\.codex\cap_sid`. A sandboxed Codex command can therefore replacesuch a parent; Linger accepts this so it installs beside Codex. Private paths-themselves still grant access only to the current user and SYSTEM.+themselves still grant access only to the current user and SYSTEM. Their+owner is the current user or, when that user is an administrator,+Administrators, which owns what an elevated process (Run as administrator,+the built-in Administrator) creates.Process recovery uses the creation time and a held process handle, so a reusedprocess ID is never mistaken for the original. Ordinary tasks are held by a Jobdiff --git a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.goindex 93d44c04..a46715d0 100644--- a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go+++ b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows.go@@ -153,13 +153,44 @@ func validateHandle(file *os.File, kind string, ownerOnly bool) error {return validateDescriptor(sd, ownerOnly)}+// privateOwner reports whether owner may own the current user's private path:+// the user, or BUILTIN\Administrators when the user is an administrator. That+// group owns what an elevated process creates (Run as administrator, the+// built-in Administrator). It is already trusted on every ancestor and in+// private ACLs, and an administrator can take ownership of any file, so+// accepting it trusts no other account. Git for Windows decides ownership the+// same way.+func privateOwner(owner, user *windows.SID) bool {+ return owner != nil && (windows.EqualSid(owner, user) ||+ owner.IsWellKnown(windows.WinBuiltinAdministratorsSid) && currentUserIsAdministrator())+}++// currentUserIsAdministrator reports whether this process's token, or the+// elevated token UAC links to it, has Administrators enabled.+var currentUserIsAdministrator = func() bool {+ administrators, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)+ if err != nil {+ return false+ }+ if member, err := windows.Token(0).IsMember(administrators); err == nil && member {+ return true+ }+ linked, err := windows.GetCurrentProcessToken().GetLinkedToken()+ if err != nil {+ return false+ }+ defer linked.Close()+ member, err := linked.IsMember(administrators)+ return err == nil && member+}+func validateDescriptor(sd *windows.SECURITY_DESCRIPTOR, ownerOnly bool) error {user, err := CurrentSID()if err != nil {return err}owner, _, err := sd.Owner()- if err != nil || owner == nil || !windows.EqualSid(owner, user) {+ if err != nil || !privateOwner(owner, user) {return errors.New("private path is not owned by the current user")}dacl, _, err := sd.DACL()@@ -350,7 +381,7 @@ func EnsureDir(path string) error {}owner, _, err := sd.Owner()current, currentErr := CurrentSID()- if err != nil || currentErr != nil || owner == nil || !windows.EqualSid(owner, current) {+ if err != nil || currentErr != nil || !privateOwner(owner, current) {return errors.New("private directory belongs to another user")}desired, err := SecurityDescriptor()@@ -410,7 +441,7 @@ func protectFile(path string) error {}owner, _, err := sd.Owner()current, currentErr := CurrentSID()- if err != nil || currentErr != nil || owner == nil || !windows.EqualSid(owner, current) {+ if err != nil || currentErr != nil || !privateOwner(owner, current) {return errors.New("private file belongs to another user")}desired, err := SecurityDescriptor()diff --git a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.goindex 1bd2de92..df006248 100644--- a/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go+++ b/apps/computer/local-daemon/internal/platform/privatefs/privatefs_windows_test.go@@ -43,6 +43,38 @@ func TestWindowsAncestorDeleteRightsRespectVolumeRoot(t *testing.T) {}}+func TestWindowsPrivateOwnerIsUserOrAdministrators(t *testing.T) {+ sid, err := CurrentSID()+ if err != nil {+ t.Fatal(err)+ }+ original := currentUserIsAdministrator+ t.Cleanup(func() { currentUserIsAdministrator = original })+ for _, test := range []struct {+ name string+ owner string+ administrator bool+ allowed bool+ }{+ {"current user", sid.String(), false, true},+ {"Administrators, for an administrator", "BA", true, true},+ {"Administrators, for a standard user", "BA", false, false},+ {"another account, for an administrator", "S-1-5-21-1-2-3-4", true, false},+ } {+ t.Run(test.name, func(t *testing.T) {+ currentUserIsAdministrator = func() bool { return test.administrator }+ sd, err := windows.SecurityDescriptorFromString("O:" + test.owner + "D:P(A;;FA;;;" + sid.String() + ")(A;;FA;;;SY)")+ if err != nil {+ t.Fatal(err)+ }+ err = validateDescriptor(sd, true)+ if (err == nil) != test.allowed {+ t.Fatalf("allowed = %v, error = %v", test.allowed, err)+ }+ })+ }+}+func TestWindowsAncestorTrustsOnlyCodexSandboxSIDs(t *testing.T) {sid, err := CurrentSID()if err != nil {diff --git a/docs/desktop-release.md b/docs/desktop-release.mdindex 1ce23fd7..1b559f0e 100644--- a/docs/desktop-release.md+++ b/docs/desktop-release.md@@ -474,8 +474,10 @@ Windows, Linux x64 and Apple silicon bundle PostgreSQL in the app insteadelsewhere), so Native works without the CDN. Put the pinned archives in`LINGER_NATIVE_POSTGRES_DIR` before `node build.mjs`; the build fails withoutthem. To download it instead, replace `file` with the HTTPS `url` once it is on-the CDN. Native PostgreSQL refuses an elevated Linger ("Run as-administrator"), as it refuses root elsewhere.+the CDN. `postgres.exe` refuses a token with Administrators enabled, so an+elevated Linger ("Run as administrator", the built-in Administrator) starts it+from a copy of its token with that group disabled, as `pg_ctl` does. Native+PostgreSQL still refuses root elsewhere.Every target also bundles the voice tools (`voiceTools`, about 40 MB each):the official LiveKit server release (Apple silicon: built from the taggeddiff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex be3c1fde..771b8ac5 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -109,6 +109,18 @@ never leaves a directory that later attempts treat as initialized. A `postgres-d`PG_VERSION` but no `postmaster.opts` (which only a started server writes)never served a connection, holds no data, and is initialized again.+On Windows `postgres.exe` refuses a token with Administrators enabled. When+the installer runs elevated (Run as administrator, the built-in+Administrator), its supervisor starts `postgres` through a fixed PowerShell+program (`windows-restricted-token.ts`) from a copy of its own token with+Administrators and Power Users disabled, as `pg_ctl` does; `initdb` already+does this itself. `postgres` stays the supervisor's descendant, so its lease+tree, log and stop work as before. What an elevated process creates is owned+by Administrators; `windowsPrivatePath` accepts that owner as well as the+user when the user is an administrator (Administrators enabled in the token+or in the elevated token UAC links to it, as Git for Windows decides), since+the ancestor check already trusts that group. A standard user is refused.+On Windows the installer stages UTF-8 application manifests beside the bundledPostgreSQL tools before recording their file hashes. This lets `initdb`relaunch itself and start `postgres` when the profile path contains charactersdiff --git a/packages/local-installation/src/native-database.test.ts b/packages/local-installation/src/native-database.test.tsindex 70ab9f74..e9b53e56 100644--- a/packages/local-installation/src/native-database.test.ts+++ b/packages/local-installation/src/native-database.test.ts@@ -132,20 +132,25 @@ describe("prepareNativeDatabase on Windows", () => {]);expect(vi.mocked(startNativeProcess).mock.calls[0]![0]).toMatchObject({executable: path.join(options.postgresBin, "postgres.exe"),+ withoutAdministrators: false,});expect(vi.mocked(inspectNativeProcess)).toHaveBeenCalled();});- it("stops before initdb when Linger runs as administrator", async () => {+ it("starts postgres with Administrators disabled when Linger runs as administrator", async () => {asWindows();- run.mockResolvedValue(- ok('"Mandatory Label\\High Mandatory Level","Label","S-1-16-12288",""'),- );- await expect(prepareNativeDatabase(options)).rejects.toThrow(- /cannot run as administrator/,+ run.mockImplementation(async (command) =>+ command.endsWith("whoami.exe")+ ? ok(+ '"Mandatory Label\\High Mandatory Level","Label","S-1-16-12288",""',+ )+ : ok(),);- expect(run).toHaveBeenCalledTimes(1);- expect(startNativeProcess).not.toHaveBeenCalled();+ await prepareNativeDatabase(options);+ expect(vi.mocked(startNativeProcess).mock.calls[0]![0]).toMatchObject({+ executable: path.join(options.postgresBin, "postgres.exe"),+ withoutAdministrators: true,+ });});});diff --git a/packages/local-installation/src/native-database.ts b/packages/local-installation/src/native-database.tsindex b106742d..9164f013 100644--- a/packages/local-installation/src/native-database.ts+++ b/packages/local-installation/src/native-database.ts@@ -27,8 +27,10 @@ export function postgresProgram(}// postgres.exe refuses to run with an elevated token ("Run as administrator",-// or an administrator account with UAC off). Elevated tokens carry the High-// (or System) mandatory label, which `whoami` names by SID in every language.+// the built-in Administrator, or an administrator account with UAC off), so+// such a token starts it with Administrators disabled, as pg_ctl does.+// Elevated tokens carry the High (or System) mandatory label, which `whoami`+// names by SID in every language.export async function windowsElevated(run: typeof runProcess = runProcess,): Promise<boolean> {@@ -61,10 +63,8 @@ export async function prepareNativeDatabase(options: {throw new Error("Native PostgreSQL must run as a normal user; run Linger without sudo.",);- if (process.platform === "win32" && (await windowsElevated()))- throw new Error(- "Native PostgreSQL cannot run as administrator; start Linger normally, not with Run as administrator.",- );+ const withoutAdministrators =+ process.platform === "win32" && (await windowsElevated());if (!instance.source || instance.mode !== "source-native")throw new Error("Native database needs a native source instance");const port = instance.source.ports.postgres;@@ -171,6 +171,7 @@ export async function prepareNativeDatabase(options: {env,signal,redactions: [password],+ withoutAdministrators,});const connection = ["--host",diff --git a/packages/local-installation/src/native-process-worker.mjs b/packages/local-installation/src/native-process-worker.mjsindex ebd3b1f4..3f126941 100644--- a/packages/local-installation/src/native-process-worker.mjs+++ b/packages/local-installation/src/native-process-worker.mjs@@ -2,8 +2,13 @@import { spawn } from "node:child_process";import { constants, closeSync, writeSync } from "node:fs";import { open, rm } from "node:fs/promises";+import path from "node:path";import { lineRedactor } from "./redaction.ts";import { nativeLeaseProcesses } from "./native-process-identity.ts";+import {+ WITHOUT_ADMINISTRATORS_SCRIPT,+ windowsCommandLine,+} from "./windows-restricted-token.ts";const file = process.argv[2];// Windows reports neither owner nor mode bits; the native directory ACL,@@ -33,7 +38,8 @@ try {!job.env ||job.env.LINGER_NATIVE_PROCESS_LEASE !==process.env.LINGER_NATIVE_PROCESS_LEASE ||- !Array.isArray(job.redactions)+ !Array.isArray(job.redactions) ||+ ![undefined, true].includes(job.withoutAdministrators))throw new Error("Invalid native job");output = await open(@@ -68,14 +74,39 @@ try {// Stay group leader after the service exits: descendants may still be alive.process.on("SIGINT", () => {});process.on("SIGTERM", () => {});- const child = spawn(job.executable, job.args, {- cwd: job.cwd,- env: job.env,- // This detached supervisor has no console, so on Windows the service- // would open a visible one that air, PowerShell and go then share.- windowsHide: true,- stdio: ["ignore", "pipe", "pipe"],- });+ const restricted = job.withoutAdministrators && process.platform === "win32";+ const child = restricted+ ? spawn(+ path.win32.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ ),+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ Buffer.from(WITHOUT_ADMINISTRATORS_SCRIPT, "utf16le").toString(+ "base64",+ ),+ ],+ { cwd: job.cwd, env: job.env, windowsHide: true },+ )+ : spawn(job.executable, job.args, {+ cwd: job.cwd,+ env: job.env,+ // This detached supervisor has no console, so on Windows the service+ // would open a visible one that air, PowerShell and go then share.+ windowsHide: true,+ stdio: ["ignore", "pipe", "pipe"],+ });+ if (restricted)+ child.stdin.end(+ JSON.stringify(windowsCommandLine(job.executable, job.args)),+ );child.stdout.setEncoding("utf8");child.stderr.setEncoding("utf8");child.stdout.on("data", (chunk) => streams[0].write(chunk));diff --git a/packages/local-installation/src/native-process.test.ts b/packages/local-installation/src/native-process.test.tsindex aa38cfc1..5c928860 100644--- a/packages/local-installation/src/native-process.test.ts+++ b/packages/local-installation/src/native-process.test.ts@@ -35,6 +35,7 @@ import {const windows = process.platform === "win32";const test = windows ? base : base.concurrent;const posix = windows ? test.skip : test;+const win32 = windows ? test : test.skip;vi.setConfig({testTimeout: windows ? 60_000 : 30_000,hookTimeout: 60_000,@@ -103,6 +104,41 @@ test("retains an owned service after launch and reuses its identity", async (conawait readFile(path.join(root, "native/logs/web.log"), "utf8"),).toContain("native fixture ready");});+win32(+ "starts a service from a token with Administrators disabled",+ async (context) => {+ const { expect } = context;+ const root = await fixture(context);+ const args = ["a b", "", 'say "hi"', "C:\\dir with space\\", "trailing\\"];+ // The service reports the arguments it received and whether its token+ // holds Administrators; an elevated test run proves the group is gone.+ const report = [+ "const ps=require('node:path').win32.join(process.env.SystemRoot,'System32','WindowsPowerShell','v1.0','powershell.exe');",+ "const role='([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)';",+ "const administrator=require('node:child_process').execFileSync(ps,['-NoProfile','-NonInteractive','-Command',role],{encoding:'utf8'}).trim();",+ "console.log(JSON.stringify({args:process.argv.slice(1),administrator}));",+ "setInterval(()=>{},1000);",+ ].join("");+ await startNativeProcess({+ root,+ name: "web",+ executable: process.execPath,+ args: ["-e", report, ...args],+ cwd: root,+ env: process.env,+ withoutAdministrators: true,+ });+ await expect+ .poll(+ async () => readFile(path.join(root, "native/logs/web.log"), "utf8"),+ { timeout: 45_000 },+ )+ .toContain(JSON.stringify({ args, administrator: "False" }));+ expect((await inspectNativeProcess(root, "web")).running).toBe(true);+ await stopNativeProcess(root, "web");+ expect((await inspectNativeProcess(root, "web")).running).toBe(false);+ },+);test("refuses to signal a PID whose recorded lease differs", async (context) => {const { expect } = context;const root = await fixture(context);diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.tsindex 8e63a850..f63bd1a6 100644--- a/packages/local-installation/src/native-process.ts+++ b/packages/local-installation/src/native-process.ts@@ -252,6 +252,12 @@ export async function startNativeProcess(signal?: AbortSignal;redactions?: string[];restartOnConfigurationChange?: boolean;+ /**+ * Windows: start the service from a copy of the supervisor's token with+ * Administrators disabled. The same service either way, so this is not+ * part of the configuration.+ */+ withoutAdministrators?: boolean;},): Promise<NativeProcessState> {options.signal?.throwIfAborted();@@ -307,6 +313,7 @@ export async function startNativeProcess(args: options.args,cwd: options.cwd,env: { ...options.env, [leaseKey]: lease },+ ...(options.withoutAdministrators ? { withoutAdministrators: true } : {}),log: location.log,redactions: [...new Set(diff --git a/packages/local-installation/src/windows-private.native.test.ts b/packages/local-installation/src/windows-private.native.test.tsindex c17b7477..81ae8e16 100644--- a/packages/local-installation/src/windows-private.native.test.ts+++ b/packages/local-installation/src/windows-private.native.test.ts@@ -2,8 +2,15 @@ import { afterEach, expect, it, vi } from "vitest";import { mkdir, mkdtemp, rm, writeFile, symlink } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";-import { windowsPrivatePath } from "./windows-private.js";+import {+ WINDOWS_PRIVATE_SCRIPT,+ windowsPrivatePath,+} from "./windows-private.js";import { runProcess } from "./process.js";+import {+ WITHOUT_ADMINISTRATORS_SCRIPT,+ windowsCommandLine,+} from "./windows-restricted-token.js";const roots: string[] = [];afterEach(async () => {for (const root of roots.splice(0))@@ -55,6 +62,87 @@ it.skipIf(process.platform !== "win32")(}},);+it.skipIf(process.platform !== "win32")(+ "accepts private paths that Administrators own, as an elevated Linger creates them",+ async (context) => {+ const root = await fixture();+ const file = path.join(root, "manager.sqlite");+ await writeFile(file, "");+ const script =+ "$ErrorActionPreference='Stop'; [Console]::InputEncoding=[Text.UTF8Encoding]::new($false); $p=[Console]::In.ReadToEnd(); foreach ($path in @($p, [IO.Path]::GetDirectoryName($p))) { $a=Get-Acl -LiteralPath $path; $a.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')); Set-Acl -LiteralPath $path -AclObject $a }";+ const changed = await runProcess(+ path.win32.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ ),+ [+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ Buffer.from(script, "utf16le").toString("base64"),+ ],+ { input: file, timeoutMs: 30000 },+ );+ // Only an elevated process may hand a file to Administrators.+ if (changed.code !== 0) return context.skip();+ await expect(windowsPrivatePath(file, "file")).resolves.toBeUndefined();+ await expect(+ windowsPrivatePath(root, "directory", true),+ ).resolves.toBeUndefined();+ // A token with Administrators disabled and no elevated token linked to+ // it, like a standard user's, does not accept that owner.+ const powershell = path.win32.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ );+ const encoded = (text: string) =>+ Buffer.from(text, "utf16le").toString("base64");+ const program = path.join(root, "check.ps1");+ const request = path.join(root, "request.json");+ const output = path.join(root, "output.txt");+ await writeFile(program, WINDOWS_PRIVATE_SCRIPT);+ await writeFile(+ request,+ JSON.stringify({ path: file, kind: "file", repair: false }),+ );+ // The program reads its request from a real stdin, as windowsPrivatePath+ // sends it; a PowerShell pipe into powershell.exe would send CLIXML.+ const check = [+ `$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((Get-Content -Raw -LiteralPath '${program}')))`,+ `$p = Start-Process -FilePath '${powershell}' -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand',$encoded -RedirectStandardInput '${request}' -RedirectStandardOutput '${output}' -NoNewWindow -Wait -PassThru`,+ `[Console]::Out.Write((Get-Content -Raw -LiteralPath '${output}'))`,+ "exit $p.ExitCode",+ ].join("; ");+ const restricted = await runProcess(+ powershell,+ [+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ encoded(WITHOUT_ADMINISTRATORS_SCRIPT),+ ],+ {+ input: JSON.stringify(+ windowsCommandLine(powershell, [+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ encoded(check),+ ]),+ ),+ timeoutMs: 60000,+ },+ );+ expect(restricted.code).toBe(1);+ expect(restricted.stdout.trim()).toBe("UNSAFE_OWNER");+ },+);it.skipIf(process.platform !== "win32")("rejects a junction as either the target or an ancestor",async () => {diff --git a/packages/local-installation/src/windows-private.ts b/packages/local-installation/src/windows-private.tsindex ffe2029a..7158932d 100644--- a/packages/local-installation/src/windows-private.ts+++ b/packages/local-installation/src/windows-private.ts@@ -9,6 +9,39 @@ $ErrorActionPreference = 'Stop'# A caller's PowerShell 7 modules can prevent Get-Acl from loading.$env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules')[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)+# Administrators enabled in this token, or in the elevated token UAC links to+# it (an administrator running without elevation). Only the rare second case+# compiles the check.+function Test-Administrator {+ if ([Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { return $true }+ Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;+public static class LingerLinkedToken {+ [DllImport("advapi32.dll")] static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);+ [DllImport("advapi32.dll")] static extern bool GetTokenInformation(IntPtr token, int infoClass, out IntPtr info, int length, out int returned);+ [DllImport("advapi32.dll")] static extern bool CheckTokenMembership(IntPtr token, byte[] sid, out bool member);+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);+ public static bool IsAdministrator(byte[] administrators) {+ IntPtr token, linked;+ int returned;+ bool member;+ if (!OpenProcessToken(GetCurrentProcess(), 0x0008, out token)) return false;+ bool found = GetTokenInformation(token, 19, out linked, IntPtr.Size, out returned);+ CloseHandle(token);+ if (!found) return false;+ bool checkedMember = CheckTokenMembership(linked, administrators, out member);+ CloseHandle(linked);+ return checkedMember && member;+ }+}+'@+ $administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')+ $binary = [byte[]]::new($administrators.BinaryLength)+ $administrators.GetBinaryForm($binary, 0)+ return [LingerLinkedToken]::IsAdministrator($binary)+}try {$request = [Console]::In.ReadToEnd() | ConvertFrom-Json$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User@@ -16,7 +49,13 @@ try {$item = Get-Item -LiteralPath $request.path -Forceif (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item.PSIsContainer -ne ($request.kind -eq 'directory'))) { throw 'UNSAFE_TYPE' }$acl = Get-Acl -LiteralPath $item.FullName- if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'UNSAFE_OWNER' }+ # What an elevated process (Run as administrator, the built-in+ # Administrator) creates is owned by Administrators. For an administrator+ # that owner counts as the user, as in Git for Windows: the ancestor check+ # below already lets the group own and replace every parent folder, and an+ # administrator can take ownership of any file, so it trusts no one new.+ $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value+ if ($owner -ne $sid.Value -and !($owner -eq $admins -and (Test-Administrator))) { throw 'UNSAFE_OWNER' }$parent = $item.Directoryif ($item.PSIsContainer) { $parent = $item.Parent }while ($parent) {@@ -111,8 +150,7 @@ export const WINDOWS_PRIVATE_PATH_UNSAFE = "WINDOWS_PRIVATE_PATH_UNSAFE";// The ACL program's reason codes, worded for the error message.const WINDOWS_PRIVATE_REASONS = {UNSAFE_TYPE: "is a link, or not the expected file or folder",- UNSAFE_OWNER:- "is owned by another account, such as Administrators after Linger ran as administrator",+ UNSAFE_OWNER: "is owned by another account",UNSAFE_PARENT_LINK: "is inside a linked folder",UNSAFE_PARENT_OWNER: "is inside a folder another account owns",UNSAFE_PARENT_ACCESS: "is inside a folder other accounts may change",diff --git a/packages/local-installation/src/windows-restricted-token.test.ts b/packages/local-installation/src/windows-restricted-token.test.tsnew file mode 100644index 00000000..fae80daf--- /dev/null+++ b/packages/local-installation/src/windows-restricted-token.test.ts@@ -0,0 +1,19 @@+import { expect, it } from "vitest";+import { windowsCommandLine } from "./windows-restricted-token.js";++it("quotes only the arguments the C runtime would split or lose", () => {+ expect(+ windowsCommandLine("C:\\pg\\bin\\postgres.exe", ["-p", "15432", "-k", ""]),+ ).toBe('C:\\pg\\bin\\postgres.exe -p 15432 -k ""');+ expect(+ windowsCommandLine("C:\\Program Files\\pg\\postgres.exe", [+ "-D",+ "C:\\Users\\Nora\\Nouveau dossier é\\data\\",+ 'say "hi"',+ 'a\\"b',+ "trailing\\",+ ]),+ ).toBe(+ '"C:\\Program Files\\pg\\postgres.exe" -D "C:\\Users\\Nora\\Nouveau dossier é\\data\\\\" "say \\"hi\\"" "a\\\\\\"b" trailing\\',+ );+});diff --git a/packages/local-installation/src/windows-restricted-token.ts b/packages/local-installation/src/windows-restricted-token.tsnew file mode 100644index 00000000..1076d2c0--- /dev/null+++ b/packages/local-installation/src/windows-restricted-token.ts@@ -0,0 +1,135 @@+// postgres.exe refuses a token in which Administrators is enabled. pg_ctl and+// initdb start it from a restricted copy of their own token with that group+// (and Power Users) disabled; this fixed program does the same for a service+// the supervisor runs, so the service stays its child and keeps its pipes.+// The command line arrives on stdin, never in argv.+export const WITHOUT_ADMINISTRATORS_SCRIPT = String.raw`+$ErrorActionPreference = 'Stop'+# Progress records would reach the service log as CLIXML.+$ProgressPreference = 'SilentlyContinue'+try {+ # A caller's PowerShell 7 modules can prevent Add-Type from loading.+ $env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules')+ [Console]::InputEncoding = [Text.UTF8Encoding]::new($false)+ $command = [string]([Console]::In.ReadToEnd() | ConvertFrom-Json)+ Add-Type -TypeDefinition @'+using System;+using System.ComponentModel;+using System.Runtime.InteropServices;+using System.Security.AccessControl;+using System.Security.Principal;+using System.Text;++public static class LingerWithoutAdministrators {+ [StructLayout(LayoutKind.Sequential)]+ struct SidAndAttributes { public IntPtr Sid; public uint Attributes; }+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ struct StartupInfo {+ public int cb; public string lpReserved; public string lpDesktop; public string lpTitle;+ public int dwX; public int dwY; public int dwXSize; public int dwYSize;+ public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags;+ public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2;+ public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError;+ }+ [StructLayout(LayoutKind.Sequential)]+ struct ProcessInformation { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; }++ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool CreateRestrictedToken(IntPtr token, uint flags, uint disableCount, SidAndAttributes[] disable,+ uint deleteCount, IntPtr delete, uint restrictCount, IntPtr restrict, out IntPtr restricted);+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool SetTokenInformation(IntPtr token, int infoClass, ref IntPtr info, int length);+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool CreateProcessAsUserW(IntPtr token, string application, StringBuilder commandLine,+ IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, uint flags, IntPtr environment,+ string directory, ref StartupInfo startup, out ProcessInformation process);+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();+ [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int which);+ [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);+ [DllImport("kernel32.dll")] static extern bool GetExitCodeProcess(IntPtr process, out int code);+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);++ static byte[] Binary(SecurityIdentifier sid) {+ byte[] bytes = new byte[sid.BinaryLength];+ sid.GetBinaryForm(bytes, 0);+ return bytes;+ }++ public static int Run(string commandLine) {+ IntPtr token, restricted;+ if (!OpenProcessToken(GetCurrentProcess(), 0xF01FF, out token)) throw new Win32Exception();+ SecurityIdentifier[] disabled = {+ new SecurityIdentifier("S-1-5-32-544"), new SecurityIdentifier("S-1-5-32-547") };+ GCHandle[] pins = new GCHandle[disabled.Length];+ SidAndAttributes[] disable = new SidAndAttributes[disabled.Length];+ try {+ for (int i = 0; i < disabled.Length; i++) {+ pins[i] = GCHandle.Alloc(Binary(disabled[i]), GCHandleType.Pinned);+ disable[i].Sid = pins[i].AddrOfPinnedObject();+ }+ if (!CreateRestrictedToken(token, 0, (uint)disable.Length, disable, 0, IntPtr.Zero, 0, IntPtr.Zero, out restricted))+ throw new Win32Exception();+ } finally {+ foreach (GCHandle pin in pins) if (pin.IsAllocated) pin.Free();+ CloseHandle(token);+ }+ // An elevated token's default DACL grants Administrators, now deny-only,+ // and SYSTEM. PostgreSQL's processes must open each other's objects, so+ // the user is granted too, as pg_ctl does.+ RawAcl acl = new RawAcl(GenericAcl.AclRevision, 3);+ SecurityIdentifier[] granted = {+ WindowsIdentity.GetCurrent().User, new SecurityIdentifier("S-1-5-18"), new SecurityIdentifier("S-1-5-32-544") };+ for (int i = 0; i < granted.Length; i++)+ acl.InsertAce(i, new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 0x10000000, granted[i], false, null));+ byte[] dacl = new byte[acl.BinaryLength];+ acl.GetBinaryForm(dacl, 0);+ GCHandle daclPin = GCHandle.Alloc(dacl, GCHandleType.Pinned);+ try {+ IntPtr defaultDacl = daclPin.AddrOfPinnedObject();+ if (!SetTokenInformation(restricted, 6, ref defaultDacl, IntPtr.Size)) throw new Win32Exception();+ } finally { daclPin.Free(); }+ StartupInfo startup = new StartupInfo();+ startup.cb = Marshal.SizeOf(typeof(StartupInfo));+ startup.dwFlags = 0x100;+ startup.hStdInput = GetStdHandle(-10);+ startup.hStdOutput = GetStdHandle(-11);+ startup.hStdError = GetStdHandle(-12);+ ProcessInformation child;+ bool started = CreateProcessAsUserW(restricted, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero,+ true, 0, IntPtr.Zero, null, ref startup, out child);+ int error = Marshal.GetLastWin32Error();+ CloseHandle(restricted);+ if (!started) throw new Win32Exception(error);+ CloseHandle(child.hThread);+ WaitForSingleObject(child.hProcess, 0xFFFFFFFF);+ int code;+ GetExitCodeProcess(child.hProcess, out code);+ CloseHandle(child.hProcess);+ return code;+ }+}+'@+ exit ([LingerWithoutAdministrators]::Run($command))+} catch {+ # Plain output: it reaches the service log even where PowerShell runs in+ # Constrained Language mode and refuses Add-Type.+ 'Could not start the service with Administrators disabled: ' + $_.Exception.Message+ exit 1+}+`;++/**+ * The command line that the Microsoft C runtime, which PostgreSQL's tools use,+ * splits back into exactly `executable` and `args`.+ */+export function windowsCommandLine(executable: string, args: string[]) {+ return [executable, ...args]+ .map((value) =>+ value && !/[\s"]/.test(value)+ ? value+ : `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`,+ )+ .join(" ");+}