| 1 | using System.Reflection; |
| 2 | using System.Runtime.CompilerServices; |
| 3 | using System.Security.AccessControl; |
| 4 | using System.Security.Cryptography; |
| 5 | using System.Security.Principal; |
| 6 | using System.Text; |
| 7 | using System.Text.Json.Nodes; |
| 8 | using System.Text.RegularExpressions; |
| 9 | using System.Diagnostics; |
| 10 | |
| 11 | namespace Cage.GuestClipboard; |
| 12 | |
| 13 | internal static class WindowsCliRpc |
| 14 | { |
| 15 | private static readonly Regex ProfileID = new("^[a-f0-9]{16}$",RegexOptions.CultureInvariant); |
| 16 | private static readonly Regex AccountID = new("^(default|[a-f0-9]{24})$",RegexOptions.CultureInvariant); |
| 17 | private static readonly Regex Subject = new("^[a-f0-9]{64}$",RegexOptions.CultureInvariant); |
| 18 | private static readonly Regex CCSProfile = new("^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$",RegexOptions.CultureInvariant); |
| 19 | private static readonly HashSet<string> Modes=["discover","view","rpc","active","handoff","purge","account-switch","account-switch-cancel"]; |
| 20 | private static readonly object Gate=new(); |
| 21 | private static readonly Dictionary<string,int> Active=new(StringComparer.OrdinalIgnoreCase); |
| 22 | [ModuleInitializer] internal static void Register() |
| 23 | { |
| 24 | if(!GuestOperations.Names.Contains("cli"))return; |
| 25 | try{LoadTools();}catch(Exception){return;} |
| 26 | GuestOperations.Register("cli",Run); |
| 27 | } |
| 28 | private sealed record Tools(string Python,string Claude,string Bash); |
| 29 | private sealed record Layout(string Profile,string Root,string Accounts,string State,string Shared,string Code,Tools Tools); |
| 30 | internal static async Task Run(Stream stream,CancellationToken token,Func<bool> available) |
| 31 | { |
| 32 | if(!available())throw new InvalidDataException("requires_gui_login"); |
| 33 | var request=await Protocol.Read(stream,4<<20,token)??throw new EndOfStreamException(); |
| 34 | var profile=request["profile"]?.GetValue<string>()??""; |
| 35 | if(!ProfileID.IsMatch(profile))throw new InvalidDataException("cli_profile_invalid"); |
| 36 | var layout=Prepare(profile); |
| 37 | var action=request["action"]?.GetValue<string>()??""; |
| 38 | if(action=="terminal") |
| 39 | { |
| 40 | var kind=request["kind"]?.GetValue<string>()??""; |
| 41 | if(kind is not ("claude" or "claude-login"))throw new InvalidDataException("cli_kind_invalid"); |
| 42 | var account=request["account"]?.GetValue<string>()??"default"; |
| 43 | if(!AccountID.IsMatch(account)||kind=="claude-login"&&account=="default")throw new InvalidDataException("cli_account_invalid"); |
| 44 | var directory=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 45 | var open=new JsonObject{["action"]="open",["cols"]=request["cols"]?.DeepClone()??100,["rows"]=request["rows"]?.DeepClone()??30,["workspace"]="home",["shell"]="claude"}; |
| 46 | var arguments=new List<string>{"-X","utf8","-I"}; |
| 47 | var env=EnvironmentFor(layout,account); |
| 48 | using var lease=AccountLease(layout,account); |
| 49 | if(kind=="claude-login")arguments.AddRange([Path.Combine(layout.Code,"cage-claude-account.py"),"login",account]); |
| 50 | else |
| 51 | { |
| 52 | var id=request["project_id"]?.GetValue<string>()??"";var grant=request["grant"]?.GetValue<string>()??""; |
| 53 | directory=ProjectRpc.Resolve(id,grant);open["workspace"]="project";open["project_id"]=id;open["grant"]=grant; |
| 54 | var payload=request["conversation"]?.DeepClone() as JsonObject??throw new InvalidDataException("cli_conversation_invalid"); |
| 55 | Guid.Parse(payload["id"]?.GetValue<string>()??"");Guid.Parse(payload["session_id"]?.GetValue<string>()??""); |
| 56 | ValidatePaths(layout,payload); |
| 57 | var subject=request["subject"]?.GetValue<string>()??""; |
| 58 | if(subject!=""&&!Subject.IsMatch(subject))throw new InvalidDataException("cli_identity_invalid"); |
| 59 | payload["account"]=account;payload["subject"]=subject;payload["prefix"]=new JsonArray(layout.Tools.Claude); |
| 60 | if(request["ccs_profile"] is JsonValue c&&c.TryGetValue<string>(out var ccs)&&ccs!="") |
| 61 | { |
| 62 | if(!CCSProfile.IsMatch(ccs)||account!="default"||subject!="")throw new InvalidDataException("ccs_profile_invalid"); |
| 63 | var tools=LoadCCSTools();env["CAGE_CCS_NODE"]=tools.Node;env["CAGE_CCS_MAIN"]=tools.Main; |
| 64 | env["CAGE_CCS_PRELOAD"]=Path.Combine(layout.Code,"windows_ccs_launch.cjs"); |
| 65 | env["CCS_CLAUDE_PATH"]=layout.Tools.Claude; |
| 66 | env["CCS_DIR"]=Path.Combine(layout.Root,"ccs");env["CCS_HOME"]=Path.Combine(layout.Root,"ccs-home"); |
| 67 | PrivateDirectory(env["CCS_DIR"]);PrivateDirectory(env["CCS_HOME"]);payload["ccs_profile"]=ccs; |
| 68 | } |
| 69 | arguments.AddRange([Path.Combine(layout.Code,"cli_channel.py"),"launch",payload.ToJsonString()]); |
| 70 | } |
| 71 | if(!available())throw new InvalidDataException("requires_gui_login"); |
| 72 | using var prefixed=new PrefixStream(stream,Protocol.Utf8.GetBytes(open.ToJsonString()+"\n")); |
| 73 | await TerminalRpc.RunWithLaunch(prefixed,token,available,new(layout.Tools.Python,arguments.ToArray(),directory,env)); |
| 74 | return; |
| 75 | } |
| 76 | string script;string[] args;JsonNode? input=null;var selected="default"; |
| 77 | if(action=="account") |
| 78 | { |
| 79 | var mode=request["mode"]?.GetValue<string>()??""; |
| 80 | if(mode is not ("snapshot" or "usage" or "quotas"))throw new InvalidDataException("cli_account_operation_invalid"); |
| 81 | selected=request["account"]?.GetValue<string>()??"default"; |
| 82 | if(!AccountID.IsMatch(selected))throw new InvalidDataException("cli_account_invalid"); |
| 83 | args=[mode,selected]; |
| 84 | if(mode=="usage"){var subject=request["subject"]?.GetValue<string>()??"";if(!Subject.IsMatch(subject))throw new InvalidDataException("cli_identity_invalid");args=[mode,selected,subject];} |
| 85 | if(mode=="quotas") |
| 86 | { |
| 87 | var ids=request["ids"] as JsonArray??throw new InvalidDataException("cli_account_invalid"); |
| 88 | if(ids.Count is <1 or >100||ids.Any(x=>!AccountID.IsMatch(x?.GetValue<string>()??"")))throw new InvalidDataException("cli_account_invalid"); |
| 89 | args=[mode,..ids.Select(x=>x!.GetValue<string>())]; |
| 90 | } |
| 91 | script=Path.Combine(layout.Code,"cage-claude-account.py"); |
| 92 | } |
| 93 | else if(action=="channel") |
| 94 | { |
| 95 | var mode=request["mode"]?.GetValue<string>()??"";if(!Modes.Contains(mode))throw new InvalidDataException("cli_channel_operation_invalid"); |
| 96 | input=request["input"]?.DeepClone()??throw new InvalidDataException("cli_channel_input_invalid"); |
| 97 | ValidatePaths(layout,input as JsonObject??throw new InvalidDataException("cli_channel_input_invalid")); |
| 98 | if(input["config"] is JsonValue c&&c.TryGetValue<string>(out var config)&&config!="") |
| 99 | { |
| 100 | var relative=Path.GetRelativePath(layout.Accounts,Path.GetFullPath(config)).Split(Path.DirectorySeparatorChar); |
| 101 | if(relative.Length==2&&AccountID.IsMatch(relative[0])&&relative[0]!="default"&&relative[1]=="config")selected=relative[0]; |
| 102 | } |
| 103 | script=Path.Combine(layout.Code,"cli_channel.py");args=[mode,"-"]; |
| 104 | } |
| 105 | else throw new InvalidDataException("cli_operation_invalid"); |
| 106 | using var accountLease=AccountLease(layout,selected); |
| 107 | var result=await Invoke(layout,selected,script,args,input,token,available); |
| 108 | await Protocol.Write(stream,result,token); |
| 109 | } |
| 110 | private static Layout Prepare(string profile) |
| 111 | { |
| 112 | var tools=LoadTools(); |
| 113 | var root=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),"Cage","CLI",profile); |
| 114 | var accounts=Path.Combine(root,"accounts");var state=Path.Combine(root,"channels");var shared=Path.Combine(root,"shared"); |
| 115 | foreach(var path in new[]{root,accounts,state,shared})PrivateDirectory(path); |
| 116 | string Read(string resource){using var input=Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)??throw new InvalidDataException("cli_helper_missing");using var reader=new StreamReader(input,Protocol.Utf8);return reader.ReadToEnd();} |
| 117 | var files=new Dictionary<string,string>{{"cli_channel.py",Read("Cage.CliChannel")},{"cage-claude-account.py",Read("Cage.CliAccount")},{"windows_cli_platform.py",Read("Cage.CliPlatform")},{"windows_ccs_launch.cjs",Read("Cage.CliCCS")},{"mobile_cli_identity.py",Read("Cage.CliIdentity")},{"cli_channel.resume.md",Read("Cage.CliResume")},{"cli_channel.account-resume.md",Read("Cage.CliAccountResume")}}; |
| 118 | var digest=Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(string.Join("\n",files.Values)))).ToLowerInvariant(); |
| 119 | var code=Path.Combine(root,"code",digest);PrivateDirectory(code); |
| 120 | foreach(var file in files){var path=Path.Combine(code,file.Key);if(!File.Exists(path))File.WriteAllText(path,file.Value,Protocol.Utf8);else if(File.ReadAllText(path,Protocol.Utf8)!=file.Value)throw new InvalidDataException("cli_helper_changed");} |
| 121 | return new(profile,root,accounts,state,shared,code,tools); |
| 122 | } |
| 123 | private static readonly Dictionary<string,(long Size,DateTime Written,string Hash)> ToolHashes=new(StringComparer.OrdinalIgnoreCase); |
| 124 | private static Tools LoadTools() |
| 125 | { |
| 126 | var toolsFile=Path.Combine(AppContext.BaseDirectory,"cli-tools.json");Pairing.PrivateFile(toolsFile); |
| 127 | var tool=JsonNode.Parse(File.ReadAllBytes(toolsFile))as JsonObject??throw new InvalidDataException("cli_tools_invalid"); |
| 128 | return new Tools(CheckTool(tool,"python"),CheckTool(tool,"claude"),CheckTool(tool,"git_bash")); |
| 129 | } |
| 130 | |
| 131 | internal static JsonObject ComponentStatus() |
| 132 | { |
| 133 | var dependencies=new JsonObject{["python"]=false,["claude"]=false,["git_bash"]=false}; |
| 134 | try |
| 135 | { |
| 136 | var receipt=Path.Combine(AppContext.BaseDirectory,"cli-tools.json");Pairing.PrivateFile(receipt); |
| 137 | var info=new FileInfo(receipt);if(info.Length is <1 or >16384)throw new InvalidDataException("cli_tools_invalid"); |
| 138 | var tools=JsonNode.Parse(File.ReadAllBytes(receipt))as JsonObject??throw new InvalidDataException("cli_tools_invalid"); |
| 139 | foreach(var name in new[]{"python","claude","git_bash"}) |
| 140 | try{CheckTool(tools,name);dependencies[name]=true;}catch{ } |
| 141 | } |
| 142 | catch{ } |
| 143 | var installed=dependencies.All(pair=>pair.Value!.GetValue<bool>()); |
| 144 | return new JsonObject{["installed"]=installed,["ready"]=installed,["reason"]=installed?"":"cli_tools_missing_or_invalid",["dependencies"]=dependencies}; |
| 145 | } |
| 146 | private static string CheckTool(JsonObject tool,string name) |
| 147 | { |
| 148 | var path=tool[name]?.GetValue<string>()??"";var hash=tool[name+"_sha256"]?.GetValue<string>()??""; |
| 149 | if(!Path.IsPathFullyQualified(path)||!Subject.IsMatch(hash)||!File.Exists(path)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_tools_unverified"); |
| 150 | var info=new FileInfo(path); |
| 151 | lock(Gate) |
| 152 | { |
| 153 | if(!ToolHashes.TryGetValue(path,out var known)||known.Size!=info.Length||known.Written!=info.LastWriteTimeUtc||known.Hash!=hash) |
| 154 | { |
| 155 | using var file=File.OpenRead(path); |
| 156 | if(Convert.ToHexString(SHA256.HashData(file)).ToLowerInvariant()!=hash)throw new InvalidDataException("cli_tools_unverified"); |
| 157 | ToolHashes[path]=(info.Length,info.LastWriteTimeUtc,hash); |
| 158 | } |
| 159 | } |
| 160 | return Path.GetFullPath(path); |
| 161 | } |
| 162 | private sealed record CCSTools(string Node,string Main); |
| 163 | private static CCSTools LoadCCSTools() |
| 164 | { |
| 165 | var receipt=Path.Combine(AppContext.BaseDirectory,"ccs-tools.json");Pairing.PrivateFile(receipt); |
| 166 | var value=JsonNode.Parse(File.ReadAllBytes(receipt))as JsonObject??throw new InvalidDataException("ccs_tools_invalid"); |
| 167 | string Check(string name) |
| 168 | { |
| 169 | var path=value[name]?.GetValue<string>()??"";var hash=value[name+"_sha256"]?.GetValue<string>()??""; |
| 170 | if(!Path.IsPathFullyQualified(path)||!Subject.IsMatch(hash)||!File.Exists(path)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("ccs_tools_invalid"); |
| 171 | using var data=File.OpenRead(path);if(Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()!=hash)throw new InvalidDataException("ccs_tools_changed"); |
| 172 | return Path.GetFullPath(path); |
| 173 | } |
| 174 | var node=Check("node");var main=Check("main");var manifest=Check("manifest"); |
| 175 | if(new FileInfo(manifest).Length>2<<20)throw new InvalidDataException("ccs_manifest_invalid"); |
| 176 | var files=System.Text.Json.JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllBytes(manifest))??throw new InvalidDataException("ccs_manifest_invalid"); |
| 177 | if(files.Count is <1 or >20000)throw new InvalidDataException("ccs_manifest_invalid"); |
| 178 | var root=Path.GetDirectoryName(manifest)!; |
| 179 | foreach(var item in files) |
| 180 | { |
| 181 | var path=Path.GetFullPath(Path.Combine(root,item.Key.Replace('/',Path.DirectorySeparatorChar))); |
| 182 | if(!path.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||!Subject.IsMatch(item.Value)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("ccs_manifest_invalid"); |
| 183 | using var data=File.OpenRead(path);if(Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()!=item.Value)throw new InvalidDataException("ccs_tools_changed"); |
| 184 | } |
| 185 | if(!main.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("ccs_tools_invalid"); |
| 186 | return new(node,main); |
| 187 | } |
| 188 | private static Dictionary<string,string> EnvironmentFor(Layout layout,string account) |
| 189 | { |
| 190 | var env=Environment.GetEnvironmentVariables().Cast<System.Collections.DictionaryEntry>().ToDictionary(x=>(string)x.Key,x=>x.Value?.ToString()??"",StringComparer.OrdinalIgnoreCase); |
| 191 | env["CAGE_CLI_BINARY"]=layout.Tools.Claude;env["CAGE_CLI_STATE_ROOT"]=layout.State;env["CAGE_CLI_ACCOUNT_ROOT"]=layout.Accounts;env["CAGE_CLI_SHARED_ROOT"]=layout.Shared; |
| 192 | env["CAGE_CLI_ACCOUNT_HELPER"]=Path.Combine(layout.Code,"cage-claude-account.py");env["CLAUDE_CODE_GIT_BASH_PATH"]=layout.Tools.Bash; |
| 193 | env["CAGE_CLI_IDENTITY_HELPER"]=Path.Combine(layout.Code,"mobile_cli_identity.py"); |
| 194 | env["CAGE_CLI_PYTHON"]=layout.Tools.Python;env["CAGE_CLI_SHELL"]=TerminalRpc.PowerShellPath();env["CAGE_CLAUDE_ACCOUNT_ID"]=account; |
| 195 | env["PATH"]=Path.GetDirectoryName(layout.Tools.Claude)+";"+Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(layout.Tools.Bash))!,"cmd")+";"+env.GetValueOrDefault("PATH"); |
| 196 | if(account!="default")env["CLAUDE_CONFIG_DIR"]=Path.Combine(layout.Accounts,account,"config"); |
| 197 | else env.Remove("CLAUDE_CONFIG_DIR"); |
| 198 | return env; |
| 199 | } |
| 200 | private static void ValidatePaths(Layout layout,JsonObject value) |
| 201 | { |
| 202 | if(value["workspace"] is JsonValue w&&w.TryGetValue<string>(out var workspace)&&workspace!="") |
| 203 | { |
| 204 | var resolved=ProjectRpc.Resolve(value["project_id"]?.GetValue<string>()??"",value["grant"]?.GetValue<string>()??""); |
| 205 | if(!Path.GetFullPath(workspace).Equals(Path.GetFullPath(resolved),StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_project_unregistered"); |
| 206 | } |
| 207 | if(value["config"]is JsonValue c&&c.TryGetValue<string>(out var config)&&config!="") |
| 208 | { |
| 209 | var path=Path.GetFullPath(config);var home=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".claude"); |
| 210 | var relative=Path.GetRelativePath(layout.Accounts,path).Split(Path.DirectorySeparatorChar); |
| 211 | var ccs=Path.GetRelativePath(layout.Root,path); |
| 212 | var registeredCCS=(ccs.StartsWith("ccs-home"+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||ccs.StartsWith("ccs"+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))&&Directory.Exists(path); |
| 213 | if(!path.Equals(home,StringComparison.OrdinalIgnoreCase)&&!(relative.Length==2&&AccountID.IsMatch(relative[0])&&relative[0]!="default"&&relative[1]=="config")&&!registeredCCS)throw new InvalidDataException("cli_config_unregistered"); |
| 214 | } |
| 215 | if(value["resume_transcript"] is JsonValue t&&t.TryGetValue<string>(out var transcript)&&transcript!="") |
| 216 | { |
| 217 | var id=Guid.Parse(value["switch_id"]?.GetValue<string>()??""); |
| 218 | var expected=Path.Combine(layout.Root,"cli-account-switches",id.ToString("D"),"history.jsonl"); |
| 219 | if(!Path.GetFullPath(transcript).Equals(expected,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_history_unregistered"); |
| 220 | } |
| 221 | } |
| 222 | private static async Task<JsonObject> Invoke(Layout layout,string account,string script,string[] args,JsonNode? input,CancellationToken token,Func<bool> available) |
| 223 | { |
| 224 | var start=new ProcessStartInfo(layout.Tools.Python){UseShellExecute=false,CreateNoWindow=true,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true}; |
| 225 | foreach(var arg in new[]{"-X","utf8","-I",script}.Concat(args))start.ArgumentList.Add(arg); |
| 226 | foreach(var pair in EnvironmentFor(layout,account))start.Environment[pair.Key]=pair.Value; |
| 227 | start.WorkingDirectory=layout.Root; |
| 228 | using var child=Process.Start(start)??throw new InvalidDataException("cli_process_failed"); |
| 229 | using var cancel=token.Register(()=>{try{child.Kill(true);}catch{}}); |
| 230 | var stderr=child.StandardError.BaseStream.CopyToAsync(Stream.Null,token); |
| 231 | try |
| 232 | { |
| 233 | if(input is not null)await child.StandardInput.WriteLineAsync(input.ToJsonString().AsMemory(),token);child.StandardInput.Close(); |
| 234 | using var output=new MemoryStream();var buffer=new byte[16384];int size; |
| 235 | while((size=await child.StandardOutput.BaseStream.ReadAsync(buffer,token))!=0) |
| 236 | { |
| 237 | if(output.Length+size>4<<20)throw new InvalidDataException("cli_status_limit"); |
| 238 | output.Write(buffer,0,size); |
| 239 | } |
| 240 | var raw=Protocol.Utf8.GetString(output.GetBuffer(),0,(int)output.Length);await child.WaitForExitAsync(token);await stderr; |
| 241 | if(!available()||child.ExitCode!=0)throw new InvalidDataException("cli_status_unavailable"); |
| 242 | var parsed=JsonNode.Parse(raw); |
| 243 | return new JsonObject{["result"]=parsed}; |
| 244 | } |
| 245 | finally |
| 246 | { |
| 247 | if(!child.HasExited)try{child.Kill(true);}catch{} |
| 248 | await child.WaitForExitAsync(CancellationToken.None); |
| 249 | try{await stderr;}catch(OperationCanceledException){} |
| 250 | } |
| 251 | } |
| 252 | private static void PrivateDirectory(string path) |
| 253 | { |
| 254 | var home=Path.GetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); |
| 255 | if(!Path.GetFullPath(path).StartsWith(home+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_directory_invalid"); |
| 256 | for(var ancestor=new DirectoryInfo(path);ancestor.FullName!=home;ancestor=ancestor.Parent??throw new InvalidDataException("cli_directory_invalid")) |
| 257 | if(ancestor.Exists&&ancestor.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_directory_invalid"); |
| 258 | Directory.CreateDirectory(path);var info=new DirectoryInfo(path); |
| 259 | if(info.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_directory_invalid"); |
| 260 | using var user=WindowsIdentity.GetCurrent();var acl=new DirectorySecurity();acl.SetOwner(user.User!);acl.SetAccessRuleProtection(true,false); |
| 261 | foreach(var sid in new[]{user.User!,new SecurityIdentifier("S-1-5-18"),new SecurityIdentifier("S-1-5-32-544")})acl.AddAccessRule(new(sid,FileSystemRights.FullControl,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow)); |
| 262 | info.SetAccessControl(acl); |
| 263 | } |
| 264 | private static byte[] PrivateData(string path) |
| 265 | { |
| 266 | var info=new FileInfo(path); |
| 267 | if(!info.Exists||info.Length is <1 or >16384||info.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_credentials_invalid"); |
| 268 | using var user=WindowsIdentity.GetCurrent();var allowed=new HashSet<string>{user.User!.Value,"S-1-5-18","S-1-5-32-544"}; |
| 269 | foreach(FileSystemAccessRule rule in info.GetAccessControl().GetAccessRules(true,true,typeof(SecurityIdentifier))) |
| 270 | if(rule.AccessControlType==AccessControlType.Allow&&!allowed.Contains(rule.IdentityReference.Value))throw new InvalidDataException("cli_credentials_permissions_invalid"); |
| 271 | return File.ReadAllBytes(path); |
| 272 | } |
| 273 | private static IDisposable AccountLease(Layout layout,string account) |
| 274 | { |
| 275 | if(account=="default")return new Release(()=>{}); |
| 276 | var folder=Path.Combine(layout.Accounts,account,"config");PrivateDirectory(folder); |
| 277 | var plain=Path.Combine(folder,".credentials.json");var encrypted=Path.Combine(folder,"credentials.dpapi"); |
| 278 | lock(Gate) |
| 279 | { |
| 280 | if(!File.Exists(plain)&&File.Exists(encrypted)) |
| 281 | { |
| 282 | var restored=Pairing.Crypt(PrivateData(encrypted),GuestContext.VM,GuestContext.SID+":cli:"+layout.Profile+":"+account,false); |
| 283 | try{using var file=new FileStream(plain,FileMode.CreateNew,FileAccess.Write,FileShare.None);file.Write(restored);file.Flush(true);}finally{CryptographicOperations.ZeroMemory(restored);} |
| 284 | } |
| 285 | Active[folder]=Active.GetValueOrDefault(folder)+1; |
| 286 | } |
| 287 | return new Release(()=>{lock(Gate){if(--Active[folder]!=0)return;Active.Remove(folder);if(File.Exists(plain)){var bytes=PrivateData(plain);try{var sealedBytes=Pairing.Crypt(bytes,GuestContext.VM,GuestContext.SID+":cli:"+layout.Profile+":"+account,true);var temporary=encrypted+"."+Guid.NewGuid().ToString("N");using(var file=new FileStream(temporary,FileMode.CreateNew,FileAccess.Write,FileShare.None)){file.Write(sealedBytes);file.Flush(true);}File.Move(temporary,encrypted,true);File.Delete(plain);}finally{CryptographicOperations.ZeroMemory(bytes);}}}}); |
| 288 | } |
| 289 | private sealed class Release(Action action):IDisposable{private Action? close=action;public void Dispose()=>Interlocked.Exchange(ref close,null)?.Invoke();} |
| 290 | private sealed class PrefixStream(Stream inner,byte[] prefix):Stream |
| 291 | { |
| 292 | int position; |
| 293 | public override async ValueTask<int> ReadAsync(Memory<byte> buffer,CancellationToken token=default){if(position<prefix.Length){var n=Math.Min(buffer.Length,prefix.Length-position);prefix.AsMemory(position,n).CopyTo(buffer);position+=n;return n;}return await inner.ReadAsync(buffer,token);} |
| 294 | public override int Read(byte[] buffer,int offset,int count){if(position<prefix.Length){var n=Math.Min(count,prefix.Length-position);Array.Copy(prefix,position,buffer,offset,n);position+=n;return n;}return inner.Read(buffer,offset,count);} |
| 295 | public override Task WriteAsync(byte[] buffer,int offset,int count,CancellationToken token)=>inner.WriteAsync(buffer,offset,count,token); |
| 296 | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer,CancellationToken token=default)=>inner.WriteAsync(buffer,token); |
| 297 | public override void Write(byte[] buffer,int offset,int count)=>inner.Write(buffer,offset,count);public override void Flush()=>inner.Flush();public override Task FlushAsync(CancellationToken token)=>inner.FlushAsync(token); |
| 298 | public override bool CanRead=>true;public override bool CanWrite=>true;public override bool CanSeek=>false;public override long Length=>throw new NotSupportedException();public override long Position{get=>throw new NotSupportedException();set=>throw new NotSupportedException();}public override long Seek(long a,SeekOrigin b)=>throw new NotSupportedException();public override void SetLength(long a)=>throw new NotSupportedException(); |
| 299 | } |
| 300 | } |