| 1 | using System.Diagnostics; |
| 2 | using System.Globalization; |
| 3 | using System.Security.AccessControl; |
| 4 | using System.Security.Principal; |
| 5 | using System.Text.Json.Nodes; |
| 6 | using System.Text.RegularExpressions; |
| 7 | |
| 8 | namespace Cage.GuestClipboard; |
| 9 | |
| 10 | |
| 11 | |
| 12 | internal static class WindowsSystemSettings |
| 13 | { |
| 14 | internal static async Task Apply(JsonObject settings,Guid vm,string sid,CancellationToken token) |
| 15 | { |
| 16 | if(settings.Count is not (3 or 4) || settings["action"]?.GetValue<string>()!="apply")throw new InvalidDataException("settings_invalid"); |
| 17 | var iana=settings["timezone"]?.GetValue<string>() ?? "";var locale=settings["locale"]?.GetValue<string>() ?? ""; |
| 18 | if(iana.Length>128 || !TimeZoneInfo.TryConvertIanaIdToWindowsId(iana,out var windowsZone) || |
| 19 | !Regex.IsMatch(windowsZone!,@"^[A-Za-z0-9 ()._+-]+$") || !Regex.IsMatch(locale,@"^[a-zA-Z]{2,3}_[a-zA-Z]{2,3}\.UTF-8$") || !Regex.IsMatch(sid,@"^S-1-5-21-\d+-\d+-\d+-\d+$"))throw new InvalidDataException("settings_invalid"); |
| 20 | var tag=locale[..^6].Replace('_','-');var culture=CultureInfo.GetCultureInfo(tag); |
| 21 | _=TimeZoneInfo.FindSystemTimeZoneById(windowsZone!); |
| 22 | var configPath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Cage Guest Bridge",vm.ToString("D"),"guest-config.json"); |
| 23 | var previous=ProtectedConfig(configPath); |
| 24 | var config=JsonNode.Parse(previous) as JsonObject ?? throw new InvalidDataException("settings_config_invalid"); |
| 25 | if(config["network_mode"]?.GetValue<string>()!="packet")throw new InvalidDataException("settings_config_invalid"); |
| 26 | |
| 27 | |
| 28 | var language=settings.Count==4 ? BrowserLanguage(settings) : BrowserLanguage(new JsonObject{["browser_language"]=config["language"]?.DeepClone()}); |
| 29 | config["timezone"]=iana;config["language"]=language; |
| 30 | |
| 31 | |
| 32 | PublishConfig(configPath,System.Text.Encoding.UTF8.GetBytes(config.ToJsonString())); |
| 33 | var script=$"$ErrorActionPreference='Stop';$key='Registry::HKEY_USERS\\{sid}\\Control Panel\\International';if(!(Test-Path -LiteralPath $key)){{throw 'gui_profile_not_loaded'}};$before=Get-ItemProperty -LiteralPath $key;$zone=(Get-TimeZone).Id;$system=(Get-WinSystemLocale).Name;try{{Set-TimeZone -Id '{windowsZone}';Set-ItemProperty -LiteralPath $key -Name LocaleName -Value '{culture.Name}';Set-ItemProperty -LiteralPath $key -Name Locale -Value '{culture.LCID:X8}';Set-WinSystemLocale -SystemLocale '{culture.Name}'}}catch{{Set-TimeZone -Id $zone;Set-ItemProperty -LiteralPath $key -Name LocaleName -Value $before.LocaleName;Set-ItemProperty -LiteralPath $key -Name Locale -Value $before.Locale;Set-WinSystemLocale -SystemLocale $system;throw}}"; |
| 34 | var start=new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),@"System32\WindowsPowerShell\v1.0\powershell.exe")){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true,CreateNoWindow=true}; |
| 35 | foreach(var argument in new[]{"-NoLogo","-NoProfile","-NonInteractive","-Command","-"})start.ArgumentList.Add(argument); |
| 36 | try |
| 37 | { |
| 38 | using var process=Process.Start(start) ?? throw new InvalidDataException("settings_apply_failed"); |
| 39 | using var cancel=token.Register(()=>{try{process.Kill(true);}catch{}}); |
| 40 | var output=process.StandardOutput.BaseStream.CopyToAsync(Stream.Null,token);var errors=process.StandardError.BaseStream.CopyToAsync(Stream.Null,token); |
| 41 | await process.StandardInput.WriteLineAsync(script);process.StandardInput.Close();await process.WaitForExitAsync(token);await Task.WhenAll(output,errors); |
| 42 | if(process.ExitCode!=0)throw new InvalidDataException("settings_apply_failed"); |
| 43 | } |
| 44 | catch { PublishConfig(configPath,previous);throw; } |
| 45 | } |
| 46 | |
| 47 | internal static string BrowserLanguage(JsonObject settings) |
| 48 | { |
| 49 | var language=settings["browser_language"]?.GetValue<string>() ?? ""; |
| 50 | if(language.Length>128 || !Regex.IsMatch(language,@"^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$"))throw new InvalidDataException("settings_invalid"); |
| 51 | return language; |
| 52 | } |
| 53 | |
| 54 | private static byte[] ProtectedConfig(string path) |
| 55 | { |
| 56 | var file=new FileInfo(path); |
| 57 | for(var directory=file.Directory;directory!=null;directory=directory.Parent) |
| 58 | if(directory.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("settings_config_invalid"); |
| 59 | if(!file.Exists || file.Length is <=0 or >16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("settings_config_invalid"); |
| 60 | var acl=file.GetAccessControl(); |
| 61 | if(acl.GetOwner(typeof(SecurityIdentifier))?.Value is not ("S-1-5-18" or "S-1-5-32-544"))throw new InvalidDataException("settings_config_invalid"); |
| 62 | const FileSystemRights writes=FileSystemRights.WriteData|FileSystemRights.AppendData|FileSystemRights.WriteAttributes|FileSystemRights.WriteExtendedAttributes|FileSystemRights.Delete|FileSystemRights.ChangePermissions|FileSystemRights.TakeOwnership; |
| 63 | foreach(FileSystemAccessRule rule in acl.GetAccessRules(true,true,typeof(SecurityIdentifier))) |
| 64 | if(rule.AccessControlType==AccessControlType.Allow && (rule.FileSystemRights&writes)!=0 && rule.IdentityReference.Value is not ("S-1-5-18" or "S-1-5-32-544"))throw new InvalidDataException("settings_config_invalid"); |
| 65 | using var snapshot=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read|FileShare.Delete); |
| 66 | if(snapshot.Length is <=0 or >16384)throw new InvalidDataException("settings_config_invalid"); |
| 67 | using var data=new MemoryStream();snapshot.CopyTo(data);return data.ToArray(); |
| 68 | } |
| 69 | private static void PublishConfig(string path,byte[] data) |
| 70 | { |
| 71 | var stage=path+"."+Guid.NewGuid().ToString("N")+".part"; |
| 72 | try |
| 73 | { |
| 74 | File.WriteAllBytes(stage,data); |
| 75 | new FileInfo(stage).SetAccessControl(new FileInfo(path).GetAccessControl()); |
| 76 | WindowsFilePublication.Replace(stage,path,default).GetAwaiter().GetResult(); |
| 77 | } |
| 78 | finally { if(File.Exists(stage))File.Delete(stage); } |
| 79 | } |
| 80 | } |