mirror of
https://github.com/stablyai/orca.git
synced 2026-10-31 17:17:38 +00:00
* fix(windows): restrict secure files in-process instead of spawning icacls Every secure write on Windows spawned icacls.exe five times on the calling thread (the Electron main thread for most stores): verify, /reset, /inheritance:r /grant:r, verify, verify. Process creation under endpoint security costs ~0.6 s each, so each write froze the UI for seconds (#26027). The /reset + /inheritance:r pair is also what behavioural EDR scores as ransomware tradecraft (#25583). Add native/windows-security (@orca/windows-security): a small N-API addon over advapi32 that reads and writes DACLs in-process. It exposes the token user SID, a DACL read as SDDL, a DACL write (sync and on the thread pool), a create-with-DACL file write, and an additive grant. Policy and verification stay in TypeScript. - writeSecureFile creates each temp file already carrying the protected user/SYSTEM/Administrators DACL (CreateFileW + SECURITY_ATTRIBUTES), reads it back once, and renames it. No ACL is modified on the write path and no process starts. Before: 5-7 spawns, 94-138 ms per write. After: 0 spawns, ~0.5 ms. - A secure directory is verified once per process. It is rewritten only when verification fails, on the thread pool, because the write walks every descendant (~2 s on a 29k-entry userData). - The verifier follows OpenSSH's rule: only the user, SYSTEM and Administrators may be granted anything, and the path must be protected (or, for a file, inherit from a secure parent). DACLs written by the icacls-era hardening pass unchanged, so there is no migration. - If the addon cannot load, the write still happens and reports unrestricted, logged once. There is no icacls or PowerShell fallback. - grantDirAcl, the startup userData grant, and the install-dir probe and package repair use the same addon, so whoami.exe and icacls.exe are no longer spawned anywhere at runtime. - orcad's Windows slots ship the addon beside their bundles (built per arch, PE-machine checked). Its data-root privacy check fails closed, so without the addon a Windows orcad would not start. Fixes #26027 Fixes #25583 * refactor(secure-file): harden existing Windows files through the sync lane The read path called restrictWindowsPathSync directly and recorded success itself; the existing sync lane already does both. One call site fewer. * refactor(windows-security): one load, one rule, no fallthrough (review #28135) - The descriptor parser is anchored, so a conditional ACE (its body holds parentheses) or anything else it cannot read fails closed instead of verifying the ACEs before it. - findSecureDaclViolation is one flat rule: protected, allow rules only for the user, SYSTEM and Administrators (OpenSSH's ACE rule), and full control for the user. The inherits-from-a-secure-parent exception is gone: it accepted exactly what loosening the parent reaches. - The addon and the user SID load once, behind one wrapper that adds the extended-length prefix to every path and runs async DACL writes to one path in order, so a startup grant cannot land after a re-lock and restore the broader DACL. - With the addon loaded, a failed born-restricted create throws with the matching Node error code instead of falling back to a plain write. - A grant leaves a NULL DACL untouched instead of turning 'everyone' into 'only this SID'. WriteFile runs once and fails on a short write. - The artifact create-intent store writes through writeSecureFile and drops its own temp writer, directory LRU and synchronous directory re-lock. - Test seams the global fake makes redundant are gone. * fix(packaging): fail a Windows build whose workspace addon binary is missing or foreign-arch The @orca/windows-* workspace links exist on every host, so their presence proved nothing: a missing or wrong-architecture .node only surfaced at runtime, as unrestricted secure files or an orcad that refuses to start. beforePack now reads each addon's PE machine against the target arch. * refactor(windows-security): prune what the native ACL left dead (review #28135) - Sync-spawn ratchet: hardenSecurePath and the sync-flag exemption it alone used are gone, and the advice and baseline header no longer say secure writers run icacls. - The install-dir probe reads ACEs through parseSddlDacl, so an ACE it cannot parse fails the whole reading closed instead of being skipped; AC is a resolved alias there now. - The packaging check reads the addon binary through node_modules, the copy that ships. - No winCode-to-errno table: nothing reads .code off a failed secure write. - The load memo is not mutated; secure-path keeps its own log-once flag. - grantInstallDirPackageAcl is a plain function, and secure-file restricts a Windows directory and a POSIX path directly instead of through one two-platform helper. * fix(windows-security): resolve LA in real-ACL tests; tear a file whose close fails - The GitHub Windows runner is the built-in Administrator (RID 500), whose SID reads back as LA. Production already resolves it through localDomainSidOf; the win32 test helpers parsed without it. One shared readDaclOf resolves aliases for every real-ACL suite, and the verifier's unit test covers an LA-aliased directory and LA as a stranger. - createFileWithDacl treats a failed CloseHandle like a failed write (lost data on a network volume) and deletes the torn file. - Drop a duplicate test reset and a typo. * fix(windows-security): load only from inside the app; read DACLs as structure (review #28135) - Loader: orcad's staged binary first, then the workspace package only if its real path is inside the app (process.resourcesPath, or this checkout). A bare specifier otherwise walks every parent up to C:\node_modules, which any local user may create, and orcad holds credentials. - The addon reads a DACL as { protected, aces: [{ type, flags, mask, sid }] } via GetAce, with a SID only for plain allow/deny ACEs and null for a NULL DACL. findSecureDaclViolation and the install-dir probe check that structure, so conditional, callback and object ACEs fail closed. The SDDL parser, its alias table, LA/localDomainSid resolution and getDaclSddl are gone; SDDL is only the write format. - Install-dir tree pass: files flagless as before, but a directory only when its own DACL is protected (inheritably). Re-granting inheriting directories re-propagated each subtree (3.2 s for 1,093 directories). The root is no longer granted, or counted, twice. The two passes are plain functions behind a { root, tree } seam. - One namespacing (path.win32.toNamespacedPath) at the addon boundary, also the per-path ordering key; the comment states the real sync-grant invariant. - restrictWindowsDirectory(dir): Promise<boolean> replaces the callback lane; the reporter is guarded once, so the 'settle' stage is gone. - Sync-spawn ratchet: the secure writers no longer spawn or block, so they leave the gate (109 -> 61 uses). - Errors name the Win32 call and code only; a failed GetSecurityDescriptorControl fails the write instead of defaulting to unprotected. * test(secure-file): assert the durable POSIX write's outcome, not the old chmod order writeSecureFile now chmods the temp file to 0o600 before fsyncing it, so the fsync also covers the mode change and the file is owner-writable when opened. Assert what matters under umask 0o200: the write succeeds, the temp file is fsynced read-only, and the published file is exactly 0o600. * fix(windows-security): namespace paths with the host's toNamespacedPath path.win32.toNamespacedPath rewrote POSIX temp paths (/tmp/x -> \tmp\x) in the Linux runs of the Windows-logic unit tests, so the fake addon wrote to the wrong place. The addon only runs on Windows, where the host function is the win32 one; elsewhere it is the identity. The long-path assertion runs on Windows only. * test(windows-security): assert the install-dir long-path prefix on Windows only The prefix comes from the host's toNamespacedPath, which is the identity off Windows; the Linux run of this suite expected the win32 escape. * fix(windows-user-data-acl): grant the root even when its children cannot be listed (review #28135) A readdir failure on userData aborted the whole grant, so the root grant that could repair a DACL refusing the listing was never attempted. The listing failure is now recorded, the root is still granted, and the marker stays withheld so the next launch retries. * test(windows-security): wait for relock propagation, accept Entra ID SIDs (review #28135) - The large-relock test waited only for the parent to turn protected, which happens before propagation reaches the children, then read a child. It now waits on the parent and both ends of the child range. - The token-user test rejected S-1-12-1 (Entra ID) accounts, failing the suite on Entra-joined dev machines. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
408 lines
16 KiB
C++
408 lines
16 KiB
C++
// In-process Windows DACL reads and writes for Orca's secure files.
|
|
//
|
|
// Why native: the alternative is spawning icacls.exe, which blocked the main thread for seconds
|
|
// per write on hosts with slow process creation (#26027), and whose `/reset` + `/inheritance:r`
|
|
// shape behavioural EDR scores as ransomware (#25583). Policy (which SIDs, which flags) lives in
|
|
// JS; this file writes DACLs given as SDDL and reads them back as plain structure.
|
|
|
|
#include <napi.h>
|
|
#include <windows.h>
|
|
#include <aclapi.h>
|
|
#include <sddl.h>
|
|
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace {
|
|
|
|
struct Win32Result {
|
|
DWORD code = ERROR_SUCCESS;
|
|
const char* syscall = "";
|
|
bool ok() const { return code == ERROR_SUCCESS; }
|
|
};
|
|
|
|
Win32Result Fail(const char* syscall, DWORD code) { return Win32Result{code, syscall}; }
|
|
|
|
struct LocalDeleter {
|
|
void operator()(void* pointer) const { LocalFree(pointer); }
|
|
};
|
|
using LocalPtr = std::unique_ptr<void, LocalDeleter>;
|
|
|
|
Napi::Error ToError(Napi::Env env, const Win32Result& result) {
|
|
return Napi::Error::New(
|
|
env, std::string(result.syscall) + " failed with Win32 error " + std::to_string(result.code));
|
|
}
|
|
|
|
Win32Result ParseSddl(const std::u16string& sddl, LocalPtr* descriptor) {
|
|
PSECURITY_DESCRIPTOR raw = nullptr;
|
|
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
reinterpret_cast<LPCWSTR>(sddl.c_str()), SDDL_REVISION_1, &raw, nullptr)) {
|
|
return Fail("ConvertStringSecurityDescriptorToSecurityDescriptorW", GetLastError());
|
|
}
|
|
descriptor->reset(raw);
|
|
return {};
|
|
}
|
|
|
|
// The descriptor's own protection bit decides: a replacement DACL carries the caller's choice, and
|
|
// a grant re-reads the object's, so adding one rule never flips inheritance on or off.
|
|
Win32Result DaclInformationFor(PSECURITY_DESCRIPTOR descriptor, SECURITY_INFORMATION* information) {
|
|
SECURITY_DESCRIPTOR_CONTROL control = 0;
|
|
DWORD revision = 0;
|
|
if (!GetSecurityDescriptorControl(descriptor, &control, &revision)) {
|
|
return Fail("GetSecurityDescriptorControl", GetLastError());
|
|
}
|
|
*information = DACL_SECURITY_INFORMATION | ((control & SE_DACL_PROTECTED)
|
|
? PROTECTED_DACL_SECURITY_INFORMATION
|
|
: UNPROTECTED_DACL_SECURITY_INFORMATION);
|
|
return {};
|
|
}
|
|
|
|
Win32Result ApplyDacl(std::u16string path, const std::u16string& sddl) {
|
|
LocalPtr descriptor;
|
|
auto parsed = ParseSddl(sddl, &descriptor);
|
|
if (!parsed.ok()) {
|
|
return parsed;
|
|
}
|
|
BOOL present = FALSE;
|
|
BOOL defaulted = FALSE;
|
|
PACL dacl = nullptr;
|
|
if (!GetSecurityDescriptorDacl(descriptor.get(), &present, &dacl, &defaulted)) {
|
|
return Fail("GetSecurityDescriptorDacl", GetLastError());
|
|
}
|
|
// A missing DACL means "everyone, full control"; never install that by accident.
|
|
if (!present || dacl == nullptr) {
|
|
return Fail("GetSecurityDescriptorDacl", ERROR_INVALID_SECURITY_DESCR);
|
|
}
|
|
SECURITY_INFORMATION information = 0;
|
|
auto control = DaclInformationFor(descriptor.get(), &information);
|
|
if (!control.ok()) {
|
|
return control;
|
|
}
|
|
DWORD status = SetNamedSecurityInfoW(reinterpret_cast<LPWSTR>(path.data()), SE_FILE_OBJECT,
|
|
information, nullptr, nullptr, dacl, nullptr);
|
|
return status == ERROR_SUCCESS ? Win32Result{} : Fail("SetNamedSecurityInfoW", status);
|
|
}
|
|
|
|
Win32Result GrantAccess(std::u16string path, const std::u16string& sid, DWORD mask,
|
|
bool inheritable, bool replace) {
|
|
PSECURITY_DESCRIPTOR rawDescriptor = nullptr;
|
|
PACL existing = nullptr;
|
|
DWORD status = GetNamedSecurityInfoW(reinterpret_cast<LPCWSTR>(path.c_str()), SE_FILE_OBJECT,
|
|
DACL_SECURITY_INFORMATION, nullptr, nullptr, &existing,
|
|
nullptr, &rawDescriptor);
|
|
if (status != ERROR_SUCCESS) {
|
|
return Fail("GetNamedSecurityInfoW", status);
|
|
}
|
|
LocalPtr descriptor(rawDescriptor);
|
|
// A NULL DACL already grants everyone everything; merging into it would build a DACL holding
|
|
// only this rule and lock every other principal out.
|
|
if (existing == nullptr) {
|
|
return {};
|
|
}
|
|
PSID rawSid = nullptr;
|
|
if (!ConvertStringSidToSidW(reinterpret_cast<LPCWSTR>(sid.c_str()), &rawSid)) {
|
|
return Fail("ConvertStringSidToSidW", GetLastError());
|
|
}
|
|
LocalPtr trusteeSid(rawSid);
|
|
|
|
EXPLICIT_ACCESSW access{};
|
|
access.grfAccessPermissions = mask;
|
|
access.grfAccessMode = replace ? SET_ACCESS : GRANT_ACCESS;
|
|
access.grfInheritance = inheritable ? SUB_CONTAINERS_AND_OBJECTS_INHERIT : NO_INHERITANCE;
|
|
access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
|
|
access.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
|
|
access.Trustee.ptstrName = reinterpret_cast<LPWSTR>(rawSid);
|
|
|
|
PACL merged = nullptr;
|
|
status = SetEntriesInAclW(1, &access, existing, &merged);
|
|
if (status != ERROR_SUCCESS) {
|
|
return Fail("SetEntriesInAclW", status);
|
|
}
|
|
LocalPtr mergedAcl(merged);
|
|
SECURITY_INFORMATION information = 0;
|
|
auto control = DaclInformationFor(descriptor.get(), &information);
|
|
if (!control.ok()) {
|
|
return control;
|
|
}
|
|
status = SetNamedSecurityInfoW(reinterpret_cast<LPWSTR>(path.data()), SE_FILE_OBJECT,
|
|
information, nullptr, nullptr, merged, nullptr);
|
|
return status == ERROR_SUCCESS ? Win32Result{} : Fail("SetNamedSecurityInfoW", status);
|
|
}
|
|
|
|
Win32Result CreateFileWithDacl(const std::u16string& path, const std::u16string& sddl,
|
|
const uint8_t* data, size_t length) {
|
|
LocalPtr descriptor;
|
|
auto parsed = ParseSddl(sddl, &descriptor);
|
|
if (!parsed.ok()) {
|
|
return parsed;
|
|
}
|
|
if (length > MAXDWORD) {
|
|
return Fail("WriteFile", ERROR_INVALID_PARAMETER);
|
|
}
|
|
SECURITY_ATTRIBUTES attributes{sizeof(attributes), descriptor.get(), FALSE};
|
|
// Why CREATE_NEW: the descriptor only applies to a file this call creates; opening an
|
|
// existing one would keep that file's (possibly broader) DACL. Share mode 0 keeps every other
|
|
// opener out until the contents are complete.
|
|
HANDLE file = CreateFileW(reinterpret_cast<LPCWSTR>(path.c_str()), GENERIC_WRITE, 0,
|
|
&attributes, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (file == INVALID_HANDLE_VALUE) {
|
|
return Fail("CreateFileW", GetLastError());
|
|
}
|
|
Win32Result result;
|
|
DWORD written = 0;
|
|
if (!WriteFile(file, data, static_cast<DWORD>(length), &written, nullptr)) {
|
|
result = Fail("WriteFile", GetLastError());
|
|
} else if (written != length) {
|
|
result = Fail("WriteFile", ERROR_WRITE_FAULT);
|
|
}
|
|
// A failed close can mean lost data on a network volume, so it tears the file like a failed write.
|
|
if (!CloseHandle(file) && result.ok()) {
|
|
result = Fail("CloseHandle", GetLastError());
|
|
}
|
|
if (!result.ok()) {
|
|
// A torn temp file is useless to the caller and must not linger beside the real one.
|
|
DeleteFileW(reinterpret_cast<LPCWSTR>(path.c_str()));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
bool ReadGrantOptions(const Napi::Value& value, bool* inheritable, bool* replace) {
|
|
if (!value.IsObject()) {
|
|
return false;
|
|
}
|
|
auto options = value.As<Napi::Object>();
|
|
auto inherit = options.Get("inheritable");
|
|
auto replaceValue = options.Get("replace");
|
|
if (!inherit.IsBoolean() || !replaceValue.IsBoolean()) {
|
|
return false;
|
|
}
|
|
*inheritable = inherit.As<Napi::Boolean>().Value();
|
|
*replace = replaceValue.As<Napi::Boolean>().Value();
|
|
return true;
|
|
}
|
|
|
|
Napi::Value ThrowTypeError(Napi::Env env, const char* signature) {
|
|
Napi::TypeError::New(env, signature).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
|
|
Napi::Value SidString(Napi::Env env, PSID sid) {
|
|
LPWSTR text = nullptr;
|
|
if (!ConvertSidToStringSidW(sid, &text)) {
|
|
ToError(env, Fail("ConvertSidToStringSidW", GetLastError())).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
LocalPtr owned(text);
|
|
return Napi::String::New(env, reinterpret_cast<char16_t*>(text));
|
|
}
|
|
|
|
Napi::Value CurrentUserSid(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
HANDLE token = nullptr;
|
|
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
|
|
ToError(env, Fail("OpenProcessToken", GetLastError())).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
DWORD size = 0;
|
|
GetTokenInformation(token, TokenUser, nullptr, 0, &size);
|
|
std::vector<BYTE> buffer(size);
|
|
BOOL queried = size > 0 && GetTokenInformation(token, TokenUser, buffer.data(), size, &size);
|
|
DWORD queryError = GetLastError();
|
|
CloseHandle(token);
|
|
if (!queried) {
|
|
ToError(env, Fail("GetTokenInformation", queryError)).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
return SidString(env, reinterpret_cast<TOKEN_USER*>(buffer.data())->User.Sid);
|
|
}
|
|
|
|
// Structure only, no policy: `{ protected, aces: [{ type, flags, mask, sid }] }`, or null for a
|
|
// NULL DACL. Only plain allow/deny ACEs carry a SID; every other type comes back with sid null so
|
|
// the caller can refuse what it does not understand (object, callback and conditional ACEs).
|
|
Napi::Value GetDaclAces(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
if (info.Length() < 1 || !info[0].IsString()) {
|
|
return ThrowTypeError(env, "getDaclAces(path: string)");
|
|
}
|
|
auto path = info[0].As<Napi::String>().Utf16Value();
|
|
PSECURITY_DESCRIPTOR rawDescriptor = nullptr;
|
|
PACL dacl = nullptr;
|
|
DWORD status = GetNamedSecurityInfoW(reinterpret_cast<LPCWSTR>(path.c_str()), SE_FILE_OBJECT,
|
|
DACL_SECURITY_INFORMATION, nullptr, nullptr, &dacl,
|
|
nullptr, &rawDescriptor);
|
|
if (status != ERROR_SUCCESS) {
|
|
ToError(env, Fail("GetNamedSecurityInfoW", status)).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
LocalPtr descriptor(rawDescriptor);
|
|
if (dacl == nullptr) {
|
|
return env.Null();
|
|
}
|
|
SECURITY_DESCRIPTOR_CONTROL control = 0;
|
|
DWORD revision = 0;
|
|
if (!GetSecurityDescriptorControl(rawDescriptor, &control, &revision)) {
|
|
ToError(env, Fail("GetSecurityDescriptorControl", GetLastError())).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
auto aces = Napi::Array::New(env, dacl->AceCount);
|
|
for (DWORD index = 0; index < dacl->AceCount; index++) {
|
|
void* raw = nullptr;
|
|
if (!GetAce(dacl, index, &raw)) {
|
|
ToError(env, Fail("GetAce", GetLastError())).ThrowAsJavaScriptException();
|
|
return env.Undefined();
|
|
}
|
|
auto* header = static_cast<ACE_HEADER*>(raw);
|
|
auto ace = Napi::Object::New(env);
|
|
ace.Set("type", Napi::Number::New(env, header->AceType));
|
|
ace.Set("flags", Napi::Number::New(env, header->AceFlags));
|
|
// ACCESS_ALLOWED_ACE and ACCESS_DENIED_ACE share this layout: Mask, then SidStart.
|
|
if (header->AceType == ACCESS_ALLOWED_ACE_TYPE || header->AceType == ACCESS_DENIED_ACE_TYPE) {
|
|
auto* plain = static_cast<ACCESS_ALLOWED_ACE*>(raw);
|
|
ace.Set("mask", Napi::Number::New(env, plain->Mask));
|
|
auto sid = SidString(env, &plain->SidStart);
|
|
if (env.IsExceptionPending()) {
|
|
return env.Undefined();
|
|
}
|
|
ace.Set("sid", sid);
|
|
} else {
|
|
ace.Set("mask", Napi::Number::New(env, 0));
|
|
ace.Set("sid", env.Null());
|
|
}
|
|
aces.Set(index, ace);
|
|
}
|
|
auto result = Napi::Object::New(env);
|
|
result.Set("protected", Napi::Boolean::New(env, (control & SE_DACL_PROTECTED) != 0));
|
|
result.Set("aces", aces);
|
|
return result;
|
|
}
|
|
|
|
Napi::Value SetDaclSddl(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
if (info.Length() < 2 || !info[0].IsString() || !info[1].IsString()) {
|
|
return ThrowTypeError(env, "setDaclSddl(path: string, sddl: string)");
|
|
}
|
|
auto result = ApplyDacl(info[0].As<Napi::String>().Utf16Value(),
|
|
info[1].As<Napi::String>().Utf16Value());
|
|
if (!result.ok()) {
|
|
ToError(env, result).ThrowAsJavaScriptException();
|
|
}
|
|
return env.Undefined();
|
|
}
|
|
|
|
Napi::Value CreateFileWithDaclJs(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
if (info.Length() < 3 || !info[0].IsString() || !info[1].IsString() ||
|
|
!info[2].IsTypedArray()) {
|
|
return ThrowTypeError(env, "createFileWithDacl(path: string, sddl: string, data: Uint8Array)");
|
|
}
|
|
auto data = info[2].As<Napi::Uint8Array>();
|
|
auto result = CreateFileWithDacl(info[0].As<Napi::String>().Utf16Value(),
|
|
info[1].As<Napi::String>().Utf16Value(), data.Data(),
|
|
data.ByteLength());
|
|
if (!result.ok()) {
|
|
ToError(env, result).ThrowAsJavaScriptException();
|
|
}
|
|
return env.Undefined();
|
|
}
|
|
|
|
bool ReadGrantArguments(const Napi::CallbackInfo& info, std::u16string* path, std::u16string* sid,
|
|
DWORD* mask, bool* inheritable, bool* replace) {
|
|
if (info.Length() < 4 || !info[0].IsString() || !info[1].IsString() || !info[2].IsNumber() ||
|
|
!ReadGrantOptions(info[3], inheritable, replace)) {
|
|
return false;
|
|
}
|
|
*path = info[0].As<Napi::String>().Utf16Value();
|
|
*sid = info[1].As<Napi::String>().Utf16Value();
|
|
*mask = info[2].As<Napi::Number>().Uint32Value();
|
|
return true;
|
|
}
|
|
|
|
constexpr const char* kGrantSignature =
|
|
"grantAccess(path: string, sid: string, accessMask: number, "
|
|
"options: { inheritable: boolean, replace: boolean })";
|
|
|
|
Napi::Value GrantAccessJs(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
std::u16string path, sid;
|
|
DWORD mask = 0;
|
|
bool inheritable = false, replace = false;
|
|
if (!ReadGrantArguments(info, &path, &sid, &mask, &inheritable, &replace)) {
|
|
return ThrowTypeError(env, kGrantSignature);
|
|
}
|
|
auto result = GrantAccess(path, sid, mask, inheritable, replace);
|
|
if (!result.ok()) {
|
|
ToError(env, result).ThrowAsJavaScriptException();
|
|
}
|
|
return env.Undefined();
|
|
}
|
|
|
|
// Why a worker: a directory DACL change walks every descendant (seconds on a large userData).
|
|
class DaclWorker : public Napi::AsyncWorker {
|
|
public:
|
|
DaclWorker(Napi::Env env, std::function<Win32Result()> work)
|
|
: Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
|
|
work_(std::move(work)) {}
|
|
|
|
Napi::Promise Promise() { return deferred_.Promise(); }
|
|
|
|
void Execute() override { result_ = work_(); }
|
|
void OnOK() override {
|
|
if (result_.ok()) {
|
|
deferred_.Resolve(Env().Undefined());
|
|
} else {
|
|
deferred_.Reject(ToError(Env(), result_).Value());
|
|
}
|
|
}
|
|
|
|
private:
|
|
Napi::Promise::Deferred deferred_;
|
|
std::function<Win32Result()> work_;
|
|
Win32Result result_;
|
|
};
|
|
|
|
Napi::Value SetDaclSddlAsync(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
if (info.Length() < 2 || !info[0].IsString() || !info[1].IsString()) {
|
|
return ThrowTypeError(env, "setDaclSddlAsync(path: string, sddl: string)");
|
|
}
|
|
auto path = info[0].As<Napi::String>().Utf16Value();
|
|
auto sddl = info[1].As<Napi::String>().Utf16Value();
|
|
auto* worker = new DaclWorker(env, [path, sddl]() { return ApplyDacl(path, sddl); });
|
|
auto promise = worker->Promise();
|
|
worker->Queue();
|
|
return promise;
|
|
}
|
|
|
|
Napi::Value GrantAccessAsync(const Napi::CallbackInfo& info) {
|
|
auto env = info.Env();
|
|
std::u16string path, sid;
|
|
DWORD mask = 0;
|
|
bool inheritable = false, replace = false;
|
|
if (!ReadGrantArguments(info, &path, &sid, &mask, &inheritable, &replace)) {
|
|
return ThrowTypeError(env, kGrantSignature);
|
|
}
|
|
auto* worker = new DaclWorker(env, [=]() {
|
|
return GrantAccess(path, sid, mask, inheritable, replace);
|
|
});
|
|
auto promise = worker->Promise();
|
|
worker->Queue();
|
|
return promise;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
Napi::Object Init(Napi::Env env, Napi::Object exports) {
|
|
exports.Set("currentUserSid", Napi::Function::New(env, CurrentUserSid));
|
|
exports.Set("getDaclAces", Napi::Function::New(env, GetDaclAces));
|
|
exports.Set("setDaclSddl", Napi::Function::New(env, SetDaclSddl));
|
|
exports.Set("setDaclSddlAsync", Napi::Function::New(env, SetDaclSddlAsync));
|
|
exports.Set("createFileWithDacl", Napi::Function::New(env, CreateFileWithDaclJs));
|
|
exports.Set("grantAccess", Napi::Function::New(env, GrantAccessJs));
|
|
exports.Set("grantAccessAsync", Napi::Function::New(env, GrantAccessAsync));
|
|
return exports;
|
|
}
|
|
|
|
NODE_API_MODULE(orca_windows_security, Init)
|