team-ljyzipelo

공개
145줄7.3 KB
1using System.Runtime.InteropServices;
2using System.Security.AccessControl;
3using System.Security.Principal;
4using System.Text;
5using Microsoft.Win32.SafeHandles;
6using Zipelo.Core;
7
8namespace Zipelo.Runtime;
9
10internal static class WindowsFolderGuard
11{
12 internal static void RequireNtfs(SafeFileHandle handle)
13 {
14 var name = new StringBuilder(32);
15 if (!GetVolumeInformationByHandleW(handle, null, 0, out _, out _, out _, name, name.Capacity))
16 {
17 ThrowLast("GetVolumeInformationByHandleW");
18 }
19 if (name.ToString() != "NTFS") { throw new ArchiveException(ArchiveError.OutputUnavailable); }
20 }
21
22 internal static string Inspect(SafeFileHandle handle, bool directory)
23 {
24 var attributes = Query(handle, 9, 8);
25 var flags = BitConverter.ToUInt32(attributes, 0);
26 if ((flags & 0x400) != 0 || ((flags & 0x10) != 0) != directory)
27 {
28 throw new ArchiveException(ArchiveError.UnsafePath);
29 }
30 var standard = Query(handle, 1, 24);
31 if (standard[20] != 0 || (!directory && BitConverter.ToUInt32(standard, 16) != 1))
32 {
33 throw new ArchiveException(ArchiveError.UnsafePath);
34 }
35 RequirePrivateWriters(handle);
36 return Convert.ToHexString(Query(handle, 18, 24));
37 }
38
39 internal static void RequirePrivateWriters(SafeFileHandle handle)
40 {
41 if (!OperatingSystem.IsWindows()) { throw new PlatformNotSupportedException(); }
42 var error = GetSecurityInfo(handle, 1, 5, out _, out _, out _, out _, out var descriptor);
43 if (error != 0) { throw Native("GetSecurityInfo", error); }
44 try
45 {
46 var bytes = new byte[checked((int)GetSecurityDescriptorLength(descriptor))];
47 Marshal.Copy(descriptor, bytes, 0, bytes.Length);
48 var security = new RawSecurityDescriptor(bytes, 0);
49 using var identity = WindowsIdentity.GetCurrent();
50 var trusted = new HashSet<string>(StringComparer.Ordinal) { "S-1-5-18", "S-1-5-32-544" };
51 if (identity.User is { } user) { trusted.Add(user.Value); }
52 if (security.Owner is null || !trusted.Contains(security.Owner.Value) || security.DiscretionaryAcl is null)
53 {
54 throw new ArchiveException(ArchiveError.OutputUnavailable);
55 }
56 foreach (GenericAce ace in security.DiscretionaryAcl)
57 {
58 if (ace is not CommonAce common || common.IsCallback)
59 {
60 throw new ArchiveException(ArchiveError.OutputUnavailable);
61 }
62 if (common.AceQualifier == AceQualifier.AccessDenied) { continue; }
63 if (common.AceQualifier != AceQualifier.AccessAllowed) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
64 // 알 수 없는 쓰기 권한과 상속 전용 쓰기 ACE도 보수적으로 거부함.
65 const uint mutation = 0x520D0156;
66 if ((unchecked((uint)common.AccessMask) & mutation) == 0 || trusted.Contains(common.SecurityIdentifier.Value)) { continue; }
67 if ((common.AceFlags & AceFlags.InheritOnly) != 0 &&
68 common.SecurityIdentifier.IsWellKnown(WellKnownSidType.CreatorOwnerSid)) { continue; }
69 throw new ArchiveException(ArchiveError.OutputUnavailable);
70 }
71 }
72 finally { LocalFree(descriptor); }
73 }
74
75 internal static void VerifyChildren(SafeFileHandle directory, IReadOnlyCollection<string> names)
76 {
77 var remaining = new HashSet<string>(names, StringComparer.OrdinalIgnoreCase);
78 var buffer = Marshal.AllocHGlobal(65536);
79 try
80 {
81 var restart = true;
82 while (true)
83 {
84 var status = NtQueryDirectoryFile(directory, 0, 0, 0, out var io, buffer, 65536, 12, false, 0, restart);
85 restart = false;
86 if (status == unchecked((int)0x80000006)) { break; }
87 if (status != 0) { throw Native("NtQueryDirectoryFile", RtlNtStatusToDosError(status), status); }
88 var length = checked((int)io.Information);
89 var offset = 0;
90 do
91 {
92 if (offset < 0 || offset > length - 12) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
93 var next = Marshal.ReadInt32(buffer, offset);
94 var size = Marshal.ReadInt32(buffer, offset + 8);
95 if (size < 0 || size % 2 != 0 || size > length - offset - 12)
96 {
97 throw new ArchiveException(ArchiveError.OutputUnavailable);
98 }
99 var name = Marshal.PtrToStringUni(buffer + offset + 12, size / 2)!;
100 if (name is not ("." or "..") && !remaining.Remove(name)) { throw new ArchiveException(ArchiveError.UnsafePath); }
101 if (next == 0) { break; }
102 if (next < 12 + size) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
103 offset = checked(offset + next);
104 } while (true);
105 }
106 if (remaining.Count != 0) { throw new ArchiveException(ArchiveError.UnsafePath); }
107 }
108 finally { Marshal.FreeHGlobal(buffer); }
109 }
110
111 private static byte[] Query(SafeFileHandle handle, int kind, int size)
112 {
113 var bytes = new byte[size];
114 if (!GetFileInformationByHandleEx(handle, kind, bytes, (uint)size)) { ThrowLast("GetFileInformationByHandleEx"); }
115 return bytes;
116 }
117
118 private static void ThrowLast(string operation) => throw Native(operation, unchecked((uint)Marshal.GetLastPInvokeError()));
119 private static PublicationNativeException Native(string operation, uint error, int? status = null)
120 => new(ArchiveError.OutputUnavailable, new(operation, error, status));
121
122 [StructLayout(LayoutKind.Sequential)]
123 private struct IoStatusBlock { internal nint Status; internal nuint Information; }
124
125 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
126 [return: MarshalAs(UnmanagedType.Bool)]
127 private static extern bool GetVolumeInformationByHandleW(SafeFileHandle handle, StringBuilder? volume, int volumeSize,
128 out uint serial, out uint maximumComponent, out uint flags, StringBuilder fileSystem, int fileSystemSize);
129 [DllImport("kernel32.dll", SetLastError = true)]
130 [return: MarshalAs(UnmanagedType.Bool)]
131 private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, [Out] byte[] information, uint size);
132 [DllImport("advapi32.dll")]
133 private static extern uint GetSecurityInfo(SafeFileHandle handle, int kind, uint information,
134 out nint owner, out nint group, out nint dacl, out nint sacl, out nint descriptor);
135 [DllImport("advapi32.dll")]
136 private static extern uint GetSecurityDescriptorLength(nint descriptor);
137 [DllImport("kernel32.dll")]
138 private static extern nint LocalFree(nint memory);
139 [DllImport("ntdll.dll")]
140 private static extern int NtQueryDirectoryFile(SafeFileHandle handle, nint completionEvent, nint routine, nint context,
141 out IoStatusBlock status, nint buffer, uint length, int kind, [MarshalAs(UnmanagedType.U1)] bool single,
142 nint filter, [MarshalAs(UnmanagedType.U1)] bool restart);
143 [DllImport("ntdll.dll")]
144 private static extern uint RtlNtStatusToDosError(int status);
145}