team-ljyzipelo

공개
116줄6.1 KB
1using System.Runtime.InteropServices;
2using System.Runtime.Versioning;
3using System.Security.AccessControl;
4using System.Security.Principal;
5using Zipelo.Core;
6using Zipelo.SecurityTests;
7
8namespace Zipelo.RuntimeTests;
9
10internal sealed record FolderEnvironment(ArchiveError? Rejection, string Description)
11{
12 internal static FolderEnvironment Inspect(string newlyCreatedParent)
13 {
14 if (RuntimeInformation.ProcessArchitecture != Architecture.X64)
15 {
16 return Closed("x64 이외 아키텍처");
17 }
18 if (OperatingSystem.IsWindows()) { return Windows(newlyCreatedParent); }
19 if (OperatingSystem.IsLinux()) { return Linux(newlyCreatedParent); }
20 return Closed("Windows/Linux 이외 OS");
21 }
22
23 [SupportedOSPlatform("linux")]
24 private static FolderEnvironment Linux(string parent)
25 {
26 // 별도 경로 관찰로 기대 조건을 정하며 제품 게시 결과로 SKIP 여부를 정하지 않음.
27 var buffer = new byte[256];
28 Check.Equal(0, Statfs(parent, buffer));
29 var magic = BitConverter.ToInt64(buffer, 0);
30 var expectedType = magic switch { 0xEF53 => "ext4", 0x58465342 => "xfs", _ => null };
31 if (expectedType is null) { return Closed($"Linux 미지원 파일시스템 0x{magic:X}"); }
32 var status = new byte[256];
33 if (Statx(-100, parent, 0x100, 0x17FF, status) != 0 ||
34 (BitConverter.ToUInt32(status, 0) & 0x100A) != 0x100A)
35 {
36 return Closed("Linux mount ID/소유자/모드 조회 불가");
37 }
38 var mountId = BitConverter.ToUInt64(status, 144);
39 var device = FormattableString.Invariant($"{BitConverter.ToUInt32(status, 136)}:{BitConverter.ToUInt32(status, 140)}");
40 string content;
41 try { content = File.ReadAllText("/proc/thread-self/mountinfo"); }
42 catch (IOException) { return Closed("Linux mountinfo 조회 불가"); }
43 catch (UnauthorizedAccessException) { return Closed("Linux mountinfo 읽기 권한 없음"); }
44 var matching = content.Split('\n', StringSplitOptions.RemoveEmptyEntries)
45 .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
46 .Where(parts => parts.Length > 0 && ulong.TryParse(parts[0], out var id) && id == mountId).ToArray();
47 if (matching.Length != 1) { return Closed("Linux mountinfo 레코드 누락 또는 중복"); }
48 var fields = matching[0];
49 var separator = Array.IndexOf(fields, "-");
50 if (separator < 6 || fields.Length != separator + 4 || fields[2] != device || fields[separator + 1] != expectedType)
51 {
52 return Closed("Linux mount ID/장치/파일시스템 유형 불일치");
53 }
54 var mode = BitConverter.ToUInt16(status, 28);
55 if (BitConverter.ToUInt32(status, 20) != GetEffectiveUser() || (mode & 0x12) != 0)
56 {
57 return Closed("Linux 부모 소유자 또는 그룹/기타 쓰기 조건 불충족");
58 }
59 return new(null, $"Linux {expectedType}, mount ID/장치 일치, 현재 UID 소유, 그룹 및 기타 쓰기 없음");
60 }
61
62 [SupportedOSPlatform("windows")]
63 private static FolderEnvironment Windows(string parent)
64 {
65 var drive = new DriveInfo(Path.GetPathRoot(parent) ?? throw new InvalidOperationException());
66 if (parent.StartsWith(@"\\", StringComparison.Ordinal))
67 {
68 return new(ArchiveError.UnsafePath, "Windows 네트워크 경로");
69 }
70 if (drive.DriveType is not (DriveType.Fixed or DriveType.Removable))
71 {
72 return Closed("Windows 로컬 고정/이동식 드라이브 이외 유형");
73 }
74 if (!string.Equals(drive.DriveFormat, "NTFS", StringComparison.OrdinalIgnoreCase))
75 {
76 return Closed("Windows 미지원 파일시스템 " + drive.DriveFormat);
77 }
78 var security = new DirectoryInfo(parent).GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access);
79 var descriptor = new RawSecurityDescriptor(security.GetSecurityDescriptorBinaryForm(), 0);
80 using var identity = WindowsIdentity.GetCurrent();
81 var trusted = new HashSet<string>(StringComparer.Ordinal) { "S-1-5-18", "S-1-5-32-544" };
82 if (identity.User is { } user) { trusted.Add(user.Value); }
83 if (descriptor.Owner is null || !trusted.Contains(descriptor.Owner.Value) || descriptor.DiscretionaryAcl is null)
84 {
85 return Closed("NTFS 부모 소유자 또는 DACL 조건 불충족");
86 }
87 const FileSystemRights mutation = FileSystemRights.Write | FileSystemRights.Delete |
88 FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership;
89 foreach (GenericAce entry in descriptor.DiscretionaryAcl)
90 {
91 if (entry is not CommonAce ace || ace.IsCallback)
92 {
93 return Closed("NTFS 부모의 미지원 ACE");
94 }
95 if (ace.AceQualifier == AceQualifier.AccessDenied) { continue; }
96 if (ace.AceQualifier != AceQualifier.AccessAllowed) { return Closed("NTFS 부모의 미지원 ACE 유형"); }
97 var writes = (ace.AccessMask & (int)mutation) != 0 || (ace.AccessMask & 0x52000000) != 0;
98 if (!writes || trusted.Contains(ace.SecurityIdentifier.Value)) { continue; }
99 if ((ace.AceFlags & AceFlags.InheritOnly) != 0 &&
100 ace.SecurityIdentifier.IsWellKnown(WellKnownSidType.CreatorOwnerSid)) { continue; }
101 return Closed("NTFS 부모의 신뢰 범위 밖 쓰기 ACE");
102 }
103 return new(null, "Windows NTFS, 현재 사용자/SYSTEM/Administrators 쓰기 경계");
104 }
105
106 private static FolderEnvironment Closed(string reason) => new(ArchiveError.OutputUnavailable, reason);
107
108 [DllImport("libc", EntryPoint = "statfs", SetLastError = true)]
109 private static extern int Statfs(string path, [Out] byte[] buffer);
110
111 [DllImport("libc", EntryPoint = "statx", SetLastError = true)]
112 private static extern int Statx(int directory, string path, int flags, uint mask, [Out] byte[] buffer);
113
114 [DllImport("libc", EntryPoint = "geteuid")]
115 private static extern uint GetEffectiveUser();
116}