| 1 | using System.ComponentModel; |
| 2 | using System.Diagnostics; |
| 3 | using System.Runtime.InteropServices; |
| 4 | using System.Security.AccessControl; |
| 5 | using System.Security.Cryptography; |
| 6 | using System.Security.Principal; |
| 7 | using Microsoft.Win32; |
| 8 | |
| 9 | namespace Cage.GuestClipboard; |
| 10 | |
| 11 | internal static class SetupAccount |
| 12 | { |
| 13 | [StructLayout(LayoutKind.Sequential)] |
| 14 | private struct UserInfo20 |
| 15 | { |
| 16 | public IntPtr Name, FullName, Comment; |
| 17 | public uint Flags, UserID; |
| 18 | } |
| 19 | |
| 20 | [DllImport("netapi32.dll", CharSet = CharSet.Unicode)] |
| 21 | private static extern uint NetUserGetInfo(string? server, string user, uint level, out IntPtr buffer); |
| 22 | [DllImport("netapi32.dll")] |
| 23 | private static extern uint NetApiBufferFree(IntPtr buffer); |
| 24 | |
| 25 | |
| 26 | |
| 27 | internal static bool? Disabled() |
| 28 | { |
| 29 | uint result = NetUserGetInfo(null, "cagesetup", 20, out var buffer); |
| 30 | try |
| 31 | { |
| 32 | if (result != 0 || buffer == IntPtr.Zero) return null; |
| 33 | return (Marshal.PtrToStructure<UserInfo20>(buffer).Flags & 0x2) != 0; |
| 34 | } |
| 35 | finally { if (buffer != IntPtr.Zero) NetApiBufferFree(buffer); } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | internal static class SessionGuard |
| 40 | { |
| 41 | private static readonly (int Session, SecurityIdentifier? User, bool Unprivileged) ProcessIdentity = ReadProcessIdentity(); |
| 42 | |
| 43 | private static (int Session, SecurityIdentifier? User, bool Unprivileged) ReadProcessIdentity() |
| 44 | { |
| 45 | using var identity = WindowsIdentity.GetCurrent(); |
| 46 | using var process = Process.GetCurrentProcess(); |
| 47 | return (process.SessionId, identity.User, |
| 48 | !identity.IsSystem && !new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)); |
| 49 | } |
| 50 | [DllImport("user32.dll")] static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access); |
| 51 | [DllImport("user32.dll")] static extern bool CloseDesktop(IntPtr desktop); |
| 52 | [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool GetUserObjectInformation(IntPtr handle, int index, char[] value, int bytes, out int needed); |
| 53 | [DllImport("wtsapi32.dll", EntryPoint="WTSQuerySessionInformationW", ExactSpelling=true)] static extern bool WTSQuerySessionInformation(IntPtr server, int session, int field, out IntPtr buffer, out int bytes); |
| 54 | [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr buffer); |
| 55 | [DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token); |
| 56 | [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle); |
| 57 | [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, int pid); |
| 58 | [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user); |
| 59 | [DllImport("advapi32.dll", SetLastError=true)] static extern bool GetTokenInformation(IntPtr token, int field, IntPtr buffer, int size, out int needed); |
| 60 | [DllImport("advapi32.dll")] static extern bool IsWellKnownSid(IntPtr sid, int kind); |
| 61 | [StructLayout(LayoutKind.Sequential)] private struct Group { public IntPtr Sid; public uint Flags; } |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | private static bool InspectToken(IntPtr token, int field, Func<IntPtr, int, bool> inspect) |
| 67 | { |
| 68 | GetTokenInformation(token, field, IntPtr.Zero, 0, out int size); |
| 69 | if (size <= 0 || size > 65536) return false; |
| 70 | var buffer = Marshal.AllocHGlobal(size); |
| 71 | try { return GetTokenInformation(token, field, buffer, size, out var used) && used > 0 && used <= size && inspect(buffer, used); } |
| 72 | finally { Marshal.FreeHGlobal(buffer); } |
| 73 | } |
| 74 | |
| 75 | internal static bool OwnsProcess(Process process) |
| 76 | { |
| 77 | try |
| 78 | { |
| 79 | if (process.HasExited || process.SessionId != ProcessIdentity.Session) return false; |
| 80 | var handle = OpenProcess(0x1000, false, process.Id); |
| 81 | if (handle == IntPtr.Zero) return false; |
| 82 | try |
| 83 | { |
| 84 | if (!GetProcessTimes(handle, out var created, out _, out _, out _) || |
| 85 | created != process.StartTime.ToUniversalTime().ToFileTimeUtc() || !OpenProcessToken(handle, 8, out var token)) return false; |
| 86 | try |
| 87 | { |
| 88 | var user = ProcessIdentity.User; |
| 89 | if (user == null || !InspectToken(token, 1, (p,n) => n >= IntPtr.Size && |
| 90 | user.Equals(new SecurityIdentifier(Marshal.ReadIntPtr(p)))) || |
| 91 | !InspectToken(token, 20, (p,n) => n == sizeof(int) && Marshal.ReadInt32(p) == 0)) return false; |
| 92 | return InspectToken(token, 2, (p,n) => { |
| 93 | var count = Marshal.ReadInt32(p); |
| 94 | var offset = IntPtr.Size; |
| 95 | var stride = Marshal.SizeOf<Group>(); |
| 96 | if (count < 0 || count > (n-offset)/stride) return false; |
| 97 | for (int i=0; i<count; i++) { |
| 98 | var group=Marshal.PtrToStructure<Group>(p+offset+i*stride); |
| 99 | if ((group.Flags & 4) != 0 && (group.Flags & 16) == 0 && IsWellKnownSid(group.Sid,26)) return false; |
| 100 | } |
| 101 | return true; |
| 102 | }); |
| 103 | } |
| 104 | finally { CloseHandle(token); } |
| 105 | } |
| 106 | finally { CloseHandle(handle); } |
| 107 | } |
| 108 | catch { return false; } |
| 109 | } |
| 110 | internal static bool Available() |
| 111 | { |
| 112 | |
| 113 | |
| 114 | if (!Environment.UserInteractive || ProcessIdentity.Session == 0 || !ProcessIdentity.Unprivileged) return false; |
| 115 | int session = ProcessIdentity.Session; |
| 116 | |
| 117 | |
| 118 | if (!WTSQuerySessionInformation(IntPtr.Zero, session, 25, out var state, out int bytes)) return false; |
| 119 | try |
| 120 | { |
| 121 | |
| 122 | |
| 123 | if (state == IntPtr.Zero || bytes < 20 || Marshal.ReadInt32(state) != 1 || |
| 124 | Marshal.ReadInt32(state, 8) != session || Marshal.ReadInt32(state, 12) != 0 || |
| 125 | Marshal.ReadInt32(state, 16) != 1) return false; |
| 126 | } |
| 127 | finally { WTSFreeMemory(state); } |
| 128 | var desktop = OpenInputDesktop(0, false, 1); |
| 129 | if (desktop == IntPtr.Zero) return false; |
| 130 | try { var name = new char[256]; return GetUserObjectInformation(desktop, 2, name, name.Length * 2, out _) && new string(name).TrimEnd('\0') == "Default"; } |
| 131 | finally { CloseDesktop(desktop); } |
| 132 | } |
| 133 | internal static void Assert() { if (!Available()) throw new InvalidOperationException("requires_gui_login"); } |
| 134 | internal static void Target(Guid expected, string sid) |
| 135 | { |
| 136 | using var identity = WindowsIdentity.GetCurrent(); |
| 137 | if (identity.User?.Value != sid || !sid.StartsWith("S-1-5-21-", StringComparison.Ordinal)) throw new InvalidOperationException("gui_identity_mismatch"); |
| 138 | using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters"); |
| 139 | if (!Guid.TryParse(key?.GetValue("VirtualMachineId") as string, out var actual) || actual != expected || actual == Guid.Empty) |
| 140 | throw new InvalidOperationException("guest_identity_mismatch"); |
| 141 | Assert(); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | internal static class Pairing |
| 146 | { |
| 147 | [StructLayout(LayoutKind.Sequential)] struct Blob { internal int Size; internal IntPtr Data; } |
| 148 | [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CryptProtectData(ref Blob input, string? description, ref Blob entropy, IntPtr reserved, IntPtr prompt, uint flags, out Blob output); |
| 149 | [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CryptUnprotectData(ref Blob input, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, uint flags, out Blob output); |
| 150 | [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr memory); |
| 151 | |
| 152 | internal static byte[] Crypt(byte[] data, Guid vm, string sid, bool protect) |
| 153 | { |
| 154 | var entropyBytes = SHA256.HashData(Protocol.Utf8.GetBytes("Cage.HyperV.v1:" + vm.ToString("D") + ":" + sid)); |
| 155 | var input = new Blob { Size = data.Length, Data = Marshal.AllocHGlobal(data.Length) }; |
| 156 | var entropy = new Blob { Size = entropyBytes.Length, Data = Marshal.AllocHGlobal(entropyBytes.Length) }; |
| 157 | Blob output = default; |
| 158 | try |
| 159 | { |
| 160 | Marshal.Copy(data, 0, input.Data, data.Length); Marshal.Copy(entropyBytes, 0, entropy.Data, entropyBytes.Length); |
| 161 | var ok = protect ? CryptProtectData(ref input, "Cage guest pairing", ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output) |
| 162 | : CryptUnprotectData(ref input, IntPtr.Zero, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output); |
| 163 | if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error(), "pairing_unavailable"); |
| 164 | var result = new byte[output.Size]; Marshal.Copy(output.Data, result, 0, result.Length); return result; |
| 165 | } |
| 166 | finally { if (output.Data != IntPtr.Zero) LocalFree(output.Data); Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropy.Data); } |
| 167 | } |
| 168 | |
| 169 | internal static void PrivateFile(string path) |
| 170 | { |
| 171 | var file = new FileInfo(path); |
| 172 | if (!file.Exists || file.Length is < 1 or > 16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("pairing_file_invalid"); |
| 173 | using var identity = WindowsIdentity.GetCurrent(); |
| 174 | var allowed = new HashSet<string> { identity.User!.Value, "S-1-5-18", "S-1-5-32-544" }; |
| 175 | var acl = file.GetAccessControl(); |
| 176 | if (!acl.AreAccessRulesProtected) throw new InvalidDataException("pairing_permissions_invalid"); |
| 177 | foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier))) |
| 178 | if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains(rule.IdentityReference.Value)) throw new InvalidDataException("pairing_permissions_invalid"); |
| 179 | } |
| 180 | |
| 181 | internal static byte[] Load(string path, Guid vm, string sid, bool encrypted) |
| 182 | { |
| 183 | PrivateFile(path); |
| 184 | var bytes = File.ReadAllBytes(path); |
| 185 | var secret = encrypted ? Crypt(bytes, vm, sid, false) : bytes; |
| 186 | if (secret.Length != 32) throw new InvalidDataException("pairing_invalid"); |
| 187 | return secret; |
| 188 | } |
| 189 | |
| 190 | internal static void Protect(string source, string destination, Guid vm, string sid) |
| 191 | { |
| 192 | PrivateFile(source); |
| 193 | var secret = File.ReadAllBytes(source); if (secret.Length != 32) throw new InvalidDataException("pairing_invalid"); |
| 194 | try |
| 195 | { |
| 196 | var encrypted = Crypt(secret, vm, sid, true); |
| 197 | using var file = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None); |
| 198 | var acl = new FileSecurity(); acl.SetAccessRuleProtection(true, false); |
| 199 | using var identity = WindowsIdentity.GetCurrent(); |
| 200 | acl.SetOwner(identity.User!); |
| 201 | foreach (var owner in new[] { identity.User!.Value, "S-1-5-18", "S-1-5-32-544" }) |
| 202 | acl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(owner), FileSystemRights.FullControl, AccessControlType.Allow)); |
| 203 | new FileInfo(destination).SetAccessControl(acl); |
| 204 | file.Write(encrypted); file.Flush(true); |
| 205 | } |
| 206 | finally { CryptographicOperations.ZeroMemory(secret); } |
| 207 | } |
| 208 | } |