Prepare fixed EXE fixtures and qualify pure preconditions on cloud Linux
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
# Eigene EXE-Fixture: nur Artefaktauthoring
|
||||
|
||||
Stand 2026-11-14. Dieser eigenständige C-Quelltext ist **nicht** in Domain,
|
||||
Agent, Helper, Policy, Capability oder Backend eingebunden. Spezifikation1.19
|
||||
bleibt der enge MSI-Vertrag; dieses zusätzliche EXE-Artefakt erteilt keine
|
||||
Ausführungserlaubnis und ändert diesen Vertrag nicht. Keine Installation auf
|
||||
Notebook oder VM durch den Builder. Die späteren EXE-Rezept-/Provider-/WebUI-
|
||||
und nativen Fehlerabnahmen fehlen.
|
||||
|
||||
Die beiden fest kompilierten Versionen `10` / `11` bedeuten1.0.0 /1.1.0.
|
||||
Einziger Installeraufruf ist jeweils `--quiet --norestart` in genau dieser
|
||||
Reihenfolge. Es gibt keinen Pfad-, URL-, Command-, Repair-, Uninstall- oder
|
||||
Rebootparameter. Der Prozess muss tatsächlich SYSTEM sein. Kein Netzwerk,
|
||||
Dienststart, Unterprozess oder Neustartaufruf.
|
||||
|
||||
Feste eigene Nachbedingungen, getrennt vom MSI:
|
||||
|
||||
- Datei `C:\Program Files\RustDiscoveryFixtures\exe-payload.txt`, genau33Bytes.
|
||||
- Version1.0.0: ASCII `RustDiscovery EXE fixture 1.0.0\r\n`, SHA256
|
||||
`7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf`.
|
||||
- Version1.1.0: ASCII `RustDiscovery EXE fixture 1.1.0\r\n`, SHA256
|
||||
`e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0`.
|
||||
- Registry **HKLM64** `SOFTWARE\RustDiscovery\ExeFixture`, genau7Werte und keine
|
||||
Unterkeys: `ProductId=RustDiscovery.ExeFixture`, `Version`, `PayloadSHA256`,
|
||||
`Architecture=x64`, `Context=machine` jeweilsREG_SZ; `PayloadBytes=33` und
|
||||
`NoReboot=1` jeweilsREG_DWORD. Registry ist unabhängig von der Nutzdatei lesbar.
|
||||
|
||||
| Zielartefakt | Vollständiger Ausgangsbestand | Entscheidung |
|
||||
| --- | --- | --- |
|
||||
| 1.0 | Key und Datei fehlen | Erstinstallation |
|
||||
| 1.0 | Registry und Datei exakt1.0 | Noop, keine Writeoperation |
|
||||
| 1.0 | Exakt1.1 oder irgendein Teil-/Fremdzustand | Verweigern |
|
||||
| 1.1 | Registry und Datei exakt1.0 | Upgrade auf1.1 |
|
||||
| 1.1 | Registry und Datei exakt1.1 | Noop, keine Writeoperation |
|
||||
| 1.1 | Leer oder irgendein Teil-/Fremdzustand | Verweigern |
|
||||
|
||||
Der bestehende geschützte Fixtureordner muss vorab vorhanden sein; der Installer
|
||||
repariert keine Ordner/ACL. Gehaltene Elternhandles verweigern Umbenennung,
|
||||
Reparse- und Hardlinkblätter werden verweigert, nur SYSTEM/Administrators dürfen
|
||||
an Zielobjekten schreiben. Die Nutzdatei wird beim Upgrade anhand ihrer
|
||||
ursprünglichen File-ID und Bytes erneut geprüft und exklusiv gegen weitere
|
||||
Writer gehalten. Registrylinks/Fremdwerte werden nicht übernommen. Neue eigene
|
||||
Datei-/Registryobjekte bekommen SYS/Admin-Schreibrechte und Benutzer-Leserechte;
|
||||
eine vorhandene ACL wird nicht verändert.
|
||||
|
||||
**Nicht atomar:** Nutzdatei und Registry sind getrennte Wirkungen. Exit0 bedeutet
|
||||
nur das vom Fixtureprozess selbst bestätigte vollständige Ergebnis oder Noop;
|
||||
ein künftiger Provider muss Registry und Datei unabhängig nachprüfen. Exit10
|
||||
verweigert vor einer eigenen Mutation. Exit20 bedeutet mögliche/teilweise Wirkung
|
||||
nach der ersten Datei-/Keymutation, ausdrücklich **unknown**, kein Retry,
|
||||
Rollback, Repair oder Freigabe des ursprünglichen Versuchs. Timeout/Prozessverlust
|
||||
nach Übergabe kann unabhängig vom Exit ebenfalls unknown bedeuten. Diese eigenen
|
||||
Exitcodes sind keine MSI-Exitsemantik.
|
||||
|
||||
## Lokaler Build
|
||||
|
||||
Geplanter Builderaufruf: `python3 tools/windows-exe-fixture/build.py`.
|
||||
Der Builder verwendet nur das gepinnte vorhandene GNU-Buildimage, Netzwerk aus,
|
||||
keine Hostinstallation. Er kompiliert/runnt zuerst den reinen Linux-Guard,
|
||||
kompiliert dessen Windows-PE sowie beide Installer, erhält Original- und
|
||||
Stripdateien und speichert einen create-only privaten Quell-/Compiler-/Hash-
|
||||
Beleg unter `devstate/windows-exe-fixture/build-<UUID>/`. Er führt keine Windows-EXE
|
||||
aus. Gehashte Fixtureartefakte sind zunächst bewusst **unsigniert**; das ist
|
||||
kein Produktions-Signier- oder Installationsnachweis.
|
||||
|
||||
`contract_test.c` prüft ausschließlich die feste Zustands-/CLI-Matrix, ohne
|
||||
Datei/Registry/Netz und ohne Simulation einer Installerwirkung. Derselbe Guard
|
||||
muss später zuerst auf der Cloud-Linux-VM, danach auf der Windows-VM laufen.
|
||||
Native HKLM64-/ACL-/File-ID-/Install-/Upgrade-/Noop-/Teilwirkungsnachweise sind
|
||||
noch offen. Jede tatsächliche Installation benötigt einen neuen festen Plan und
|
||||
die reale WebUI-Genehmigung; Bootstrap/SFTP allein ist kein Paketnachweis.
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host-only, fixed-image EXE authoring. Never uploads or executes an installer."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9'
|
||||
NAMES = ('contract.h', 'contract_test.c', 'fixture.c', 'build.py', 'README.md')
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def snapshot():
|
||||
paths = [ROOT/'tools/windows-exe-fixture'/n for n in NAMES]
|
||||
paths += [ROOT/n for n in ('AGENTS.md', 'Rust_RMM_Implementierungsspezifikation.md', 'docs/project-decisions.md', 'docs/development.md')]
|
||||
return {str(p.relative_to(ROOT)): sha(p) for p in paths}
|
||||
|
||||
|
||||
def write(path, value):
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump(value, f, indent=2, sort_keys=True);f.flush();os.fsync(f.fileno())
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
base = ROOT/'devstate/windows-exe-fixture';base.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
case = base/('build-'+str(uuid.uuid4()));case.mkdir(mode=0o700)
|
||||
before = snapshot();write(case/'intent.json', {'image': IMAGE, 'source_files': before, 'build_only': True, 'native_installer_execution': False, 'network': False})
|
||||
script = '''set -eu
|
||||
cd /source
|
||||
cc --version > /out/linux-compiler.txt
|
||||
x86_64-w64-mingw32-gcc --version > /out/windows-compiler.txt
|
||||
cc -std=c11 -O2 -Wall -Wextra -Werror contract_test.c -o /out/linux-precondition-guard
|
||||
/out/linux-precondition-guard
|
||||
x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror contract_test.c -Wl,--no-insert-timestamp -o /out/windows-precondition-guard.original.exe
|
||||
x86_64-w64-mingw32-strip --strip-all /out/windows-precondition-guard.original.exe -o /out/windows-precondition-guard.exe
|
||||
for version in 10 11; do
|
||||
x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror -municode -DFIXTURE_VERSION=$version fixture.c -Wl,--no-insert-timestamp,--nxcompat,--dynamicbase,--high-entropy-va -ladvapi32 -lbcrypt -o /out/RustDiscoveryExeFixture-$version.original.exe
|
||||
x86_64-w64-mingw32-strip --strip-all /out/RustDiscoveryExeFixture-$version.original.exe -o /out/RustDiscoveryExeFixture-$version.exe
|
||||
x86_64-w64-mingw32-objdump -p /out/RustDiscoveryExeFixture-$version.exe > /out/imports-$version.log
|
||||
done
|
||||
readelf -h /out/linux-precondition-guard > /out/linux-elf-header.log
|
||||
readelf -d /out/linux-precondition-guard > /out/linux-elf-needed.log
|
||||
readelf --version-info /out/linux-precondition-guard > /out/linux-elf-versions.log
|
||||
chmod 600 /out/*
|
||||
'''
|
||||
args = ['docker', 'run', '--rm', '--user', str(os.getuid())+':'+str(os.getgid()), '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=64m', '-v', str(ROOT/'tools/windows-exe-fixture')+':/source:ro', '-v', str(case)+':/out', '--entrypoint', 'sh', IMAGE, '-c', script]
|
||||
result = subprocess.run(args, capture_output=True, timeout=120)
|
||||
write(case/'compiler-output.json', {'exit_code': result.returncode, 'stdout': result.stdout.decode(errors='replace'), 'stderr': result.stderr.decode(errors='replace')})
|
||||
after = snapshot();write(case/'source-after.json', after)
|
||||
if result.returncode != 0 or before != after:
|
||||
raise RuntimeError('FIXTURE_BUILD_FAILED_RETAINED_'+case.name)
|
||||
artifacts = {}
|
||||
for path in sorted(case.glob('*.exe')):
|
||||
b = path.read_bytes();pe = int.from_bytes(b[60:64], 'little')
|
||||
if b[:2] != b'MZ' or b[pe:pe+4] != b'PE\0\0' or int.from_bytes(b[pe+4:pe+6], 'little') != 0x8664:
|
||||
raise RuntimeError('FIXTURE_PE_AMD64_REQUIRED')
|
||||
if not '.original.' in path.name and len(b) > 262144:
|
||||
raise RuntimeError('FIXTURE_ARTIFACT_BUDGET')
|
||||
artifacts[path.name] = {'sha256': sha(path), 'bytes': len(b), 'architecture': 'AMD64', 'authenticode': 'not_signed_fixture_only'}
|
||||
artifacts['linux-precondition-guard'] = {'sha256': sha(case/'linux-precondition-guard'), 'bytes': (case/'linux-precondition-guard').stat().st_size}
|
||||
imports = {str(v): [l.strip().split(':', 1)[1].strip() for l in (case/f'imports-{v}.log').read_text().splitlines() if 'DLL Name:' in l] for v in (10, 11)}
|
||||
write(case/'qualification.json', {'image': IMAGE, 'source_files': before, 'source_before_after_equal': True, 'linux_pure_precondition_guard': 'passed_container_only', 'windows_pure_guard': 'linked_not_executed', 'windows_installer': 'linked_not_executed', 'cloud_linux_native_guard': 'not_executed', 'windows_native': 'not_executed', 'artifacts': artifacts, 'imports': imports, 'no_installer_run': True, 'no_upload': True})
|
||||
print(json.dumps({'case': str(case.relative_to(ROOT)), 'qualification_sha256': sha(case/'qualification.json'), 'artifacts': artifacts}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef RMM_EXE_FIXTURE_CONTRACT_H
|
||||
#define RMM_EXE_FIXTURE_CONTRACT_H
|
||||
#include <wchar.h>
|
||||
/* This authoring contract is NOT exported by an agent, helper or domain crate. */
|
||||
enum fixture_state { FIXTURE_ABSENT, FIXTURE_10, FIXTURE_11, FIXTURE_CONFLICT };
|
||||
enum fixture_step { FIXTURE_DENY, FIXTURE_INSTALL, FIXTURE_UPGRADE, FIXTURE_NOOP };
|
||||
static enum fixture_state fixture_state(unsigned registry, unsigned payload) {
|
||||
if (registry == 0 && payload == 0) return FIXTURE_ABSENT;
|
||||
if (registry == 10 && payload == 10) return FIXTURE_10;
|
||||
if (registry == 11 && payload == 11) return FIXTURE_11;
|
||||
return FIXTURE_CONFLICT;
|
||||
}
|
||||
static enum fixture_step fixture_step(unsigned desired, enum fixture_state before) {
|
||||
if (desired == 10) {
|
||||
if (before == FIXTURE_ABSENT) return FIXTURE_INSTALL;
|
||||
if (before == FIXTURE_10) return FIXTURE_NOOP;
|
||||
} else if (desired == 11) {
|
||||
if (before == FIXTURE_10) return FIXTURE_UPGRADE;
|
||||
if (before == FIXTURE_11) return FIXTURE_NOOP;
|
||||
}
|
||||
return FIXTURE_DENY;
|
||||
}
|
||||
static int fixture_arguments(int argc, const wchar_t *const *argv) {
|
||||
return argc == 3 && wcscmp(argv[1], L"--quiet") == 0
|
||||
&& wcscmp(argv[2], L"--norestart") == 0;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,25 @@
|
||||
/* Pure guard only. No OS, registry, file, installer or network operations. */
|
||||
#include "contract.h"
|
||||
#include <assert.h>
|
||||
int main(void) {
|
||||
const enum fixture_step expected[2][4] = {
|
||||
{ FIXTURE_INSTALL, FIXTURE_NOOP, FIXTURE_DENY, FIXTURE_DENY },
|
||||
{ FIXTURE_DENY, FIXTURE_UPGRADE, FIXTURE_NOOP, FIXTURE_DENY }
|
||||
};
|
||||
const wchar_t *good[] = { L"fixture.exe", L"--quiet", L"--norestart" };
|
||||
const wchar_t *foreign[] = { L"fixture.exe", L"--quiet", L"C:\\somewhere" };
|
||||
for (unsigned target = 0; target < 2; ++target)
|
||||
for (unsigned state = 0; state < 4; ++state)
|
||||
assert(fixture_step(10 + target, (enum fixture_state)state) == expected[target][state]);
|
||||
assert(fixture_step(12, FIXTURE_ABSENT) == FIXTURE_DENY);
|
||||
assert(fixture_state(0, 0) == FIXTURE_ABSENT);
|
||||
assert(fixture_state(10, 10) == FIXTURE_10);
|
||||
assert(fixture_state(11, 11) == FIXTURE_11);
|
||||
assert(fixture_state(0, 10) == FIXTURE_CONFLICT);
|
||||
assert(fixture_state(10, 11) == FIXTURE_CONFLICT);
|
||||
assert(fixture_state(99, 99) == FIXTURE_CONFLICT);
|
||||
assert(fixture_arguments(3, good));
|
||||
assert(!fixture_arguments(2, good));
|
||||
assert(!fixture_arguments(3, foreign));
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
/* Fixed own EXE fixture authoring source. Not an exported RMM provider.
|
||||
* No shell, network, service, reboot, repair, retry or caller-selected target.
|
||||
* An error after the first file/key mutation returns20: effect unresolved.
|
||||
*/
|
||||
#define _WIN32_WINNT 0x0a00
|
||||
#include <windows.h>
|
||||
#include <sddl.h>
|
||||
#include <aclapi.h>
|
||||
#include <bcrypt.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "contract.h"
|
||||
#if !defined(FIXTURE_VERSION) || (FIXTURE_VERSION != 10 && FIXTURE_VERSION != 11)
|
||||
#error Compile exactly one fixed fixture version10 or11
|
||||
#endif
|
||||
static const wchar_t *const ROOT = L"C:\\Program Files\\RustDiscoveryFixtures";
|
||||
static const wchar_t *const FILE_PATH = L"C:\\Program Files\\RustDiscoveryFixtures\\exe-payload.txt";
|
||||
static const wchar_t *const PARENT_KEY = L"SOFTWARE\\RustDiscovery";
|
||||
static const wchar_t *const PRODUCT_KEY = L"ExeFixture";
|
||||
static const wchar_t *const HASH10 = L"7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf";
|
||||
static const wchar_t *const HASH11 = L"e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0";
|
||||
static const char *payload(unsigned version) {
|
||||
return version == 10 ? "RustDiscovery EXE fixture 1.0.0\r\n" : "RustDiscovery EXE fixture 1.1.0\r\n";
|
||||
}
|
||||
static const wchar_t *version_text(unsigned version) {return version == 10 ? L"1.0.0" : L"1.1.0";}
|
||||
static const wchar_t *hash_text(unsigned version) {return version == 10 ? HASH10 : HASH11;}
|
||||
static int privileged_sid(PSID sid) {
|
||||
return IsWellKnownSid(sid, WinLocalSystemSid) || IsWellKnownSid(sid, WinBuiltinAdministratorsSid);
|
||||
}
|
||||
static int protected_object(HANDLE handle, SE_OBJECT_TYPE kind, DWORD read_mask) {
|
||||
PSID owner = NULL; PACL dacl = NULL; PSECURITY_DESCRIPTOR sd = NULL;
|
||||
if (GetSecurityInfo(handle, kind, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
&owner, NULL, &dacl, NULL, &sd) != ERROR_SUCCESS) return 0;
|
||||
int valid = owner && privileged_sid(owner) && dacl && dacl->AceCount;
|
||||
for (DWORD i = 0; valid && i < dacl->AceCount; ++i) {
|
||||
PVOID raw = NULL;
|
||||
if (!GetAce(dacl, i, &raw)) {valid = 0; break;}
|
||||
ACCESS_ALLOWED_ACE *ace = raw;
|
||||
if (ace->Header.AceType != ACCESS_ALLOWED_ACE_TYPE
|
||||
|| ace->Header.AceSize < sizeof(*ace)) {valid = 0; break;}
|
||||
if (ace->Header.AceFlags & INHERIT_ONLY_ACE) continue;
|
||||
PSID who = &ace->SidStart;
|
||||
if (!IsValidSid(who) || (!privileged_sid(who) && (ace->Mask & ~read_mask))) valid = 0;
|
||||
}
|
||||
LocalFree(sd); return valid;
|
||||
}
|
||||
static int system_process(void) {
|
||||
HANDLE token = NULL; _Alignas(8) BYTE buffer[128]; DWORD bytes = sizeof(buffer);
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return 0;
|
||||
int ok = GetTokenInformation(token, TokenUser, buffer, bytes, &bytes)
|
||||
&& IsWellKnownSid(((TOKEN_USER *)buffer)->User.Sid, WinLocalSystemSid);
|
||||
CloseHandle(token); return ok;
|
||||
}
|
||||
static int regular(HANDLE file, int directory, BY_HANDLE_FILE_INFORMATION *info) {
|
||||
return GetFileInformationByHandle(file, info)
|
||||
&& !(info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
&& !!(info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == directory
|
||||
&& (directory || info->nNumberOfLinks == 1);
|
||||
}
|
||||
static int same_file(const BY_HANDLE_FILE_INFORMATION *a, const BY_HANDLE_FILE_INFORMATION *b) {
|
||||
return a->dwVolumeSerialNumber == b->dwVolumeSerialNumber
|
||||
&& a->nFileIndexHigh == b->nFileIndexHigh && a->nFileIndexLow == b->nFileIndexLow;
|
||||
}
|
||||
static int file_version(HANDLE file) {
|
||||
BY_HANDLE_FILE_INFORMATION info; BYTE bytes[64], digest[32]; DWORD read = 0;
|
||||
BCRYPT_ALG_HANDLE alg = NULL; BCRYPT_HASH_HANDLE hash = NULL; BYTE *object = NULL;
|
||||
DWORD size = 0, got = 0; wchar_t hex[65]; int version = 99;
|
||||
if (!regular(file, 0, &info) || !protected_object(file, SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)
|
||||
|| info.nFileSizeHigh || info.nFileSizeLow != 33
|
||||
|| SetFilePointer(file, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER
|
||||
|| !ReadFile(file, bytes, sizeof(bytes), &read, NULL) || read != 33) return 99;
|
||||
if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, NULL, 0) < 0) goto done;
|
||||
if (BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&size, sizeof(size), &got, 0) < 0
|
||||
|| size == 0 || size > 4096) goto done;
|
||||
object = HeapAlloc(GetProcessHeap(), 0, size); if (!object) goto done;
|
||||
if (BCryptCreateHash(alg, &hash, object, size, NULL, 0, 0) < 0
|
||||
|| BCryptHashData(hash, bytes, read, 0) < 0
|
||||
|| BCryptFinishHash(hash, digest, sizeof(digest), 0) < 0) goto done;
|
||||
for (unsigned i = 0; i < 32; ++i) {
|
||||
static const wchar_t digits[] = L"0123456789abcdef";
|
||||
hex[2*i] = digits[digest[i] >> 4]; hex[2*i+1] = digits[digest[i] & 15];
|
||||
}
|
||||
hex[64] = 0;
|
||||
if (!wcscmp(hex, HASH10) && !memcmp(bytes, payload(10), 33)) version = 10;
|
||||
if (!wcscmp(hex, HASH11) && !memcmp(bytes, payload(11), 33)) version = 11;
|
||||
done:
|
||||
if (hash) BCryptDestroyHash(hash);
|
||||
if (object) HeapFree(GetProcessHeap(), 0, object);
|
||||
if (alg) BCryptCloseAlgorithmProvider(alg, 0);
|
||||
return version;
|
||||
}
|
||||
static int string_value(HKEY key, const wchar_t *name, const wchar_t *expected) {
|
||||
wchar_t data[128]; DWORD type = 0, size = sizeof(data);
|
||||
return RegQueryValueExW(key, name, NULL, &type, (BYTE *)data, &size) == ERROR_SUCCESS
|
||||
&& type == REG_SZ && size == (wcslen(expected) + 1) * sizeof(wchar_t)
|
||||
&& !memcmp(data, expected, size);
|
||||
}
|
||||
static int dword_value(HKEY key, const wchar_t *name, DWORD expected) {
|
||||
DWORD data = 0, type = 0, size = sizeof(data);
|
||||
return RegQueryValueExW(key, name, NULL, &type, (BYTE *)&data, &size) == ERROR_SUCCESS
|
||||
&& type == REG_DWORD && size == sizeof(data) && data == expected;
|
||||
}
|
||||
static int not_registry_link(HKEY key) {
|
||||
DWORD type = 0, size = 0;
|
||||
LSTATUS s = RegQueryValueExW(key, L"SymbolicLinkValue", NULL, &type, NULL, &size);
|
||||
return s == ERROR_FILE_NOT_FOUND; /* Never follow/adopt a caller-created link. */
|
||||
}
|
||||
static int registry_version(void) {
|
||||
HKEY parent = NULL, key = NULL; DWORD subkeys = 0, values = 0; int version = 99;
|
||||
LSTATUS s = RegOpenKeyExW(HKEY_LOCAL_MACHINE, PARENT_KEY, REG_OPTION_OPEN_LINK,
|
||||
KEY_READ | KEY_WOW64_64KEY, &parent);
|
||||
if (s == ERROR_FILE_NOT_FOUND) return 0;
|
||||
if (s != ERROR_SUCCESS) return 99;
|
||||
if (!protected_object((HANDLE)parent, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(parent)) goto done;
|
||||
s = RegOpenKeyExW(parent, PRODUCT_KEY, REG_OPTION_OPEN_LINK, KEY_READ | KEY_WOW64_64KEY, &key);
|
||||
if (s == ERROR_FILE_NOT_FOUND) {version = 0; goto done;}
|
||||
if (s != ERROR_SUCCESS || !protected_object((HANDLE)key, SE_REGISTRY_KEY, KEY_READ)
|
||||
|| !not_registry_link(key)) goto done;
|
||||
if (RegQueryInfoKeyW(key, NULL, NULL, NULL, &subkeys, NULL, NULL, &values,
|
||||
NULL, NULL, NULL, NULL) != ERROR_SUCCESS || subkeys || values != 7) goto done;
|
||||
unsigned candidate = string_value(key, L"Version", L"1.0.0") ? 10
|
||||
: string_value(key, L"Version", L"1.1.0") ? 11 : 0;
|
||||
if (candidate && string_value(key, L"ProductId", L"RustDiscovery.ExeFixture")
|
||||
&& string_value(key, L"PayloadSHA256", hash_text(candidate))
|
||||
&& string_value(key, L"Architecture", L"x64") && string_value(key, L"Context", L"machine")
|
||||
&& dword_value(key, L"PayloadBytes", 33) && dword_value(key, L"NoReboot", 1)) version = (int)candidate;
|
||||
done:
|
||||
if (key) RegCloseKey(key);
|
||||
if (parent) RegCloseKey(parent);
|
||||
return version;
|
||||
}
|
||||
static int set_string(HKEY key, const wchar_t *name, const wchar_t *value) {
|
||||
return RegSetValueExW(key, name, 0, REG_SZ, (const BYTE *)value,
|
||||
(DWORD)((wcslen(value)+1)*sizeof(wchar_t))) == ERROR_SUCCESS;
|
||||
}
|
||||
static int write_registry(unsigned version) {
|
||||
HKEY parent = NULL, key = NULL; PSECURITY_DESCRIPTOR sd = NULL; int ok = 0;
|
||||
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
L"D:P(A;;KA;;;SY)(A;;KA;;;BA)(A;;KR;;;BU)", SDDL_REVISION_1, &sd, NULL)) return 0;
|
||||
SECURITY_ATTRIBUTES sa = {sizeof(sa), sd, FALSE}; DWORD disposition = 0, bytes = 33, no_reboot = 1;
|
||||
if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, PARENT_KEY, 0, NULL, REG_OPTION_NON_VOLATILE,
|
||||
KEY_READ | KEY_CREATE_SUB_KEY | KEY_WOW64_64KEY, &sa, &parent, &disposition) != ERROR_SUCCESS) goto done;
|
||||
if (!protected_object((HANDLE)parent, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(parent)) goto done;
|
||||
if (RegCreateKeyExW(parent, PRODUCT_KEY, 0, NULL, REG_OPTION_NON_VOLATILE,
|
||||
KEY_READ | KEY_SET_VALUE | KEY_WOW64_64KEY, &sa, &key, &disposition) != ERROR_SUCCESS) goto done;
|
||||
if (!protected_object((HANDLE)key, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(key)) goto done;
|
||||
ok = set_string(key, L"ProductId", L"RustDiscovery.ExeFixture")
|
||||
&& set_string(key, L"Version", version_text(version))
|
||||
&& set_string(key, L"PayloadSHA256", hash_text(version))
|
||||
&& set_string(key, L"Architecture", L"x64") && set_string(key, L"Context", L"machine")
|
||||
&& RegSetValueExW(key, L"PayloadBytes", 0, REG_DWORD, (BYTE *)&bytes, sizeof(bytes)) == ERROR_SUCCESS
|
||||
&& RegSetValueExW(key, L"NoReboot", 0, REG_DWORD, (BYTE *)&no_reboot, sizeof(no_reboot)) == ERROR_SUCCESS
|
||||
&& RegFlushKey(key) == ERROR_SUCCESS;
|
||||
done:
|
||||
if (key) RegCloseKey(key);
|
||||
if (parent) RegCloseKey(parent);
|
||||
LocalFree(sd); return ok;
|
||||
}
|
||||
int wmain(int argc, wchar_t **argv) {
|
||||
HANDLE parents[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
|
||||
const wchar_t *const directories[] = {L"C:\\", L"C:\\Program Files", ROOT};
|
||||
HANDLE file = INVALID_HANDLE_VALUE; BY_HANDLE_FILE_INFORMATION original = {0}, current;
|
||||
int result = 10, observed_file = 0, observed_registry; PSECURITY_DESCRIPTOR sd = NULL;
|
||||
SYSTEM_INFO platform; GetNativeSystemInfo(&platform);
|
||||
if (platform.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64
|
||||
|| !fixture_arguments(argc, (const wchar_t *const *)argv) || !system_process()) return 10;
|
||||
for (unsigned i = 0; i < 3; ++i) {
|
||||
parents[i] = CreateFileW(directories[i], FILE_READ_ATTRIBUTES | READ_CONTROL,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
|
||||
if (parents[i] == INVALID_HANDLE_VALUE || !regular(parents[i], 1, ¤t)) goto done;
|
||||
}
|
||||
if (!protected_object(parents[2], SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)) goto done;
|
||||
file = CreateFileW(FILE_PATH, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);
|
||||
if (file == INVALID_HANDLE_VALUE) {
|
||||
if (GetLastError() != ERROR_FILE_NOT_FOUND) goto done;
|
||||
} else {
|
||||
if (!regular(file, 0, &original)) goto done;
|
||||
observed_file = file_version(file);
|
||||
}
|
||||
observed_registry = registry_version();
|
||||
enum fixture_step step = fixture_step(FIXTURE_VERSION, fixture_state((unsigned)observed_registry, (unsigned)observed_file));
|
||||
if (step == FIXTURE_NOOP) {result = 0; goto done;}
|
||||
if (step == FIXTURE_DENY) goto done;
|
||||
if (file != INVALID_HANDLE_VALUE) {CloseHandle(file); file = INVALID_HANDLE_VALUE;}
|
||||
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
L"D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;BU)", SDDL_REVISION_1, &sd, NULL)) goto done;
|
||||
SECURITY_ATTRIBUTES sa = {sizeof(sa), sd, FALSE};
|
||||
file = CreateFileW(FILE_PATH, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa,
|
||||
step == FIXTURE_INSTALL ? CREATE_NEW : OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);
|
||||
if (file == INVALID_HANDLE_VALUE) goto done;
|
||||
/* CREATE_NEW itself is the first possible mutation (an empty own file). */
|
||||
if (step == FIXTURE_INSTALL) result = 20;
|
||||
if (!regular(file, 0, ¤t) || !protected_object(file, SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)) goto done;
|
||||
if (step == FIXTURE_UPGRADE && (!same_file(&original, ¤t) || file_version(file) != 10)) goto done;
|
||||
if (registry_version() != observed_registry) goto done;
|
||||
/* From this boundary onwards every error is effect-unresolved, no rollback. */
|
||||
result = 20; DWORD written = 0;
|
||||
if (SetFilePointer(file, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER
|
||||
|| !WriteFile(file, payload(FIXTURE_VERSION), 33, &written, NULL) || written != 33
|
||||
|| !SetEndOfFile(file) || !FlushFileBuffers(file) || !write_registry(FIXTURE_VERSION)) goto done;
|
||||
if (file_version(file) == FIXTURE_VERSION && registry_version() == FIXTURE_VERSION) result = 0;
|
||||
done:
|
||||
if (sd) LocalFree(sd);
|
||||
if (file != INVALID_HANDLE_VALUE) CloseHandle(file);
|
||||
for (unsigned i = 0; i < 3; ++i) if (parents[i] != INVALID_HANDLE_VALUE) CloseHandle(parents[i]);
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user