| 1 | using System.Net.Sockets; |
| 2 | using System.Security.Cryptography; |
| 3 | using System.Text.Json; |
| 4 | using System.Text.Json.Nodes; |
| 5 | using System.Text.Json.Serialization; |
| 6 | |
| 7 | namespace Cage.GuestClipboard; |
| 8 | |
| 9 | internal sealed class WindowsProfile |
| 10 | { |
| 11 | [JsonPropertyName("version")] public int Version { get; set; } |
| 12 | [JsonPropertyName("vm_id")] public Guid VM { get; set; } |
| 13 | [JsonPropertyName("gui_user_sid")] public string SID { get; set; } = ""; |
| 14 | [JsonPropertyName("gui_user")] public string? User { get; set; } |
| 15 | [JsonPropertyName("instance_directory")] public string Directory { get; set; } = ""; |
| 16 | [JsonPropertyName("relay_executable")] public string Executable { get; set; } = ""; |
| 17 | [JsonPropertyName("pairing_file")] public string Pairing { get; set; } = ""; |
| 18 | [JsonPropertyName("network_pairing_file")] public string? NetworkPairing { get; set; } |
| 19 | internal static WindowsProfile Load(string file) |
| 20 | { |
| 21 | PairingPrivate(file); |
| 22 | var p = JsonSerializer.Deserialize<WindowsProfile>(File.ReadAllBytes(file), new JsonSerializerOptions { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow }) ?? throw new InvalidDataException(); |
| 23 | if (p.Version != 1 || p.VM == Guid.Empty || !p.SID.StartsWith("S-1-5-21-", StringComparison.Ordinal) || |
| 24 | new[] { p.Directory, p.Executable, p.Pairing }.Any(path => !Path.IsPathFullyQualified(path) || path.IndexOfAny(['\0', '\r', '\n']) >= 0)) throw new InvalidDataException("profile_invalid"); |
| 25 | if (p.NetworkPairing != null && (!Path.IsPathFullyQualified(p.NetworkPairing) || p.NetworkPairing.IndexOfAny(['\0', '\r', '\n']) >= 0)) throw new InvalidDataException("profile_invalid"); |
| 26 | return p; |
| 27 | } |
| 28 | static void PairingPrivate(string file) => GuestClipboard.Pairing.PrivateFile(file); |
| 29 | } |
| 30 | |
| 31 | internal static class Relay |
| 32 | { |
| 33 | internal static string Phase { get; private set; } = "startup"; |
| 34 | internal static async Task Run(string[] args) |
| 35 | { |
| 36 | if (args.Length is < 3 or > 4 || !GuestOperations.Names.Contains(args[2]) || args.Length == 4 && !(args[2] == "export" && args[3] == "--paths-stdin")) throw new InvalidDataException("command_invalid"); |
| 37 | Phase = "profile"; var profile = WindowsProfile.Load(args[1]); var operation = args[2]; |
| 38 | Phase = "pairing"; |
| 39 | var privilegedNetwork = operation is "network-stream" or "network-settings"; |
| 40 | var pairing = privilegedNetwork ? profile.NetworkPairing ?? throw new InvalidDataException("network_pairing_unavailable") : profile.Pairing; |
| 41 | var service = privilegedNetwork ? NetworkRuntime.Service : Protocol.Service; |
| 42 | var secret = Pairing.Load(pairing, profile.VM, profile.SID, true); |
| 43 | using var socket = HyperVEndPoint.Socket(); |
| 44 | using var lifetime = new CancellationTokenSource(); |
| 45 | Console.CancelKeyPress += (_, e) => { e.Cancel = true; lifetime.Cancel(); socket.Dispose(); }; |
| 46 | using var connect = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); connect.CancelAfter(TimeSpan.FromSeconds(10)); |
| 47 | try |
| 48 | { |
| 49 | Phase = "connect"; |
| 50 | |
| 51 | |
| 52 | |
| 53 | using (connect.Token.Register(socket.Dispose)) |
| 54 | await Task.Run(() => socket.Connect(new HyperVEndPoint(profile.VM, service)), CancellationToken.None).WaitAsync(connect.Token); |
| 55 | using var network = new NetworkStream(socket, false); using var stream = new ReadAheadStream(network); |
| 56 | Phase = "server_proof"; var challenge = await Protocol.Read(stream, 4096, connect.Token) ?? throw new EndOfStreamException(); |
| 57 | var nonce = challenge["nonce"]?.GetValue<string>() ?? ""; var session = challenge["session"]?.GetValue<string>() ?? ""; |
| 58 | if (challenge["vm_id"]?.GetValue<string>() != profile.VM.ToString("D") || challenge["sid"]?.GetValue<string>() != profile.SID || |
| 59 | !Protocol.EqualProof(Protocol.Proof(secret, "server", nonce, profile.VM, profile.SID, session, "", null), challenge["proof"]?.GetValue<string>())) throw new InvalidDataException("pairing_invalid"); |
| 60 | JsonNode? paths = null; |
| 61 | if (operation == "export") |
| 62 | { |
| 63 | using var input = new MemoryStream(); var buffer = new byte[64 << 10]; int n; |
| 64 | var source = Console.OpenStandardInput(); |
| 65 | while ((n = await source.ReadAsync(buffer, lifetime.Token)) > 0) |
| 66 | { if (input.Length + n > Protocol.PathLimit) throw new InvalidDataException("selection_limit"); input.Write(buffer, 0, n); } |
| 67 | paths = JsonNode.Parse(input.ToArray()); Protocol.Paths(paths); |
| 68 | } |
| 69 | Phase = "client_proof"; await Protocol.Write(stream, new() { ["vm_id"] = profile.VM.ToString("D"), ["sid"] = profile.SID, ["operation"] = operation, |
| 70 | ["paths"] = paths, ["proof"] = Protocol.Proof(secret, "client", nonce, profile.VM, profile.SID, session, operation, paths) }, connect.Token); |
| 71 | if (operation == "network-stream") connect.CancelAfter(TimeSpan.FromSeconds(20)); |
| 72 | Phase = "hello"; var hello = await Protocol.Read(stream, 16384, connect.Token) ?? throw new EndOfStreamException(); |
| 73 | if (hello["error"] != null || hello["version"]?.GetValue<int>() != 1 || hello["session"]?.GetValue<string>() != session) throw new IOException("guest_unavailable"); |
| 74 | Phase = "transfer"; if (operation == "status") { await Protocol.Write(Console.OpenStandardOutput(), hello, lifetime.Token); return; } |
| 75 | if (operation != "stream" && operation != "diagnostics" && hello["available"]?.GetValue<bool>() != true) throw new IOException("requires_gui_login"); |
| 76 | if (operation == "import") |
| 77 | { |
| 78 | await Protocol.SendFrames(Console.OpenStandardInput(), stream, lifetime.Token); |
| 79 | var result = await Protocol.Read(stream, Protocol.PathLimit, lifetime.Token) ?? throw new EndOfStreamException(); |
| 80 | Protocol.Paths(result["paths"]); await Protocol.Write(Console.OpenStandardOutput(), result, lifetime.Token); |
| 81 | } |
| 82 | else if (operation == "export") |
| 83 | { |
| 84 | await Protocol.ReceiveFrames(stream, Console.OpenStandardOutput(), lifetime.Token); |
| 85 | var result = await Protocol.Read(stream, 4096, lifetime.Token) ?? throw new EndOfStreamException(); |
| 86 | if (result["complete"]?.GetValue<bool>() != true) throw new IOException("archive_incomplete"); |
| 87 | } |
| 88 | else |
| 89 | { |
| 90 | if (operation == "stream") await Protocol.Write(Console.OpenStandardOutput(), Protocol.PublicHello(hello), lifetime.Token); |
| 91 | |
| 92 | |
| 93 | |
| 94 | if (operation == "network-stream") |
| 95 | { |
| 96 | if (hello["os"]?.GetValue<string>() != "windows" || hello["network"]?.GetValue<string>() != "packet" || |
| 97 | hello["vm_id"]?.GetValue<string>() != profile.VM.ToString("D") || hello["gui_user_sid"]?.GetValue<string>() != profile.SID) |
| 98 | throw new IOException("network_identity_invalid"); |
| 99 | await Protocol.Write(Console.OpenStandardError(), new() { ["network_ready"] = true, ["version"] = 1, |
| 100 | ["vm_id"] = profile.VM.ToString("D"), ["gui_user_sid"] = profile.SID, |
| 101 | ["session"] = session, ["network"] = "packet", ["available"] = true }, lifetime.Token); |
| 102 | } |
| 103 | var input = Task.Run(async () => { await Console.OpenStandardInput().CopyToAsync(stream, lifetime.Token); socket.Shutdown(SocketShutdown.Send); }); |
| 104 | var output = stream.CopyToAsync(Console.OpenStandardOutput(), lifetime.Token); |
| 105 | await output; lifetime.Cancel(); try { await input; } catch (OperationCanceledException) { } |
| 106 | } |
| 107 | } |
| 108 | finally { CryptographicOperations.ZeroMemory(secret); } |
| 109 | } |
| 110 | } |