blun-king-cli 9.1.630 → 9.1.633
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/blun.js +0 -0
- package/bin/core-bootstrap.js +0 -0
- package/bin/king.js +0 -0
- package/bin/launcher-mode.js +0 -0
- package/bin/launcher-runtime.js +25 -15
- package/bin/managed-node.js +0 -0
- package/bin/managed-plugin-selection.cjs +26 -1
- package/bin/native-command-runner.js +0 -0
- package/bin/native-module-repair.js +0 -0
- package/bin/node-runtime.js +0 -0
- package/bin/node-version.js +0 -0
- package/bin/plugin-bootstrap.js +280 -38
- package/bin/private-paths.js +621 -40
- package/bin/rename-private-staging.cjs +1 -1
- package/bin/standard-tools-bootstrap.js +97 -0
- package/bin/startup-security.cjs +306 -0
- package/bin/update-copy.js +0 -0
- package/bin/update-lease.js +0 -0
- package/bin/update-notice.js +192 -8
- package/bin/windows-private-temp.cjs +282 -0
- package/blun.mjs +0 -0
- package/package.json +1 -1
package/bin/private-paths.js
CHANGED
|
@@ -4,6 +4,7 @@ const { execFileSync } = require('node:child_process');
|
|
|
4
4
|
const fs = require('node:fs');
|
|
5
5
|
const path = require('node:path');
|
|
6
6
|
const { gzipSync } = require('node:zlib');
|
|
7
|
+
const { createWindowsPrivateTemp } = require('./windows-private-temp.cjs');
|
|
7
8
|
|
|
8
9
|
const PRIVATE_DIRECTORY_MODE = 0o700;
|
|
9
10
|
const PRIVATE_FILE_MODE = 0o600;
|
|
@@ -27,14 +28,36 @@ using System.Text;
|
|
|
27
28
|
|
|
28
29
|
public static class BlunPrivateAclNative
|
|
29
30
|
{
|
|
31
|
+
public static string CurrentPhase = "native-dispatch";
|
|
32
|
+
public static string CurrentTarget = null;
|
|
30
33
|
private const uint GENERIC_READ = 0x80000000;
|
|
31
34
|
private const uint GENERIC_WRITE = 0x40000000;
|
|
32
35
|
private const uint DELETE = 0x00010000;
|
|
33
36
|
private const uint READ_CONTROL = 0x00020000;
|
|
34
37
|
private const uint WRITE_DAC = 0x00040000;
|
|
38
|
+
private const uint WRITE_OWNER = 0x00080000;
|
|
35
39
|
private const uint SYNCHRONIZE = 0x00100000;
|
|
36
40
|
private const uint CREATE_NEW = 1;
|
|
37
41
|
private const uint OPEN_EXISTING = 3;
|
|
42
|
+
private const uint FILE_SHARE_ALL = 0x00000007;
|
|
43
|
+
public static int DirectoryDaclWrites = 0;
|
|
44
|
+
public static readonly List<string> Warnings = new List<string>();
|
|
45
|
+
|
|
46
|
+
private static SafeFileHandle OpenShared(string target, uint access, uint flags)
|
|
47
|
+
{
|
|
48
|
+
for (int attempt = 0; ; attempt++)
|
|
49
|
+
{
|
|
50
|
+
SafeFileHandle handle = CreateFileExisting(target, access, FILE_SHARE_ALL,
|
|
51
|
+
IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
52
|
+
if (!handle.IsInvalid) return handle;
|
|
53
|
+
int error = Marshal.GetLastWin32Error();
|
|
54
|
+
handle.Dispose();
|
|
55
|
+
if ((error != 32 && error != 33) || attempt == 2)
|
|
56
|
+
throw new Win32Exception(error);
|
|
57
|
+
System.Threading.Thread.Sleep(40);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
38
61
|
private const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
|
|
39
62
|
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
|
|
40
63
|
private const uint FILE_ATTRIBUTE_DEVICE = 0x00000040;
|
|
@@ -213,6 +236,11 @@ public static class BlunPrivateAclNative
|
|
|
213
236
|
out IntPtr dacl,
|
|
214
237
|
[MarshalAs(UnmanagedType.Bool)] out bool daclDefaulted);
|
|
215
238
|
|
|
239
|
+
[DllImport("advapi32.dll", SetLastError = true)]
|
|
240
|
+
[return: MarshalAs(UnmanagedType.Bool)]
|
|
241
|
+
private static extern bool SetKernelObjectSecurity(
|
|
242
|
+
SafeFileHandle handle, uint securityInformation, IntPtr securityDescriptor);
|
|
243
|
+
|
|
216
244
|
[DllImport("advapi32.dll", SetLastError = true)]
|
|
217
245
|
private static extern uint SetSecurityInfo(
|
|
218
246
|
SafeFileHandle handle,
|
|
@@ -277,7 +305,6 @@ public static class BlunPrivateAclNative
|
|
|
277
305
|
HashSet<string> expected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
278
306
|
expected.Add(user.Value);
|
|
279
307
|
expected.Add("S-1-5-18");
|
|
280
|
-
expected.Add("S-1-5-32-544");
|
|
281
308
|
return expected;
|
|
282
309
|
}
|
|
283
310
|
|
|
@@ -286,8 +313,7 @@ public static class BlunPrivateAclNative
|
|
|
286
313
|
string flags = directory ? "OICI" : "";
|
|
287
314
|
string[] trustees = new string[] {
|
|
288
315
|
new SecurityIdentifier(userSid).Value,
|
|
289
|
-
"S-1-5-18"
|
|
290
|
-
"S-1-5-32-544"
|
|
316
|
+
"S-1-5-18"
|
|
291
317
|
};
|
|
292
318
|
HashSet<string> seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
293
319
|
StringBuilder builder = new StringBuilder("D:P");
|
|
@@ -312,8 +338,30 @@ public static class BlunPrivateAclNative
|
|
|
312
338
|
return descriptor;
|
|
313
339
|
}
|
|
314
340
|
|
|
341
|
+
private static void SetExactDirectoryDacl(SafeFileHandle handle, string userSid, bool directory)
|
|
342
|
+
{
|
|
343
|
+
CurrentPhase = "dacl-write";
|
|
344
|
+
if (directory) DirectoryDaclWrites++;
|
|
345
|
+
IntPtr descriptor = CreateExactDescriptor(userSid, directory);
|
|
346
|
+
try
|
|
347
|
+
{
|
|
348
|
+
// SetSecurityInfo(SE_FILE_OBJECT) propagates inheritable ACEs into
|
|
349
|
+
// existing descendants. A startup root check must touch only this
|
|
350
|
+
// handle; explicit HardenTree remains the opt-in recursive API.
|
|
351
|
+
if (!SetKernelObjectSecurity(handle,
|
|
352
|
+
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
|
|
353
|
+
descriptor))
|
|
354
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
355
|
+
}
|
|
356
|
+
finally
|
|
357
|
+
{
|
|
358
|
+
LocalFree(descriptor);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
315
362
|
private static void SetExactDacl(SafeFileHandle handle, string userSid, bool directory)
|
|
316
363
|
{
|
|
364
|
+
CurrentPhase = "dacl-write";
|
|
317
365
|
IntPtr descriptor = CreateExactDescriptor(userSid, directory);
|
|
318
366
|
try
|
|
319
367
|
{
|
|
@@ -376,10 +424,37 @@ public static class BlunPrivateAclNative
|
|
|
376
424
|
SafeFileHandle handle,
|
|
377
425
|
HashSet<string> expectedSids)
|
|
378
426
|
{
|
|
427
|
+
CurrentPhase = "owner-verification";
|
|
379
428
|
RawSecurityDescriptor descriptor = ReadAccessDescriptor(handle);
|
|
380
|
-
if (descriptor.Owner == null
|
|
429
|
+
if (descriptor.Owner == null) throw new UnauthorizedAccessException();
|
|
430
|
+
if (expectedSids.Contains(descriptor.Owner.Value)) return descriptor.Owner.Value;
|
|
431
|
+
// The only additional trusted owner is BUILTIN\\Administrators.
|
|
432
|
+
// WRITE_OWNER permits taking ownership as self without SeRestorePrivilege.
|
|
433
|
+
if (!String.Equals(descriptor.Owner.Value, "S-1-5-32-544", StringComparison.OrdinalIgnoreCase))
|
|
381
434
|
throw new UnauthorizedAccessException();
|
|
382
|
-
|
|
435
|
+
CurrentPhase = "owner-takeover";
|
|
436
|
+
SecurityIdentifier self = WindowsIdentity.GetCurrent().User;
|
|
437
|
+
if (self == null || !expectedSids.Contains(self.Value))
|
|
438
|
+
throw new UnauthorizedAccessException();
|
|
439
|
+
byte[] sid = new byte[self.BinaryLength];
|
|
440
|
+
self.GetBinaryForm(sid, 0);
|
|
441
|
+
IntPtr owner = Marshal.AllocHGlobal(sid.Length);
|
|
442
|
+
try
|
|
443
|
+
{
|
|
444
|
+
Marshal.Copy(sid, 0, owner, sid.Length);
|
|
445
|
+
uint result = SetSecurityInfo(handle, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION,
|
|
446
|
+
owner, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
|
447
|
+
if (result != 0) throw new Win32Exception((int)result);
|
|
448
|
+
}
|
|
449
|
+
finally
|
|
450
|
+
{
|
|
451
|
+
Marshal.FreeHGlobal(owner);
|
|
452
|
+
Array.Clear(sid, 0, sid.Length);
|
|
453
|
+
}
|
|
454
|
+
RawSecurityDescriptor actual = ReadAccessDescriptor(handle);
|
|
455
|
+
if (actual.Owner == null || !actual.Owner.Equals(self))
|
|
456
|
+
throw new UnauthorizedAccessException();
|
|
457
|
+
return self.Value;
|
|
383
458
|
}
|
|
384
459
|
|
|
385
460
|
private static void VerifyExactDacl(
|
|
@@ -388,6 +463,7 @@ public static class BlunPrivateAclNative
|
|
|
388
463
|
bool directory,
|
|
389
464
|
string expectedOwner)
|
|
390
465
|
{
|
|
466
|
+
CurrentPhase = "dacl-verification";
|
|
391
467
|
HashSet<string> expectedSids = ExpectedSids(userSid);
|
|
392
468
|
RawSecurityDescriptor descriptor = ReadAccessDescriptor(handle);
|
|
393
469
|
if (descriptor.Owner == null
|
|
@@ -424,6 +500,7 @@ public static class BlunPrivateAclNative
|
|
|
424
500
|
SafeFileHandle handle,
|
|
425
501
|
bool directory)
|
|
426
502
|
{
|
|
503
|
+
CurrentPhase = "entry-validation";
|
|
427
504
|
ByHandleFileInformation information;
|
|
428
505
|
if (!GetFileInformationByHandle(handle, out information))
|
|
429
506
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
@@ -532,6 +609,7 @@ public static class BlunPrivateAclNative
|
|
|
532
609
|
|
|
533
610
|
private static void VerifyHandlePath(SafeFileHandle handle, string expectedPath)
|
|
534
611
|
{
|
|
612
|
+
CurrentPhase = "path-verification";
|
|
535
613
|
StringBuilder buffer = new StringBuilder(32768);
|
|
536
614
|
uint length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Capacity, 0);
|
|
537
615
|
if (length == 0 || length >= buffer.Capacity)
|
|
@@ -545,23 +623,147 @@ public static class BlunPrivateAclNative
|
|
|
545
623
|
}
|
|
546
624
|
}
|
|
547
625
|
|
|
548
|
-
private static
|
|
626
|
+
private static ByHandleFileInformation TakeOwnerBeforeReopen(
|
|
627
|
+
string target, bool directory, string userSid, ByHandleFileInformation? expected)
|
|
549
628
|
{
|
|
550
|
-
|
|
551
|
-
|
|
629
|
+
CurrentTarget = target;
|
|
630
|
+
CurrentPhase = "owner-takeover";
|
|
552
631
|
uint flags = FILE_FLAG_OPEN_REPARSE_POINT;
|
|
553
632
|
if (directory) flags |= FILE_FLAG_BACKUP_SEMANTICS;
|
|
554
|
-
SafeFileHandle handle
|
|
555
|
-
|
|
556
|
-
|
|
633
|
+
SafeFileHandle handle;
|
|
634
|
+
try { handle = OpenShared(target, READ_CONTROL | WRITE_OWNER | 0x80, flags); }
|
|
635
|
+
catch (Win32Exception error)
|
|
557
636
|
{
|
|
558
|
-
|
|
559
|
-
handle
|
|
560
|
-
|
|
637
|
+
if (error.NativeErrorCode != 5) throw;
|
|
638
|
+
handle = OpenShared(target, READ_CONTROL | 0x80, flags);
|
|
639
|
+
}
|
|
640
|
+
using (handle)
|
|
641
|
+
{
|
|
642
|
+
ByHandleFileInformation identity = ValidateHandle(handle, directory);
|
|
643
|
+
VerifyHandlePath(handle, target);
|
|
644
|
+
if (expected.HasValue) VerifyReopenedIdentity(handle, directory, expected.Value);
|
|
645
|
+
CurrentPhase = "owner-verification";
|
|
646
|
+
RawSecurityDescriptor before = ReadAccessDescriptor(handle);
|
|
647
|
+
if (before.Owner == null || before.Owner.Value != "S-1-5-32-544")
|
|
648
|
+
throw new UnauthorizedAccessException();
|
|
649
|
+
ValidateOwner(handle, ExpectedSids(userSid));
|
|
650
|
+
ValidateHandle(handle, directory);
|
|
651
|
+
VerifyHandlePath(handle, target);
|
|
652
|
+
return identity;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
private static void VerifyReopenedIdentity(
|
|
657
|
+
SafeFileHandle handle, bool directory, ByHandleFileInformation expected)
|
|
658
|
+
{
|
|
659
|
+
ByHandleFileInformation actual = ValidateHandle(handle, directory);
|
|
660
|
+
if (actual.VolumeSerialNumber != expected.VolumeSerialNumber
|
|
661
|
+
|| FileId(actual) == 0 || FileId(actual) != FileId(expected))
|
|
662
|
+
throw new UnauthorizedAccessException();
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// Existing objects are inspected without requesting WRITE_DAC, WRITE_OWNER,
|
|
666
|
+
// DELETE or data-write access. Directory listing is needed for tree snapshots.
|
|
667
|
+
private static SafeFileHandle OpenExisting(string target, bool directory, bool enumerate, string userSid)
|
|
668
|
+
{
|
|
669
|
+
CurrentTarget = target;
|
|
670
|
+
CurrentPhase = "entry-open";
|
|
671
|
+
uint flags = FILE_FLAG_OPEN_REPARSE_POINT;
|
|
672
|
+
if (directory) flags |= FILE_FLAG_BACKUP_SEMANTICS;
|
|
673
|
+
uint access = READ_CONTROL | 0x80;
|
|
674
|
+
if (directory && enumerate) access |= 1;
|
|
675
|
+
SafeFileHandle handle;
|
|
676
|
+
try { handle = OpenShared(target, access, flags); }
|
|
677
|
+
catch (Win32Exception error)
|
|
678
|
+
{
|
|
679
|
+
if (error.NativeErrorCode != 5) throw;
|
|
680
|
+
ByHandleFileInformation identity = TakeOwnerBeforeReopen(target, directory, userSid, null);
|
|
681
|
+
handle = OpenShared(target, access, flags);
|
|
682
|
+
try { VerifyReopenedIdentity(handle, directory, identity); VerifyHandlePath(handle, target); }
|
|
683
|
+
catch { handle.Dispose(); throw; }
|
|
561
684
|
}
|
|
562
685
|
return handle;
|
|
563
686
|
}
|
|
564
687
|
|
|
688
|
+
private static bool IsExact(SafeFileHandle handle, string userSid, bool directory, out string owner)
|
|
689
|
+
{
|
|
690
|
+
CurrentPhase = "owner-verification";
|
|
691
|
+
RawSecurityDescriptor descriptor = ReadAccessDescriptor(handle);
|
|
692
|
+
if (descriptor.Owner == null) throw new UnauthorizedAccessException();
|
|
693
|
+
owner = descriptor.Owner.Value;
|
|
694
|
+
if (!ExpectedSids(userSid).Contains(owner))
|
|
695
|
+
{
|
|
696
|
+
if (owner == "S-1-5-32-544") return false;
|
|
697
|
+
throw new UnauthorizedAccessException();
|
|
698
|
+
}
|
|
699
|
+
try { VerifyExactDacl(handle, userSid, directory, owner); return true; }
|
|
700
|
+
catch (UnauthorizedAccessException) { return false; }
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
private static string ApplyExactSecurity(SafeFileHandle inspected, string target, string userSid, bool directory)
|
|
704
|
+
{
|
|
705
|
+
CurrentTarget = target;
|
|
706
|
+
ByHandleFileInformation identity = ValidateHandle(inspected, directory);
|
|
707
|
+
VerifyHandlePath(inspected, target);
|
|
708
|
+
string owner;
|
|
709
|
+
if (IsExact(inspected, userSid, directory, out owner))
|
|
710
|
+
{
|
|
711
|
+
ValidateHandle(inspected, directory);
|
|
712
|
+
VerifyHandlePath(inspected, target);
|
|
713
|
+
return owner;
|
|
714
|
+
}
|
|
715
|
+
uint flags = FILE_FLAG_OPEN_REPARSE_POINT;
|
|
716
|
+
if (directory) flags |= FILE_FLAG_BACKUP_SEMANTICS;
|
|
717
|
+
uint access = READ_CONTROL | WRITE_DAC | 0x80;
|
|
718
|
+
if (owner == "S-1-5-32-544") access |= WRITE_OWNER;
|
|
719
|
+
SafeFileHandle mutation;
|
|
720
|
+
try { mutation = OpenShared(target, access, flags); }
|
|
721
|
+
catch (Win32Exception error)
|
|
722
|
+
{
|
|
723
|
+
if (error.NativeErrorCode == 5 && owner == "S-1-5-32-544")
|
|
724
|
+
{
|
|
725
|
+
// Administrator-owned objects may grant WRITE_OWNER but not yet
|
|
726
|
+
// WRITE_DAC. Bind the takeover to the original read identity.
|
|
727
|
+
TakeOwnerBeforeReopen(target, directory, userSid, identity);
|
|
728
|
+
mutation = OpenShared(target, READ_CONTROL | WRITE_DAC | 0x80, flags);
|
|
729
|
+
}
|
|
730
|
+
else
|
|
731
|
+
{
|
|
732
|
+
// A lock is never proof of safety. Recheck this very object AND its
|
|
733
|
+
// current pathname; warn only if the full current descriptor is exact.
|
|
734
|
+
if (error.NativeErrorCode != 32 && error.NativeErrorCode != 33) throw;
|
|
735
|
+
VerifyReopenedIdentity(inspected, directory, identity);
|
|
736
|
+
VerifyHandlePath(inspected, target);
|
|
737
|
+
if (!IsExact(inspected, userSid, directory, out owner)) throw;
|
|
738
|
+
VerifyReopenedIdentity(inspected, directory, identity);
|
|
739
|
+
VerifyHandlePath(inspected, target);
|
|
740
|
+
Warnings.Add(target);
|
|
741
|
+
return owner;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
using (mutation)
|
|
745
|
+
{
|
|
746
|
+
// Keep the read handle alive across escalation. Reject replacement,
|
|
747
|
+
// reparse or hardlink attacks before ANY security descriptor mutation.
|
|
748
|
+
VerifyReopenedIdentity(mutation, directory, identity);
|
|
749
|
+
VerifyHandlePath(mutation, target);
|
|
750
|
+
VerifyReopenedIdentity(inspected, directory, identity);
|
|
751
|
+
VerifyHandlePath(inspected, target);
|
|
752
|
+
if (IsExact(mutation, userSid, directory, out owner)) return owner;
|
|
753
|
+
ValidateHandle(mutation, directory);
|
|
754
|
+
VerifyHandlePath(mutation, target);
|
|
755
|
+
owner = ValidateOwner(mutation, ExpectedSids(userSid));
|
|
756
|
+
VerifyReopenedIdentity(mutation, directory, identity);
|
|
757
|
+
VerifyHandlePath(mutation, target);
|
|
758
|
+
if (directory) SetExactDirectoryDacl(mutation, userSid, true);
|
|
759
|
+
else SetExactDacl(mutation, userSid, false);
|
|
760
|
+
VerifyExactDacl(mutation, userSid, directory, owner);
|
|
761
|
+
VerifyReopenedIdentity(mutation, directory, identity);
|
|
762
|
+
VerifyHandlePath(mutation, target);
|
|
763
|
+
return owner;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
565
767
|
private static string NativePath(string target)
|
|
566
768
|
{
|
|
567
769
|
string full = Path.GetFullPath(target);
|
|
@@ -574,6 +776,9 @@ public static class BlunPrivateAclNative
|
|
|
574
776
|
string target,
|
|
575
777
|
string userSid)
|
|
576
778
|
{
|
|
779
|
+
CurrentTarget = target;
|
|
780
|
+
CurrentPhase = "directory-open";
|
|
781
|
+
if (Directory.Exists(target)) return OpenExisting(target, true, false, userSid);
|
|
577
782
|
string nativePath = NativePath(target);
|
|
578
783
|
if (Encoding.Unicode.GetByteCount(nativePath) > UInt16.MaxValue - 2)
|
|
579
784
|
throw new PathTooLongException();
|
|
@@ -602,16 +807,99 @@ public static class BlunPrivateAclNative
|
|
|
602
807
|
IoStatusBlock ioStatus;
|
|
603
808
|
int status = NtCreateFile(
|
|
604
809
|
out rawHandle,
|
|
605
|
-
GENERIC_READ | READ_CONTROL | WRITE_DAC | DELETE | SYNCHRONIZE,
|
|
810
|
+
GENERIC_READ | READ_CONTROL | WRITE_DAC | WRITE_OWNER | DELETE | SYNCHRONIZE,
|
|
606
811
|
ref attributes,
|
|
607
812
|
out ioStatus,
|
|
608
813
|
IntPtr.Zero,
|
|
609
814
|
0,
|
|
815
|
+
FILE_SHARE_ALL,
|
|
816
|
+
FILE_OPEN_IF,
|
|
817
|
+
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
|
|
818
|
+
IntPtr.Zero,
|
|
819
|
+
0);
|
|
820
|
+
if (status < 0 && RtlNtStatusToDosError(status) == 5)
|
|
821
|
+
{
|
|
822
|
+
status = NtCreateFile(out rawHandle,
|
|
823
|
+
GENERIC_READ | READ_CONTROL | WRITE_DAC | DELETE | SYNCHRONIZE,
|
|
824
|
+
ref attributes, out ioStatus, IntPtr.Zero, 0, FILE_SHARE_ALL, FILE_OPEN_IF,
|
|
825
|
+
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
|
|
826
|
+
IntPtr.Zero, 0);
|
|
827
|
+
}
|
|
828
|
+
if (status < 0 && RtlNtStatusToDosError(status) == 5)
|
|
829
|
+
return OpenExisting(target, true, false, userSid);
|
|
830
|
+
if (status < 0)
|
|
831
|
+
throw new Win32Exception((int)RtlNtStatusToDosError(status));
|
|
832
|
+
return new SafeFileHandle(rawHandle, true);
|
|
833
|
+
}
|
|
834
|
+
catch
|
|
835
|
+
{
|
|
836
|
+
if (rawHandle != IntPtr.Zero && rawHandle != new IntPtr(-1))
|
|
837
|
+
new SafeFileHandle(rawHandle, true).Dispose();
|
|
838
|
+
throw;
|
|
839
|
+
}
|
|
840
|
+
finally
|
|
841
|
+
{
|
|
842
|
+
if (descriptor != IntPtr.Zero) LocalFree(descriptor);
|
|
843
|
+
if (namePointer != IntPtr.Zero) Marshal.FreeHGlobal(namePointer);
|
|
844
|
+
if (nameBuffer != IntPtr.Zero) Marshal.FreeHGlobal(nameBuffer);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
private static SafeFileHandle OpenOrCreateStartupDirectory(
|
|
849
|
+
string target,
|
|
850
|
+
string userSid)
|
|
851
|
+
{
|
|
852
|
+
CurrentTarget = target;
|
|
853
|
+
CurrentPhase = "directory-open";
|
|
854
|
+
if (Directory.Exists(target)) return OpenShared(target, READ_CONTROL | 0x80, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
|
|
855
|
+
string nativePath = NativePath(target);
|
|
856
|
+
if (Encoding.Unicode.GetByteCount(nativePath) > UInt16.MaxValue - 2)
|
|
857
|
+
throw new PathTooLongException();
|
|
858
|
+
|
|
859
|
+
IntPtr nameBuffer = IntPtr.Zero;
|
|
860
|
+
IntPtr namePointer = IntPtr.Zero;
|
|
861
|
+
IntPtr descriptor = IntPtr.Zero;
|
|
862
|
+
IntPtr rawHandle = IntPtr.Zero;
|
|
863
|
+
try
|
|
864
|
+
{
|
|
865
|
+
nameBuffer = Marshal.StringToHGlobalUni(nativePath);
|
|
866
|
+
UnicodeString name = new UnicodeString();
|
|
867
|
+
name.Length = (ushort)Encoding.Unicode.GetByteCount(nativePath);
|
|
868
|
+
name.MaximumLength = (ushort)(name.Length + 2);
|
|
869
|
+
name.Buffer = nameBuffer;
|
|
870
|
+
namePointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnicodeString)));
|
|
871
|
+
Marshal.StructureToPtr(name, namePointer, false);
|
|
872
|
+
descriptor = CreateExactDescriptor(userSid, true);
|
|
873
|
+
|
|
874
|
+
ObjectAttributes attributes = new ObjectAttributes();
|
|
875
|
+
attributes.Length = Marshal.SizeOf(typeof(ObjectAttributes));
|
|
876
|
+
attributes.ObjectName = namePointer;
|
|
877
|
+
attributes.Attributes = OBJ_CASE_INSENSITIVE;
|
|
878
|
+
attributes.SecurityDescriptor = descriptor;
|
|
879
|
+
|
|
880
|
+
IoStatusBlock ioStatus;
|
|
881
|
+
int status = NtCreateFile(
|
|
882
|
+
out rawHandle,
|
|
883
|
+
GENERIC_READ | READ_CONTROL | WRITE_DAC | WRITE_OWNER | DELETE | SYNCHRONIZE,
|
|
884
|
+
ref attributes,
|
|
885
|
+
out ioStatus,
|
|
886
|
+
IntPtr.Zero,
|
|
610
887
|
0,
|
|
888
|
+
FILE_SHARE_ALL,
|
|
611
889
|
FILE_OPEN_IF,
|
|
612
890
|
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
|
|
613
891
|
IntPtr.Zero,
|
|
614
892
|
0);
|
|
893
|
+
if (status < 0 && RtlNtStatusToDosError(status) == 5)
|
|
894
|
+
{
|
|
895
|
+
status = NtCreateFile(out rawHandle,
|
|
896
|
+
GENERIC_READ | READ_CONTROL | WRITE_DAC | DELETE | SYNCHRONIZE,
|
|
897
|
+
ref attributes, out ioStatus, IntPtr.Zero, 0, FILE_SHARE_ALL, FILE_OPEN_IF,
|
|
898
|
+
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
|
|
899
|
+
IntPtr.Zero, 0);
|
|
900
|
+
}
|
|
901
|
+
if (status < 0 && RtlNtStatusToDosError(status) == 5)
|
|
902
|
+
return OpenShared(target, READ_CONTROL | 0x80, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
|
|
615
903
|
if (status < 0)
|
|
616
904
|
throw new Win32Exception((int)RtlNtStatusToDosError(status));
|
|
617
905
|
return new SafeFileHandle(rawHandle, true);
|
|
@@ -649,24 +937,184 @@ public static class BlunPrivateAclNative
|
|
|
649
937
|
{
|
|
650
938
|
ValidateHandle(handle, true);
|
|
651
939
|
VerifyHandlePath(handle, fullTarget);
|
|
652
|
-
|
|
653
|
-
string owner = ValidateOwner(handle, expectedSids);
|
|
654
|
-
SetExactDacl(handle, userSid, true);
|
|
655
|
-
VerifyExactDacl(handle, userSid, true, owner);
|
|
940
|
+
ApplyExactSecurity(handle, fullTarget, userSid, true);
|
|
656
941
|
VerifyHandlePath(handle, fullTarget);
|
|
657
942
|
}
|
|
658
943
|
}
|
|
659
944
|
|
|
945
|
+
// Startup writes only a nonconforming, user-owned directory object. The
|
|
946
|
+
// kernel handle setter deliberately does NOT propagate into descendants.
|
|
947
|
+
private static bool StartupReadOnlyExtras(RawSecurityDescriptor descriptor, string userSid)
|
|
948
|
+
{
|
|
949
|
+
if ((descriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) == 0
|
|
950
|
+
|| descriptor.DiscretionaryAcl == null) return false;
|
|
951
|
+
HashSet<string> expected = ExpectedSids(userSid);
|
|
952
|
+
HashSet<string> seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
953
|
+
int readMask = (int)(FileSystemRights.ReadAndExecute | FileSystemRights.Synchronize);
|
|
954
|
+
foreach (GenericAce generic in descriptor.DiscretionaryAcl)
|
|
955
|
+
{
|
|
956
|
+
CommonAce ace = generic as CommonAce;
|
|
957
|
+
if (ace == null || ace.AceQualifier != AceQualifier.AccessAllowed
|
|
958
|
+
|| ace.SecurityIdentifier == null) return false;
|
|
959
|
+
string sid = ace.SecurityIdentifier.Value;
|
|
960
|
+
AceFlags inheritance = AceFlags.ObjectInherit | AceFlags.ContainerInherit
|
|
961
|
+
| AceFlags.Inherited | AceFlags.InheritOnly | AceFlags.NoPropagateInherit;
|
|
962
|
+
if ((ace.AceFlags & ~inheritance) != 0) return false;
|
|
963
|
+
if (expected.Contains(sid) || sid == "S-1-5-32-544")
|
|
964
|
+
{
|
|
965
|
+
// Extra allow rights for owner/SYSTEM/Administrators are safe.
|
|
966
|
+
// Still require the explicit, self-effective base grants; an
|
|
967
|
+
// inherited-only/standard DACL belongs to the repair category.
|
|
968
|
+
if (expected.Contains(sid) && ace.AccessMask == (int)FileSystemRights.FullControl
|
|
969
|
+
&& ace.AceFlags == (AceFlags.ObjectInherit | AceFlags.ContainerInherit))
|
|
970
|
+
seen.Add(sid);
|
|
971
|
+
}
|
|
972
|
+
else if ((ace.AccessMask & ~readMask) != 0) return false;
|
|
973
|
+
}
|
|
974
|
+
return seen.SetEquals(expected);
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// USERPROFILE is supplied by the launching Windows process, never StateDir.
|
|
978
|
+
// Pin every ancestor without delete sharing: junctions and rename races must
|
|
979
|
+
// not move a repair across the profile boundary while the setter runs.
|
|
980
|
+
private sealed class StartupProfileBoundary : IDisposable
|
|
981
|
+
{
|
|
982
|
+
private readonly List<SafeFileHandle> handles = new List<SafeFileHandle>();
|
|
983
|
+
public readonly bool CanRepair;
|
|
984
|
+
private string PinAncestors(string target)
|
|
985
|
+
{
|
|
986
|
+
string full = ValidateTreeRootPath(target);
|
|
987
|
+
string current = full;
|
|
988
|
+
string resolved = null;
|
|
989
|
+
while (!String.IsNullOrEmpty(current))
|
|
990
|
+
{
|
|
991
|
+
SafeFileHandle held = CreateFileExisting(current, 0x80, 3,
|
|
992
|
+
IntPtr.Zero, OPEN_EXISTING,
|
|
993
|
+
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, IntPtr.Zero);
|
|
994
|
+
if (held.IsInvalid) { int error = Marshal.GetLastWin32Error(); held.Dispose(); throw new Win32Exception(error); }
|
|
995
|
+
handles.Add(held);
|
|
996
|
+
ValidateHandle(held, true);
|
|
997
|
+
VerifyHandlePath(held, current);
|
|
998
|
+
if (resolved == null)
|
|
999
|
+
{
|
|
1000
|
+
StringBuilder address = new StringBuilder(32768);
|
|
1001
|
+
uint length = GetFinalPathNameByHandleW(held, address, (uint)address.Capacity, 0);
|
|
1002
|
+
if (length == 0 || length >= address.Capacity) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
1003
|
+
resolved = Path.GetFullPath(NormalizeHandlePath(address.ToString())).TrimEnd('\\');
|
|
1004
|
+
}
|
|
1005
|
+
current = Path.GetDirectoryName(current);
|
|
1006
|
+
}
|
|
1007
|
+
return resolved;
|
|
1008
|
+
}
|
|
1009
|
+
public StartupProfileBoundary(string target)
|
|
1010
|
+
{
|
|
1011
|
+
try
|
|
1012
|
+
{
|
|
1013
|
+
string actual = PinAncestors(target);
|
|
1014
|
+
string profile = Environment.GetEnvironmentVariable("USERPROFILE");
|
|
1015
|
+
if (String.IsNullOrEmpty(profile)) { CanRepair = false; return; }
|
|
1016
|
+
string resolvedProfile = PinAncestors(profile);
|
|
1017
|
+
string boundary = Path.Combine(resolvedProfile, ".blun");
|
|
1018
|
+
CanRepair = String.Equals(actual, boundary, StringComparison.OrdinalIgnoreCase)
|
|
1019
|
+
|| actual.StartsWith(boundary + "\\", StringComparison.OrdinalIgnoreCase);
|
|
1020
|
+
}
|
|
1021
|
+
catch { Dispose(); throw; }
|
|
1022
|
+
}
|
|
1023
|
+
public void Dispose()
|
|
1024
|
+
{
|
|
1025
|
+
for (int i = handles.Count - 1; i >= 0; i--) handles[i].Dispose();
|
|
1026
|
+
handles.Clear();
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
public static readonly List<string> OutsideProfile = new List<string>();
|
|
1030
|
+
public static string StartupOwnerSid = null;
|
|
1031
|
+
|
|
1032
|
+
public static readonly List<string> Repaired = new List<string>();
|
|
1033
|
+
// Windows PowerShell 5.1 does not reliably bind omitted .NET optional
|
|
1034
|
+
// arguments. Keep an explicit two-argument overload for the host protocol.
|
|
1035
|
+
public static void InspectStartupDirectory(string target, string userSid)
|
|
1036
|
+
{
|
|
1037
|
+
InspectStartupDirectory(target, userSid, true);
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
public static void InspectStartupDirectory(string target, string userSid, bool allowRepair)
|
|
1041
|
+
{
|
|
1042
|
+
string full = ValidateTreeRootPath(target);
|
|
1043
|
+
if (!Directory.Exists(full))
|
|
1044
|
+
{
|
|
1045
|
+
string parent = Path.GetDirectoryName(full);
|
|
1046
|
+
if (!Directory.Exists(parent)) InspectStartupDirectory(parent, userSid, allowRepair);
|
|
1047
|
+
using (SafeFileHandle created = OpenOrCreateStartupDirectory(full, userSid))
|
|
1048
|
+
{
|
|
1049
|
+
ValidateHandle(created, true);
|
|
1050
|
+
VerifyHandlePath(created, full);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
CurrentTarget = full;
|
|
1054
|
+
using (SafeFileHandle handle = OpenShared(full, READ_CONTROL | 0x80,
|
|
1055
|
+
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT))
|
|
1056
|
+
{
|
|
1057
|
+
ByHandleFileInformation identity = ValidateHandle(handle, true);
|
|
1058
|
+
VerifyHandlePath(handle, full);
|
|
1059
|
+
CurrentPhase = "owner-verification";
|
|
1060
|
+
RawSecurityDescriptor descriptor = ReadAccessDescriptor(handle);
|
|
1061
|
+
StartupOwnerSid = descriptor.Owner == null ? null : descriptor.Owner.Value;
|
|
1062
|
+
if (descriptor.Owner == null || descriptor.Owner.Value != new SecurityIdentifier(userSid).Value)
|
|
1063
|
+
throw new UnauthorizedAccessException();
|
|
1064
|
+
try { VerifyExactDacl(handle, userSid, true, descriptor.Owner.Value); }
|
|
1065
|
+
catch (UnauthorizedAccessException)
|
|
1066
|
+
{
|
|
1067
|
+
if (StartupReadOnlyExtras(descriptor, userSid)) Warnings.Add(full);
|
|
1068
|
+
else
|
|
1069
|
+
{
|
|
1070
|
+
if (!allowRepair) throw new UnauthorizedAccessException();
|
|
1071
|
+
using (StartupProfileBoundary boundary = new StartupProfileBoundary(full))
|
|
1072
|
+
{
|
|
1073
|
+
if (!boundary.CanRepair) { OutsideProfile.Add(full); }
|
|
1074
|
+
else
|
|
1075
|
+
{
|
|
1076
|
+
using (SafeFileHandle mutation = OpenShared(full, READ_CONTROL | WRITE_DAC | 0x80,
|
|
1077
|
+
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT))
|
|
1078
|
+
{
|
|
1079
|
+
VerifyReopenedIdentity(mutation, true, identity);
|
|
1080
|
+
VerifyHandlePath(mutation, full);
|
|
1081
|
+
VerifyReopenedIdentity(handle, true, identity);
|
|
1082
|
+
RawSecurityDescriptor current = ReadAccessDescriptor(mutation);
|
|
1083
|
+
if (current.Owner == null || current.Owner.Value != new SecurityIdentifier(userSid).Value)
|
|
1084
|
+
throw new UnauthorizedAccessException();
|
|
1085
|
+
// A concurrent safe repair needs no second write.
|
|
1086
|
+
try { VerifyExactDacl(mutation, userSid, true, current.Owner.Value); }
|
|
1087
|
+
catch (UnauthorizedAccessException)
|
|
1088
|
+
{
|
|
1089
|
+
if (StartupReadOnlyExtras(current, userSid)) Warnings.Add(full);
|
|
1090
|
+
else
|
|
1091
|
+
{
|
|
1092
|
+
SetExactDirectoryDacl(mutation, userSid, true);
|
|
1093
|
+
VerifyExactDacl(mutation, userSid, true, current.Owner.Value);
|
|
1094
|
+
if (ReadAccessDescriptor(mutation).Owner.Value != current.Owner.Value)
|
|
1095
|
+
throw new UnauthorizedAccessException();
|
|
1096
|
+
Repaired.Add(full);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
VerifyReopenedIdentity(mutation, true, identity);
|
|
1100
|
+
VerifyHandlePath(mutation, full);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
VerifyReopenedIdentity(handle, true, identity);
|
|
1107
|
+
VerifyHandlePath(handle, full);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
|
|
660
1111
|
public static void HardenExisting(string target, string userSid, bool directory)
|
|
661
1112
|
{
|
|
662
|
-
using (SafeFileHandle handle = OpenExisting(target, directory, false))
|
|
1113
|
+
using (SafeFileHandle handle = OpenExisting(target, directory, false, userSid))
|
|
663
1114
|
{
|
|
664
1115
|
ValidateHandle(handle, directory);
|
|
665
1116
|
VerifyHandlePath(handle, target);
|
|
666
|
-
|
|
667
|
-
string owner = ValidateOwner(handle, expectedSids);
|
|
668
|
-
SetExactDacl(handle, userSid, directory);
|
|
669
|
-
VerifyExactDacl(handle, userSid, directory, owner);
|
|
1117
|
+
ApplyExactSecurity(handle, target, userSid, directory);
|
|
670
1118
|
ValidateHandle(handle, directory);
|
|
671
1119
|
VerifyHandlePath(handle, target);
|
|
672
1120
|
}
|
|
@@ -842,9 +1290,7 @@ public static class BlunPrivateAclNative
|
|
|
842
1290
|
{
|
|
843
1291
|
ValidateHandle(handle, directory);
|
|
844
1292
|
VerifyHandlePath(handle, target);
|
|
845
|
-
string owner =
|
|
846
|
-
SetExactDacl(handle, userSid, directory);
|
|
847
|
-
VerifyExactDacl(handle, userSid, directory, owner);
|
|
1293
|
+
string owner = ApplyExactSecurity(handle, target, userSid, directory);
|
|
848
1294
|
ValidateHandle(handle, directory);
|
|
849
1295
|
VerifyHandlePath(handle, target);
|
|
850
1296
|
return owner;
|
|
@@ -870,7 +1316,7 @@ public static class BlunPrivateAclNative
|
|
|
870
1316
|
throw new UnauthorizedAccessException();
|
|
871
1317
|
bool directory = (entry.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
|
872
1318
|
string childPath = TreeChildPath(root, directoryPath, entry.Name);
|
|
873
|
-
SafeFileHandle childHandle = OpenExisting(childPath, directory,
|
|
1319
|
+
SafeFileHandle childHandle = OpenExisting(childPath, directory, true, userSid);
|
|
874
1320
|
try
|
|
875
1321
|
{
|
|
876
1322
|
HeldTreeHandle heldHandle = new HeldTreeHandle();
|
|
@@ -916,7 +1362,7 @@ public static class BlunPrivateAclNative
|
|
|
916
1362
|
List<HeldTreeHandle> heldHandles = new List<HeldTreeHandle>();
|
|
917
1363
|
try
|
|
918
1364
|
{
|
|
919
|
-
SafeFileHandle rootHandle = OpenExisting(root, true,
|
|
1365
|
+
SafeFileHandle rootHandle = OpenExisting(root, true, true, userSid);
|
|
920
1366
|
HeldTreeHandle heldRoot = new HeldTreeHandle();
|
|
921
1367
|
heldRoot.Handle = rootHandle;
|
|
922
1368
|
heldRoot.Path = root;
|
|
@@ -964,6 +1410,7 @@ public static class BlunPrivateAclNative
|
|
|
964
1410
|
|
|
965
1411
|
private static SafeFileHandle OpenForWrite(string target, string userSid)
|
|
966
1412
|
{
|
|
1413
|
+
CurrentTarget = target;
|
|
967
1414
|
IntPtr descriptor = CreateExactDescriptor(userSid, false);
|
|
968
1415
|
try
|
|
969
1416
|
{
|
|
@@ -1066,6 +1513,7 @@ const WINDOWS_ACL_CSHARP_GZIP = gzipSync(
|
|
|
1066
1513
|
const WINDOWS_ACL_SCRIPT = [
|
|
1067
1514
|
"$ErrorActionPreference = 'Stop'",
|
|
1068
1515
|
"$ProgressPreference = 'SilentlyContinue'",
|
|
1516
|
+
"$phase='powershell-bootstrap'",
|
|
1069
1517
|
'try {',
|
|
1070
1518
|
'Set-StrictMode -Version 3',
|
|
1071
1519
|
"$target=[Environment]::GetEnvironmentVariable('BLUN_PRIVATE_ACL_TARGET','Process')",
|
|
@@ -1073,7 +1521,7 @@ const WINDOWS_ACL_SCRIPT = [
|
|
|
1073
1521
|
"$sid=[Environment]::GetEnvironmentVariable('BLUN_PRIVATE_ACL_USER_SID','Process')",
|
|
1074
1522
|
"if ([string]::IsNullOrWhiteSpace($target) -or -not [IO.Path]::IsPathRooted($target)) { throw 'Invalid target.' }",
|
|
1075
1523
|
"if ($kind -ne 'directory' -and $kind -ne 'file' -and $kind -ne 'file-write' -and $kind -ne 'tree') { throw 'Invalid kind.' }",
|
|
1076
|
-
|
|
1524
|
+
'$bytes=[Convert]::FromBase64String($env:BLUN_PRIVATE_ACL_NATIVE_CSHARP)',
|
|
1077
1525
|
'$zipin=[IO.MemoryStream]::new($bytes)',
|
|
1078
1526
|
'$gzip=[IO.Compression.GZipStream]::new($zipin,[IO.Compression.CompressionMode]::Decompress)',
|
|
1079
1527
|
'$reader=[IO.StreamReader]::new($gzip,[Text.Encoding]::UTF8)',
|
|
@@ -1085,7 +1533,9 @@ const WINDOWS_ACL_SCRIPT = [
|
|
|
1085
1533
|
'$zipin.Dispose()',
|
|
1086
1534
|
'[Array]::Clear($bytes,0,$bytes.Length)',
|
|
1087
1535
|
'}',
|
|
1536
|
+
"$phase='native-compile'",
|
|
1088
1537
|
'$null=Add-Type -TypeDefinition $code -Language CSharp',
|
|
1538
|
+
"$phase='native-dispatch'",
|
|
1089
1539
|
"if ($kind -eq 'directory') {",
|
|
1090
1540
|
'[BlunPrivateAclNative]::EnsurePrivateDirectory($target,$sid)',
|
|
1091
1541
|
"} elseif ($kind -eq 'file') {",
|
|
@@ -1106,9 +1556,29 @@ const WINDOWS_ACL_SCRIPT = [
|
|
|
1106
1556
|
'}',
|
|
1107
1557
|
'}',
|
|
1108
1558
|
"[Console]::Out.Write('BLUN_PRIVATE_ACL_OK_V1')",
|
|
1559
|
+
'foreach ($warning in [BlunPrivateAclNative]::Warnings) {',
|
|
1560
|
+
"[Console]::Out.Write(('`nBLUN_PRIVATE_ACL_LOCK_EXACT:' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($warning))).Replace('`n',[Environment]::NewLine))",
|
|
1561
|
+
'}',
|
|
1109
1562
|
'exit 0',
|
|
1110
1563
|
'} catch {',
|
|
1111
|
-
"
|
|
1564
|
+
"$safePhase=$phase",
|
|
1565
|
+
"if ($phase -eq 'native-dispatch') { $safePhase=[BlunPrivateAclNative]::CurrentPhase }",
|
|
1566
|
+
'$nativeCode=0',
|
|
1567
|
+
"$reason='unknown'",
|
|
1568
|
+
'$failure=$_.Exception',
|
|
1569
|
+
'for ($depth=0; $depth -lt 8 -and $null -ne $failure; $depth++) {',
|
|
1570
|
+
"if ($failure -is [ComponentModel.Win32Exception]) { $nativeCode=$failure.NativeErrorCode; $reason='native-error'; break }",
|
|
1571
|
+
"if ($failure -is [UnauthorizedAccessException]) { $reason='access-denied'; break }",
|
|
1572
|
+
"if ($failure -is [IO.IOException]) { $reason='io-error'; break }",
|
|
1573
|
+
"if ($failure -is [ArgumentException]) { $reason='argument-error'; break }",
|
|
1574
|
+
'$failure=$failure.InnerException',
|
|
1575
|
+
'}',
|
|
1576
|
+
"if ($phase -eq 'native-dispatch') {",
|
|
1577
|
+
"$errorTarget=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([BlunPrivateAclNative]::CurrentTarget))",
|
|
1578
|
+
"[Console]::Error.Write(('BLUN_PRIVATE_ACL_ERROR_V4:{0}:{1}:{2}:{3}' -f $safePhase,$nativeCode,$reason,$errorTarget))",
|
|
1579
|
+
'} else {',
|
|
1580
|
+
"[Console]::Error.Write(('BLUN_PRIVATE_ACL_ERROR_V3:{0}:{1}:{2}' -f $safePhase,$nativeCode,$reason))",
|
|
1581
|
+
'}',
|
|
1112
1582
|
'exit 1',
|
|
1113
1583
|
'}',
|
|
1114
1584
|
].join('\n');
|
|
@@ -1163,6 +1633,50 @@ function framedPrivateContents(contents) {
|
|
|
1163
1633
|
}
|
|
1164
1634
|
}
|
|
1165
1635
|
|
|
1636
|
+
// Internal structured diagnostics only. Keep the existing public/catalog message.
|
|
1637
|
+
// Never retain raw child exceptions, stderr, environment or file contents.
|
|
1638
|
+
const WINDOWS_PRIVATE_ACL_PHASES = new Set([
|
|
1639
|
+
'powershell-bootstrap', 'native-compile', 'native-dispatch', 'directory-open',
|
|
1640
|
+
'entry-open', 'entry-validation', 'path-verification', 'owner-verification', 'owner-takeover',
|
|
1641
|
+
'dacl-write', 'dacl-verification',
|
|
1642
|
+
]);
|
|
1643
|
+
|
|
1644
|
+
function windowsPrivateAclError(phase, privatePath, operation, nativeErrorCode, reason) {
|
|
1645
|
+
const code = `BLUN_PRIVATE_ACL_${phase.replaceAll('-', '_').toUpperCase()}`;
|
|
1646
|
+
const error = new Error(`Windows private ACL hardening or verification failed. [${code}${reason && reason !== 'unknown' ? `; ${reason.toUpperCase().replaceAll('-', '_')}` : ''}]${privatePath === undefined ? '' : ` ${privatePath}`}${nativeErrorCode ? ` (${nativeErrorCode})` : ''}`);
|
|
1647
|
+
error.code = code;
|
|
1648
|
+
if (privatePath !== undefined) error.privatePath = privatePath;
|
|
1649
|
+
if (operation !== undefined) error.operation = operation;
|
|
1650
|
+
if (reason && reason !== 'unknown') error.reasonCode = reason.replaceAll('-', '_').toUpperCase();
|
|
1651
|
+
if (nativeErrorCode !== undefined && nativeErrorCode !== 0) error.nativeErrorCode = nativeErrorCode;
|
|
1652
|
+
return error;
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
function windowsPrivateAclHostError(failure, privatePath, operation, userSid) {
|
|
1656
|
+
const stderr = typeof failure?.stderr === 'string' ? failure.stderr : '';
|
|
1657
|
+
const takeover = /^BLUN_PRIVATE_ACL_ERROR_V4:([a-z-]+):([0-9]{1,5}):(native-error|access-denied|io-error|argument-error|unknown):([A-Za-z0-9+/=]{1,24000})$/u.exec(stderr);
|
|
1658
|
+
if (takeover && WINDOWS_PRIVATE_ACL_PHASES.has(takeover[1]) && Number(takeover[2]) <= 65535) {
|
|
1659
|
+
const target = Buffer.from(takeover[4], 'base64').toString('utf8');
|
|
1660
|
+
const prefix = privatePath.replace(/[\\/]+$/u, '') + path.sep;
|
|
1661
|
+
if ((target === privatePath || (operation === 'tree' && target.startsWith(prefix)))
|
|
1662
|
+
&& !/[\x00-\x1f"]/u.test(target)) {
|
|
1663
|
+
const error = windowsPrivateAclError(takeover[1], target, operation, Number(takeover[2]), takeover[3]);
|
|
1664
|
+
if (takeover[1] !== 'owner-takeover') return error;
|
|
1665
|
+
error.nextStep = `icacls "${target}" /setowner *${userSid}`;
|
|
1666
|
+
error.requiredAccess = 'WRITE_OWNER';
|
|
1667
|
+
error.message = `[${error.code}] ${target}; WRITE_OWNER; ${error.nextStep}${error.nativeErrorCode ? ` (${error.nativeErrorCode})` : ''}`;
|
|
1668
|
+
return error;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
const match = /^BLUN_PRIVATE_ACL_ERROR_V(2|3):([a-z-]+):([0-9]{1,5})(?::([a-z-]+))?$/u.exec(stderr);
|
|
1672
|
+
const reasons = new Set(['unknown', 'native-error', 'access-denied', 'io-error', 'argument-error']);
|
|
1673
|
+
if (match && WINDOWS_PRIVATE_ACL_PHASES.has(match[2]) && Number(match[3]) <= 65535
|
|
1674
|
+
&& (match[1] === '2' ? match[4] === undefined : reasons.has(match[4]))) {
|
|
1675
|
+
return windowsPrivateAclError(match[2], privatePath, operation, Number(match[3]), match[4]);
|
|
1676
|
+
}
|
|
1677
|
+
return windowsPrivateAclError('host-execution', privatePath, operation);
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1166
1680
|
function resolveWindowsPrivateTarget(targetPath) {
|
|
1167
1681
|
if (process.platform !== 'win32') return path.resolve(targetPath);
|
|
1168
1682
|
try {
|
|
@@ -1191,10 +1705,25 @@ function resolveWindowsPrivateTarget(targetPath) {
|
|
|
1191
1705
|
}
|
|
1192
1706
|
return absoluteTarget;
|
|
1193
1707
|
} catch {
|
|
1194
|
-
throw
|
|
1708
|
+
throw windowsPrivateAclError('target-validation');
|
|
1195
1709
|
}
|
|
1196
1710
|
}
|
|
1197
1711
|
|
|
1712
|
+
function existingTimeoutDirectory(target) {
|
|
1713
|
+
try { return checkedTimeoutDirectory(target); }
|
|
1714
|
+
catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
function checkedTimeoutDirectory(target, expected) {
|
|
1718
|
+
const stat = fs.lstatSync(target);
|
|
1719
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()
|
|
1720
|
+
|| path.resolve(fs.realpathSync(target)).toLowerCase() !== path.resolve(target).toLowerCase()
|
|
1721
|
+
|| (expected && !sameFileIdentity(expected, stat))) {
|
|
1722
|
+
throw windowsPrivateAclError('target-validation', target, 'directory');
|
|
1723
|
+
}
|
|
1724
|
+
return stat;
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1198
1727
|
function windowsAclController(options) {
|
|
1199
1728
|
const systemDirectory = windowsSystemDirectory(options);
|
|
1200
1729
|
const hostEnvironment = windowsHostEnvironment(systemDirectory);
|
|
@@ -1218,31 +1747,44 @@ function windowsAclController(options) {
|
|
|
1218
1747
|
hostEnvironment,
|
|
1219
1748
|
);
|
|
1220
1749
|
} catch {
|
|
1221
|
-
throw new Error('Cannot determine the current Windows user SID for private launcher paths.');
|
|
1750
|
+
throw Object.assign(new Error('Cannot determine the current Windows user SID for private launcher paths.'), { code: 'BLUN_PRIVATE_ACL_SID_RESOLUTION' });
|
|
1222
1751
|
}
|
|
1223
1752
|
const sids = [...new Set(String(output).match(WINDOWS_SID_PATTERN) || [])];
|
|
1224
1753
|
if (sids.length !== 1) {
|
|
1225
|
-
throw new Error('Cannot determine the current Windows user SID for private launcher paths.');
|
|
1754
|
+
throw Object.assign(new Error('Cannot determine the current Windows user SID for private launcher paths.'), { code: 'BLUN_PRIVATE_ACL_SID_RESOLUTION' });
|
|
1226
1755
|
}
|
|
1227
1756
|
userSid = sids[0].toUpperCase();
|
|
1228
1757
|
return userSid;
|
|
1229
1758
|
};
|
|
1230
1759
|
|
|
1231
1760
|
const invoke = (targetPath, kind, input) => {
|
|
1761
|
+
let temporary;
|
|
1762
|
+
let primaryFailure;
|
|
1232
1763
|
try {
|
|
1233
1764
|
const absoluteTarget = resolveWindowsPrivateTarget(targetPath);
|
|
1234
1765
|
const root = path.parse(absoluteTarget).root;
|
|
1235
1766
|
if (!path.isAbsolute(absoluteTarget)
|
|
1236
1767
|
|| root.toLowerCase() === absoluteTarget.toLowerCase()
|
|
1237
1768
|
|| !['directory', 'file', 'file-write', 'tree'].includes(kind)) {
|
|
1238
|
-
throw
|
|
1769
|
+
throw windowsPrivateAclError('target-validation');
|
|
1239
1770
|
}
|
|
1771
|
+
const sid = currentUserSid();
|
|
1772
|
+
temporary = (options.createPrivateTempImpl || createWindowsPrivateTemp)({
|
|
1773
|
+
systemDirectory, userSid: sid, resolveTarget: resolveWindowsPrivateTarget,
|
|
1774
|
+
tempRoot: options.tempRoot, privateTempRoot: options.privateTempRoot,
|
|
1775
|
+
warn: options.onWarning, execute: options.execFileSyncImpl || execFileSync,
|
|
1776
|
+
});
|
|
1240
1777
|
const env = {
|
|
1241
1778
|
...hostEnvironment,
|
|
1779
|
+
TEMP: temporary.path,
|
|
1780
|
+
TMP: temporary.path,
|
|
1242
1781
|
BLUN_PRIVATE_ACL_KIND: kind,
|
|
1243
1782
|
BLUN_PRIVATE_ACL_TARGET: absoluteTarget,
|
|
1244
|
-
BLUN_PRIVATE_ACL_USER_SID:
|
|
1783
|
+
BLUN_PRIVATE_ACL_USER_SID: sid,
|
|
1784
|
+
BLUN_PRIVATE_ACL_NATIVE_CSHARP: WINDOWS_ACL_CSHARP_GZIP,
|
|
1245
1785
|
};
|
|
1786
|
+
const beforeTimeout = kind === 'directory' && process.platform === 'win32'
|
|
1787
|
+
? existingTimeoutDirectory(absoluteTarget) : undefined;
|
|
1246
1788
|
let output;
|
|
1247
1789
|
try {
|
|
1248
1790
|
output = runWindowsCommand(
|
|
@@ -1253,14 +1795,40 @@ function windowsAclController(options) {
|
|
|
1253
1795
|
env,
|
|
1254
1796
|
input,
|
|
1255
1797
|
);
|
|
1256
|
-
} catch {
|
|
1257
|
-
|
|
1798
|
+
} catch (failure) {
|
|
1799
|
+
const error = windowsPrivateAclHostError(failure, absoluteTarget, kind, sid);
|
|
1800
|
+
throw error;
|
|
1801
|
+
}
|
|
1802
|
+
const lines = String(output).split(/\r?\n/u);
|
|
1803
|
+
if (lines.shift() !== WINDOWS_ACL_OK_SENTINEL) {
|
|
1804
|
+
throw windowsPrivateAclError('result-protocol', absoluteTarget, kind);
|
|
1258
1805
|
}
|
|
1259
|
-
|
|
1260
|
-
|
|
1806
|
+
for (const line of lines) {
|
|
1807
|
+
const match = /^BLUN_PRIVATE_ACL_LOCK_EXACT:([A-Za-z0-9+/=]+)$/u.exec(line);
|
|
1808
|
+
if (!match) throw windowsPrivateAclError('result-protocol', absoluteTarget, kind);
|
|
1809
|
+
const lockedPath = Buffer.from(match[1], 'base64').toString('utf8');
|
|
1810
|
+
if (lockedPath !== absoluteTarget && !(kind === 'tree' && lockedPath.startsWith(absoluteTarget + path.sep))) {
|
|
1811
|
+
throw windowsPrivateAclError('result-protocol', absoluteTarget, kind);
|
|
1812
|
+
}
|
|
1813
|
+
const warning = windowsPrivateAclError('lock-exact', lockedPath, kind);
|
|
1814
|
+
if (options.onWarning) options.onWarning(warning);
|
|
1815
|
+
else process.emitWarning(warning.message, { code: warning.code });
|
|
1261
1816
|
}
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
primaryFailure = error;
|
|
1819
|
+
throw error;
|
|
1262
1820
|
} finally {
|
|
1263
1821
|
input?.fill(0);
|
|
1822
|
+
if (temporary) {
|
|
1823
|
+
try { temporary.dispose(); } catch (cleanupFailure) {
|
|
1824
|
+
if (primaryFailure) {
|
|
1825
|
+
primaryFailure.cleanupCode = 'BLUN_PRIVATE_ACL_TEMP_CLEANUP';
|
|
1826
|
+
} else {
|
|
1827
|
+
if (typeof cleanupFailure?.code === 'string' && cleanupFailure.code.startsWith('BLUN_PRIVATE_ACL_TEMP_')) throw cleanupFailure;
|
|
1828
|
+
throw windowsPrivateAclError('temp-cleanup', temporary.path, kind);
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1264
1832
|
}
|
|
1265
1833
|
};
|
|
1266
1834
|
|
|
@@ -1596,7 +2164,20 @@ function securePrivateTree(targetPath, options = {}) {
|
|
|
1596
2164
|
securePosixPrivateTree(targetPath, fsImpl, options);
|
|
1597
2165
|
}
|
|
1598
2166
|
|
|
2167
|
+
function createStartupSecurity(options = {}) {
|
|
2168
|
+
return require('./startup-security.cjs').createStartupSecurity({
|
|
2169
|
+
...options, nativeCode: WINDOWS_ACL_CSHARP_GZIP,
|
|
2170
|
+
resolveTarget: resolveWindowsPrivateTarget,
|
|
2171
|
+
nativeError: windowsPrivateAclError,
|
|
2172
|
+
allowedPhases: WINDOWS_PRIVATE_ACL_PHASES,
|
|
2173
|
+
systemDirectory: (options.platform || process.platform) === 'win32'
|
|
2174
|
+
? windowsSystemDirectory(options) : undefined,
|
|
2175
|
+
posix: { ensurePrivateDirectory, securePrivateFile, writePrivateFile },
|
|
2176
|
+
});
|
|
2177
|
+
}
|
|
2178
|
+
|
|
1599
2179
|
module.exports = {
|
|
2180
|
+
createStartupSecurity,
|
|
1600
2181
|
PRIVATE_DIRECTORY_MODE,
|
|
1601
2182
|
PRIVATE_FILE_MODE,
|
|
1602
2183
|
ensurePrivateDirectory,
|