| 1 | using System.Globalization; |
| 2 | using System.Net; |
| 3 | using System.Net.Http; |
| 4 | using System.Net.NetworkInformation; |
| 5 | using System.Net.Sockets; |
| 6 | using System.Runtime.CompilerServices; |
| 7 | using System.Runtime.InteropServices; |
| 8 | using System.Security.Cryptography; |
| 9 | using System.Text.Json.Nodes; |
| 10 | |
| 11 | namespace Cage.GuestClipboard; |
| 12 | |
| 13 | |
| 14 | |
| 15 | internal static class NativeSafetyRpc |
| 16 | { |
| 17 | [ModuleInitializer] internal static void Register() => GuestOperations.Register("safety",Run); |
| 18 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode)] private static extern int GetSystemDefaultLocaleName(char[] value,int capacity); |
| 19 | private sealed class Progress { internal string Stage="request"; } |
| 20 | internal static async Task Run(Stream stream,CancellationToken token,Func<bool> available) |
| 21 | { |
| 22 | var progress=new Progress(); |
| 23 | try{await RunCore(stream,token,available,progress);} |
| 24 | catch(Exception error) when(error is not OperationCanceledException) |
| 25 | { |
| 26 | var code=error switch { InvalidDataException=>"invalid_probe",UnauthorizedAccessException=>"access_denied",IOException=>"file_io",SocketException=>"socket",_=>"probe_failed" }; |
| 27 | await Protocol.Write(stream,new JsonObject{["error"]="safety_probe_failed",["stage"]=progress.Stage,["error_code"]=code,["hresult"]=unchecked((uint)error.HResult).ToString("x8"),["native_code"]=error is SocketException socket ? socket.NativeErrorCode : 0},token); |
| 28 | } |
| 29 | } |
| 30 | private static async Task RunCore(Stream stream,CancellationToken token,Func<bool> available,Progress progress) |
| 31 | { |
| 32 | var input=await Protocol.Read(stream,16384,token) ?? throw new EndOfStreamException(); |
| 33 | if(!available())throw new InvalidDataException("requires_gui_login"); |
| 34 | var stage=input["stage"]?.GetValue<string>(); |
| 35 | if(stage is not ("environment" or "boundary" or "network"))throw new InvalidDataException("safety_request_invalid"); |
| 36 | progress.Stage="environment";TimeZoneInfo.ClearCachedData(); |
| 37 | var timezone=ObservedTimezone(TimeZoneInfo.Local.Id,input["timezone"]?.GetValue<string>()); |
| 38 | var system=new char[85];var count=GetSystemDefaultLocaleName(system,system.Length); |
| 39 | var result=new JsonObject{["tz"]=timezone,["system_timezone"]=timezone,["process_locale"]=CultureInfo.CurrentCulture.Name,["system_locale"]=count>0 ? new string(system,0,count-1) : "",["locale_valid"]=count>0}; |
| 40 | if(stage=="network") |
| 41 | { |
| 42 | progress.Stage="network"; |
| 43 | result["egress"]=await Probe("egress",token);result["dns"]=await Probe("dns",token); |
| 44 | } |
| 45 | if(stage=="boundary") |
| 46 | { |
| 47 | var port=input["control_port"]?.GetValue<int>() ?? 0; |
| 48 | if(port is <1 or >65535)throw new InvalidDataException("safety_request_invalid"); |
| 49 | progress.Stage="public-tcp";result["public_connected"]=await Connect("1.1.1.1",443,AddressFamily.InterNetwork,token); |
| 50 | result["management_connected"]=await Connect("192.168.5.2",port,AddressFamily.InterNetwork,token); |
| 51 | result["ipv6_connected"]=await Connect("2606:4700:4700::1111",443,AddressFamily.InterNetworkV6,token); |
| 52 | result["ipv6_default_routes"]=NetworkInterface.GetAllNetworkInterfaces().Sum(n=>n.GetIPProperties().GatewayAddresses.Count(g=>g.Address.AddressFamily==AddressFamily.InterNetworkV6)); |
| 53 | var nonce=Convert.ToHexString(RandomNumberGenerator.GetBytes(8)).ToLowerInvariant(); |
| 54 | progress.Stage="udp"; |
| 55 | using(var udp=new UdpClient(AddressFamily.InterNetwork)) |
| 56 | { |
| 57 | await udp.SendAsync(new byte[]{1,2,3},new IPEndPoint(IPAddress.Parse("8.8.8.8"),53),token);result["udp_attempted"]=true; |
| 58 | } |
| 59 | progress.Stage="dns";result["public_dns_answered"]=await PublicDNS(nonce,token); |
| 60 | var id=input["project_id"]?.GetValue<string>() ?? "";var grant=input["grant"]?.GetValue<string>() ?? ""; |
| 61 | progress.Stage="project-grant";var directory=ProjectRpc.Resolve(id,grant); |
| 62 | var name=input["shared_name"]?.GetValue<string>() ?? ""; |
| 63 | var challenge=input["challenge"]?.GetValue<string>() ?? ""; |
| 64 | if(name.Length is <1 or >255 || Path.GetFileName(name)!=name || !name.StartsWith(".cage-share-probe-",StringComparison.Ordinal) || challenge.Length!=64 || challenge.Any(c=>!char.IsAsciiHexDigit(c)))throw new InvalidDataException("safety_file_invalid"); |
| 65 | var file=Path.Combine(directory,name); |
| 66 | progress.Stage="shared-read";var original=await File.ReadAllTextAsync(file,token); |
| 67 | result["shared_file"]=original==challenge; |
| 68 | progress.Stage="shared-write";if(original==challenge)await File.WriteAllTextAsync(file,challenge+":guest",token); |
| 69 | |
| 70 | |
| 71 | progress.Stage="private-scope";var privateName=input["private_name"]?.GetValue<string>() ?? ""; |
| 72 | if(Path.GetFileName(privateName)!=privateName || !privateName.StartsWith(".cage-private-probe-",StringComparison.Ordinal))throw new InvalidDataException("safety_file_invalid"); |
| 73 | result["private_file"]=File.Exists(Path.Combine(directory,privateName)) ? "reachable" : "unreachable"; |
| 74 | } |
| 75 | if(!available())throw new InvalidDataException("requires_gui_login"); |
| 76 | await Protocol.Write(stream,result,token); |
| 77 | } |
| 78 | internal static string ObservedTimezone(string windowsZone,string? requested) |
| 79 | { |
| 80 | |
| 81 | |
| 82 | if(requested is { Length: >0 and <=128 } && TimeZoneInfo.TryConvertIanaIdToWindowsId(requested,out var expected) && string.Equals(expected,windowsZone,StringComparison.OrdinalIgnoreCase))return requested; |
| 83 | return TimeZoneInfo.TryConvertWindowsIdToIanaId(windowsZone,out var iana) ? iana! : windowsZone; |
| 84 | } |
| 85 | private static async Task<bool> Connect(string host,int port,AddressFamily family,CancellationToken token) |
| 86 | { |
| 87 | using var timeout=CancellationTokenSource.CreateLinkedTokenSource(token);timeout.CancelAfter(TimeSpan.FromSeconds(3)); |
| 88 | using var client=new TcpClient(family); |
| 89 | try{await client.ConnectAsync(IPAddress.Parse(host),port,timeout.Token);return true;}catch(SocketException){return false;}catch(OperationCanceledException)when(!token.IsCancellationRequested){return false;} |
| 90 | } |
| 91 | private static async Task<JsonObject> Probe(string path,CancellationToken token) |
| 92 | { |
| 93 | using var handler=new HttpClientHandler{UseProxy=false,AllowAutoRedirect=false};using var client=new HttpClient(handler){Timeout=TimeSpan.FromSeconds(15)}; |
| 94 | try |
| 95 | { |
| 96 | using var response=await client.GetAsync("http://198.18.0.254/"+path,HttpCompletionOption.ResponseHeadersRead,token); |
| 97 | using var body=await response.Content.ReadAsStreamAsync(token);using var buffer=new MemoryStream();var chunk=new byte[1024];int n; |
| 98 | while((n=await body.ReadAsync(chunk,token))!=0){if(buffer.Length+n>4096)throw new InvalidDataException("safety_response_limit");buffer.Write(chunk,0,n);} |
| 99 | var data=JsonNode.Parse(buffer.ToArray()) as JsonObject; |
| 100 | return new JsonObject{["status"]=(int)response.StatusCode,["ip"]=data?["ip"]?.GetValue<string>() ?? ""}; |
| 101 | } |
| 102 | catch(HttpRequestException){return new JsonObject{["status"]=0,["ip"]=""};} |
| 103 | catch(TaskCanceledException)when(!token.IsCancellationRequested){return new JsonObject{["status"]=0,["ip"]=""};} |
| 104 | } |
| 105 | private static async Task<bool> PublicDNS(string nonce,CancellationToken token) |
| 106 | { |
| 107 | using var timeout=CancellationTokenSource.CreateLinkedTokenSource(token);timeout.CancelAfter(TimeSpan.FromSeconds(2)); |
| 108 | using var client=new UdpClient(AddressFamily.InterNetwork);var query=new List<byte>{1,2,1,0,0,1,0,0,0,0,0,0}; |
| 109 | foreach(var label in (nonce+".example.com").Split('.')){query.Add((byte)label.Length);query.AddRange(Protocol.Utf8.GetBytes(label));}query.AddRange(new byte[]{0,0,1,0,1}); |
| 110 | await client.SendAsync(query.ToArray(),new IPEndPoint(IPAddress.Parse("192.168.127.1"),53),token); |
| 111 | try{var reply=await client.ReceiveAsync(timeout.Token);return reply.Buffer.Length>=12 && (reply.Buffer[6]!=0 || reply.Buffer[7]!=0);} |
| 112 | catch(SocketException){return false;}catch(OperationCanceledException)when(!token.IsCancellationRequested){return false;} |
| 113 | } |
| 114 | } |