跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

NetworkRuntime.cs

255 行 · 18.9 KB历史下载
1using System.Buffers.Binary;
2using System.ComponentModel;
3using System.Diagnostics;
4using System.Net.Sockets;
5using System.Runtime.InteropServices;
6using System.Security.Cryptography;
7using System.Security.Principal;
8using System.Text.Json.Nodes;
9
10namespace Cage.GuestClipboard;
11
12// This SYSTEM process owns only the Cage virtual packet interface. The GUI
13// clipboard, browser, files and input endpoints run in the ordinary user agent.
14internal static class NetworkRuntime
15{
16 internal static readonly Guid Service = new("f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fb");
17 internal const string IP = "192.168.127.2", Gateway = "192.168.127.1";
18 private static readonly SemaphoreSlim PacketSlot = new(1,1);
19 private static readonly byte[] GuestMac = [0x5a,0x94,0xef,0xe4,0x0c,0xee], GatewayMac = [0x5a,0x94,0xef,0xe4,0x0c,0xdd];
20 internal static async Task Run(Guid vm, string sid, string keyPath, CancellationToken token)
21 {
22 if (WindowsIdentity.GetCurrent().User?.Value != "S-1-5-18") throw new InvalidDataException("network_requires_system");
23 var parameters = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters");
24 if (!Guid.TryParse(parameters?.GetValue("VirtualMachineId")?.ToString(), out var actual) || actual != vm || !sid.StartsWith("S-1-5-21-",StringComparison.Ordinal)) throw new InvalidDataException("network_vm_invalid");
25 var secret = Pairing.Load(keyPath,vm,sid,false);
26 using var listener = HyperVEndPoint.Socket();
27 using var interrupt = token.Register(listener.Dispose);
28 listener.Bind(new HyperVEndPoint(Protocol.Parent,Service)); listener.Listen(1);
29 using var slots = new SemaphoreSlim(4,4);
30 var active = new HashSet<Task>();
31 try
32 {
33 while (!token.IsCancellationRequested)
34 {
35 await slots.WaitAsync(token);
36 Socket socket;
37 try { socket = await Task.Run(listener.Accept,CancellationToken.None).WaitAsync(token); }
38 catch { slots.Release();throw; }
39 lock(active)
40 {
41 Task? task = null;
42 task = Task.Run(async()=>{
43 try { await Connection(socket,vm,sid,secret,token); }
44 catch(Exception error) {
45 // Stage-free native code only: never serialize request,
46 // packet bytes, paths, identity secrets or exception text.
47 try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"network-error.json"),new JsonObject { ["error_type"]=error.GetType().Name,["hresult"]=error.HResult.ToString("X8"),["stage"]=(error as NetworkFailure)?.Stage ?? "handshake-or-stream",["native_code"]=(error.InnerException as Win32Exception)?.NativeErrorCode ?? (error as Win32Exception)?.NativeErrorCode ?? 0,["updated_at"]=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString()); } catch { }
48 }
49 finally { socket.Dispose();slots.Release();lock(active)active.Remove(task!); }
50 },CancellationToken.None);
51 active.Add(task);
52 }
53 }
54 }
55 catch(OperationCanceledException)when(token.IsCancellationRequested){ }
56 catch(ObjectDisposedException)when(token.IsCancellationRequested){ }
57 finally { Task[] pending;lock(active)pending=active.ToArray();await Task.WhenAll(pending);CryptographicOperations.ZeroMemory(secret); }
58 }
59
60 private static async Task Connection(Socket socket,Guid vm,string sid,byte[] secret,CancellationToken token)
61 {
62 using var connection = CancellationTokenSource.CreateLinkedTokenSource(token);
63 using var cancel = connection.Token.Register(socket.Dispose);
64 using var network = new NetworkStream(socket,false);
65 using var stream = new ReadAheadStream(network);
66 using var handshake = CancellationTokenSource.CreateLinkedTokenSource(connection.Token); handshake.CancelAfter(TimeSpan.FromSeconds(10));
67 var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); var session = Guid.NewGuid().ToString("N");
68 await Protocol.Write(stream,new JsonObject { ["nonce"] = nonce,["vm_id"] = vm.ToString("D"),["sid"] = sid,["session"] = session,["proof"] = Protocol.Proof(secret,"server",nonce,vm,sid,session,"",null) },handshake.Token);
69 var request = await Protocol.Read(stream,4096,handshake.Token) ?? throw new EndOfStreamException();
70 var operation = request["operation"]?.GetValue<string>() ?? "";
71 if (operation is not ("network-stream" or "network-settings") || request["paths"] is not null || request["vm_id"]?.GetValue<string>() != vm.ToString("D") || request["sid"]?.GetValue<string>() != sid ||
72 !Protocol.EqualProof(Protocol.Proof(secret,"client",nonce,vm,sid,session,operation,null),request["proof"]?.GetValue<string>())) throw new InvalidDataException("pairing_invalid");
73 if (operation == "network-settings")
74 {
75 await Protocol.Write(stream,new JsonObject { ["version"] = 1,["session"] = session,["available"] = true },handshake.Token);
76 var settings = await Protocol.Read(stream,4096,handshake.Token) ?? throw new EndOfStreamException();
77 await WindowsSystemSettings.Apply(settings,vm,sid,connection.Token);
78 await Protocol.Write(stream,new JsonObject { ["ok"] = true },connection.Token); return;
79 }
80 if(!await PacketSlot.WaitAsync(0,connection.Token))throw new InvalidDataException("network_stream_already_connected");
81 try {
82 handshake.CancelAfter(TimeSpan.FromSeconds(20));
83 using var tun = new Wintun(vm);
84 // Adapter configuration is part of the bounded admission handshake.
85 // A stalled PowerShell operation must release this packet slot so a
86 // later authenticated host connection can retry.
87 await tun.Configure(handshake.Token);
88 await Protocol.Write(stream,new JsonObject { ["version"] = 1,["os"] = "windows",["vm_id"] = vm.ToString("D"),["gui_user_sid"] = sid,["session"] = session,["available"] = true,["network"] = "packet" },handshake.Token);
89 using var writes = new SemaphoreSlim(1,1);
90 async Task Send(byte[] frame)
91 {
92 await writes.WaitAsync(connection.Token);
93 try { var length = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(length,(uint)frame.Length); await stream.WriteAsync(length,connection.Token); await stream.WriteAsync(frame,connection.Token); await stream.FlushAsync(connection.Token); }
94 finally { writes.Release(); }
95 }
96 var readyPath = Path.Combine(AppContext.BaseDirectory,"network-ready.json");
97 var receipt = Task.Run(async () =>
98 {
99 while(!connection.IsCancellationRequested)
100 {
101 var data = new JsonObject { ["version"] = 1,["vm_id"] = vm.ToString("D"),["gui_user_sid"] = sid,["adapter"] = tun.Name,["interface_index"] = tun.Index,["session"] = session,["updated_at"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),["network"] = "packet" };
102 var stage = readyPath+"."+session;
103 await PublishReceipt(stage,readyPath,data.ToJsonString(),connection.Token);
104 await Task.Delay(1000,connection.Token);
105 }
106 },connection.Token);
107 var outgoing = Task.Run(async () =>
108 {
109 while(!connection.IsCancellationRequested)
110 {
111 var packet = tun.Receive();
112 if (packet is null) { await Task.Delay(5,connection.Token); continue; }
113 var frame = new byte[14+packet.Length]; GatewayMac.CopyTo(frame,0); GuestMac.CopyTo(frame,6);
114 frame[12] = packet[0]>>4 == 6 ? (byte)0x86 : (byte)0x08; frame[13] = packet[0]>>4 == 6 ? (byte)0xdd : (byte)0;
115 packet.CopyTo(frame,14); await Send(frame);
116 }
117 },connection.Token);
118 var incoming = Task.Run(async () =>
119 {
120 var header = new byte[4];
121 while(!connection.IsCancellationRequested)
122 {
123 await stream.ReadExactlyAsync(header,connection.Token); var size = BinaryPrimitives.ReadUInt32BigEndian(header);
124 if (size is < 14 or > 65549) throw new InvalidDataException("network_packet_invalid");
125 var frame = new byte[size]; await stream.ReadExactlyAsync(frame,connection.Token);
126 if (frame[12]==8 && frame[13]==6)
127 {
128 var response = Arp(frame); if (response is not null) await Send(response); continue;
129 }
130 if (!(frame[12]==8 && frame[13]==0 || frame[12]==0x86 && frame[13]==0xdd)) continue;
131 if (!frame.AsSpan(0,6).SequenceEqual(GuestMac) && !frame.AsSpan(0,6).SequenceEqual(new byte[]{255,255,255,255,255,255})) continue;
132 tun.Send(frame.AsSpan(14));
133 }
134 },connection.Token);
135 Task completed;
136 try { completed = await Task.WhenAny(incoming,outgoing,receipt); }
137 finally
138 {
139 connection.Cancel(); socket.Dispose();
140 try { await Task.WhenAll(incoming,outgoing,receipt); } catch { }
141 try { if (JsonNode.Parse(File.ReadAllText(readyPath))?["session"]?.GetValue<string>()==session) File.Delete(readyPath); } catch { }
142 try { File.Delete(readyPath+"."+session); } catch { }
143 }
144 // Retire all workers before reporting the worker that ended the stream.
145 // Awaiting WhenAny alone would discard its exception and leave only an
146 // old diagnostic from an unrelated admission failure.
147 if (!token.IsCancellationRequested)
148 {
149 var stage = completed == incoming ? "stream-incoming" : completed == outgoing ? "stream-outgoing" : "stream-receipt";
150 try { await completed; }
151 catch (NetworkFailure) { throw; }
152 catch (Exception error) { throw new NetworkFailure(stage,error); }
153 throw new NetworkFailure(stage,new EndOfStreamException());
154 }
155 } finally { PacketSlot.Release(); }
156 }
157
158 internal static async Task PublishReceipt(string stage,string destination,string contents,CancellationToken token)
159 {
160 try { await File.WriteAllTextAsync(stage,contents,token); }
161 catch (Exception error) when (!token.IsCancellationRequested) { throw new NetworkFailure("receipt-write",error); }
162 try { await WindowsFilePublication.Replace(stage,destination,token); }
163 catch(Exception error) when(!token.IsCancellationRequested) { throw new NetworkFailure("receipt-replace",error); }
164 }
165
166 private static byte[]? Arp(byte[] frame)
167 {
168 if (frame.Length < 42 || frame[14]!=0 || frame[15]!=1 || frame[16]!=8 || frame[17]!=0 || frame[18]!=6 || frame[19]!=4 || frame[20]!=0 || frame[21]!=1 || !frame.AsSpan(38,4).SequenceEqual(new byte[]{192,168,127,2})) return null;
169 var result = new byte[42]; frame.AsSpan(6,6).CopyTo(result); GuestMac.CopyTo(result,6); result[12]=8; result[13]=6;
170 frame.AsSpan(14,8).CopyTo(result.AsSpan(14)); result[21]=2; GuestMac.CopyTo(result,22); new byte[]{192,168,127,2}.CopyTo(result,28);
171 frame.AsSpan(22,10).CopyTo(result.AsSpan(32)); return result;
172 }
173
174 private sealed class Wintun : IDisposable
175 {
176 [UnmanagedFunctionPointer(CallingConvention.Winapi,CharSet=CharSet.Unicode,SetLastError=true)] private delegate IntPtr Create(string name,string type,ref Guid id);
177 [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void Close(IntPtr handle);
178 [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr Start(IntPtr adapter,uint capacity);
179 [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr ReceivePacket(IntPtr session,out uint size);
180 [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void ReleasePacket(IntPtr session,IntPtr packet);
181 [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr AllocatePacket(IntPtr session,uint size);
182 [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void Luid(IntPtr adapter,out ulong luid);
183 [DllImport("iphlpapi.dll")] private static extern uint ConvertInterfaceLuidToIndex(ref ulong luid,out uint index);
184 private readonly IntPtr library,adapter,session;
185 private readonly Close close,end; private readonly ReceivePacket receive; private readonly ReleasePacket release,send; private readonly AllocatePacket allocate;
186 internal string Name { get; }
187 internal uint Index { get; }
188 private T Load<T>(string name) where T:Delegate => Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library,name));
189 internal Wintun(Guid vm)
190 {
191 Name = "Cage-"+vm.ToString("N")[..8];
192 library = NativeLibrary.Load(Path.Combine(AppContext.BaseDirectory,"wintun.dll"));
193 close = Load<Close>("WintunCloseAdapter"); end = Load<Close>("WintunEndSession"); receive = Load<ReceivePacket>("WintunReceivePacket"); release = Load<ReleasePacket>("WintunReleaseReceivePacket"); send = Load<ReleasePacket>("WintunSendPacket"); allocate = Load<AllocatePacket>("WintunAllocateSendPacket");
194 try
195 {
196 adapter = Load<Create>("WintunCreateAdapter")(Name,"Cage",ref vm);
197 if (adapter==IntPtr.Zero) throw new Win32Exception(Marshal.GetLastPInvokeError());
198 Load<Luid>("WintunGetAdapterLUID")(adapter,out var luid);
199 if (ConvertInterfaceLuidToIndex(ref luid,out var index)!=0 || index==0) throw new InvalidDataException("network_adapter_invalid"); Index=index;
200 session = Load<Start>("WintunStartSession")(adapter,4<<20);
201 if (session==IntPtr.Zero) throw new Win32Exception(Marshal.GetLastPInvokeError());
202 }
203 catch(Exception error) { Dispose(); throw new NetworkFailure("driver",error); }
204 }
205 internal async Task Configure(CancellationToken token)
206 {
207 var script = $"$ErrorActionPreference='Stop';$stage='adapter';try{{$i={Index};$a=Get-NetAdapter -Name '{Name}';if($a.ifIndex -ne $i -or $a.Name -cne '{Name}'){{throw 'network_adapter_invalid'}};$stage='ip';New-NetIPAddress -InterfaceIndex $i -IPAddress '{IP}' -PrefixLength 24 -DefaultGateway '{Gateway}' -AddressFamily IPv4 | Out-Null;$stage='dns';Set-DnsClientServerAddress -InterfaceIndex $i -ServerAddresses '{Gateway}';$stage='interface';Set-NetIPInterface -InterfaceIndex $i -AddressFamily IPv4 -InterfaceMetric 1 -NlMtuBytes 1500";
208 // New-NetIPAddress returns before Windows completes duplicate
209 // address detection. A tentative address cannot send the probes.
210 // Admit this exact adapter only when its real address and route
211 // are usable; a timer by itself is never readiness evidence.
212 script += $";$stage='preferred';$until=[DateTime]::UtcNow.AddSeconds(10);$ready=$false;while([DateTime]::UtcNow -lt $until){{$ip=Get-NetIPAddress -InterfaceIndex $i -AddressFamily IPv4 -IPAddress '{IP}' -ErrorAction SilentlyContinue;if($ip.AddressState -eq 'Duplicate'){{throw 'network_address_duplicate'}};$route=Get-NetRoute -InterfaceIndex $i -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue;$dns=Get-DnsClientServerAddress -InterfaceIndex $i -AddressFamily IPv4;$ready=($ip.AddressState -eq 'Preferred' -and (Get-NetAdapter -Name '{Name}').Status -eq 'Up' -and @($route|Where-Object {{$_.NextHop -eq '{Gateway}'}}).Count -gt 0 -and $dns.ServerAddresses -contains '{Gateway}');if($ready){{break}};Start-Sleep -Milliseconds 100}};if(!$ready){{throw 'network_address_not_ready'}}}}catch{{[Console]::Out.WriteLine((@{{stage=$stage;hresult=[int]$_.Exception.HResult;category=[string]$_.CategoryInfo.Category}}|ConvertTo-Json -Compress));exit 1}}";
213 var info = 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 };
214 foreach(var argument in new[]{"-NoLogo","-NoProfile","-NonInteractive","-Command","-"}) info.ArgumentList.Add(argument);
215 using var process = Process.Start(info) ?? throw new InvalidDataException("network_configuration_failed");
216 using var cancel = token.Register(()=>{try{process.Kill(true);}catch{}});
217 var output = process.StandardOutput.ReadToEndAsync(token); var errors = process.StandardError.BaseStream.CopyToAsync(Stream.Null,token);
218 await process.StandardInput.WriteLineAsync(script); process.StandardInput.Close(); await process.WaitForExitAsync(token); await Task.WhenAll(output,errors);
219 if (process.ExitCode!=0)
220 {
221 var diagnostic=await output;
222 try
223 {
224 if(diagnostic.Length>4096)throw new InvalidDataException("network_diagnostic_invalid");
225 var detail=JsonNode.Parse(diagnostic) as JsonObject;
226 var stage=detail?["stage"]?.GetValue<string>();
227 if(stage is "adapter" or "ip" or "dns" or "interface" or "preferred")
228 {
229 var failure=new NetworkConfigurationFailure(detail?["hresult"]?.GetValue<int>() ?? 0);
230 throw new NetworkFailure("configure-"+stage,failure);
231 }
232 }
233 catch(NetworkFailure){throw;}
234 catch(Exception error) when(error is System.Text.Json.JsonException or InvalidDataException or InvalidOperationException){ }
235 throw new NetworkFailure("configure",new Win32Exception(process.ExitCode));
236 }
237 }
238 internal byte[]? Receive()
239 {
240 var pointer = receive(session,out var size);
241 if(pointer==IntPtr.Zero) return null;
242 try { if(size is <20 or >65535) throw new InvalidDataException("network_packet_invalid"); var data=new byte[size];Marshal.Copy(pointer,data,0,(int)size);return data; }
243 finally { release(session,pointer); }
244 }
245 internal void Send(ReadOnlySpan<byte> data)
246 {
247 if(data.Length is <20 or >65535) throw new InvalidDataException("network_packet_invalid");
248 var pointer=allocate(session,(uint)data.Length);if(pointer==IntPtr.Zero)return;
249 Marshal.Copy(data.ToArray(),0,pointer,data.Length);send(session,pointer);
250 }
251 public void Dispose() { if(session!=IntPtr.Zero)end(session);if(adapter!=IntPtr.Zero)close(adapter);NativeLibrary.Free(library); }
252 }
253 private sealed class NetworkConfigurationFailure:Exception{internal NetworkConfigurationFailure(int hresult):base("network_configuration_failed"){HResult=hresult;}}
254 private sealed class NetworkFailure:Exception{internal NetworkFailure(string stage,Exception error):base("network_stage_failed",error){Stage=stage;HResult=error.HResult;}internal string Stage{get;}}
255}