| 1 | using System.Buffers.Binary; |
| 2 | using System.Net; |
| 3 | using System.Net.Sockets; |
| 4 | using System.Security.Cryptography; |
| 5 | using System.Text; |
| 6 | using System.Text.Json; |
| 7 | using System.Text.Json.Nodes; |
| 8 | |
| 9 | namespace Cage.GuestClipboard; |
| 10 | |
| 11 | internal static class Protocol |
| 12 | { |
| 13 | internal static readonly Guid Service = new("f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fa"); |
| 14 | internal static readonly Guid Parent = new("a42e7cda-d03f-480c-9cc2-a4de20abb878"); |
| 15 | internal const int WireLimit = 30 << 20, PathLimit = 1 << 20, TextLimit = 2 << 20, PngLimit = 20 << 20; |
| 16 | internal static readonly UTF8Encoding Utf8 = new(false, true); |
| 17 | internal static JsonObject PublicHello(JsonObject hello) => new() { ["hello"] = hello }; |
| 18 | |
| 19 | |
| 20 | |
| 21 | internal static async Task<JsonObject?> Read(Stream input, int limit, CancellationToken token) |
| 22 | { |
| 23 | if (input is ReadAheadStream buffered) |
| 24 | { |
| 25 | var bytes = await buffered.Line(limit, token); |
| 26 | if (bytes == null) return null; |
| 27 | return JsonNode.Parse(Utf8.GetString(bytes)) as JsonObject ?? throw new InvalidDataException("message_invalid"); |
| 28 | } |
| 29 | using var line = new MemoryStream(); |
| 30 | var one = new byte[1]; |
| 31 | while (true) |
| 32 | { |
| 33 | if (await input.ReadAsync(one, token) == 0) |
| 34 | { |
| 35 | if (line.Length == 0) return null; |
| 36 | throw new EndOfStreamException(); |
| 37 | } |
| 38 | if (one[0] == 10) break; |
| 39 | if (line.Length >= limit) throw new InvalidDataException("message_limit"); |
| 40 | line.WriteByte(one[0]); |
| 41 | } |
| 42 | return JsonNode.Parse(Utf8.GetString(line.GetBuffer(), 0, (int)line.Length)) as JsonObject |
| 43 | ?? throw new InvalidDataException("message_invalid"); |
| 44 | } |
| 45 | |
| 46 | internal static async Task Write(Stream output, JsonObject data, CancellationToken token) |
| 47 | { |
| 48 | var bytes = Utf8.GetBytes(data.ToJsonString()); |
| 49 | if (bytes.Length > WireLimit) throw new InvalidDataException("message_limit"); |
| 50 | await output.WriteAsync(bytes, token); |
| 51 | await output.WriteAsync(new byte[] { 10 }, token); |
| 52 | await output.FlushAsync(token); |
| 53 | } |
| 54 | |
| 55 | internal static string[] Paths(JsonNode? value) |
| 56 | { |
| 57 | if (value is not JsonArray a || a.Count is < 1 or > 100) throw new InvalidDataException("selection_invalid"); |
| 58 | var paths = a.Select(x => x?.GetValue<string>() ?? "").ToArray(); |
| 59 | if (paths.Any(x => string.IsNullOrWhiteSpace(x) || x.Contains('\0') || !Path.IsPathFullyQualified(x)) || |
| 60 | Utf8.GetByteCount(a.ToJsonString()) > PathLimit) |
| 61 | throw new InvalidDataException("selection_invalid"); |
| 62 | return paths; |
| 63 | } |
| 64 | |
| 65 | internal static void Png(byte[] data) |
| 66 | { |
| 67 | ReadOnlySpan<byte> signature = [137, 80, 78, 71, 13, 10, 26, 10]; |
| 68 | if (data.Length is < 33 or > PngLimit || !data.AsSpan(0, 8).SequenceEqual(signature) || |
| 69 | !data.AsSpan(12, 4).SequenceEqual("IHDR"u8)) throw new InvalidDataException("image_invalid"); |
| 70 | var w = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(16, 4)); |
| 71 | var h = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(20, 4)); |
| 72 | if (w == 0 || h == 0 || (ulong)w * h > 40_000_000) throw new InvalidDataException("image_limit"); |
| 73 | } |
| 74 | |
| 75 | internal static string Proof(byte[] secret, string role, string nonce, Guid vm, string sid, string session, string operation, JsonNode? paths) |
| 76 | { |
| 77 | var content = new JsonArray(role, nonce, vm.ToString("D"), sid, session, operation, paths?.ToJsonString() ?? "").ToJsonString(); |
| 78 | return Convert.ToBase64String(HMACSHA256.HashData(secret, Utf8.GetBytes(content))); |
| 79 | } |
| 80 | |
| 81 | internal static bool EqualProof(string expected, string? actual) |
| 82 | { |
| 83 | try { return CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(expected), Convert.FromBase64String(actual ?? "")); } |
| 84 | catch (FormatException) { return false; } |
| 85 | } |
| 86 | |
| 87 | |
| 88 | |
| 89 | internal static async Task SendFrames(Stream input, Stream output, CancellationToken token) |
| 90 | { |
| 91 | var buffer = new byte[64 << 10]; var header = new byte[4]; |
| 92 | int n; |
| 93 | while ((n = await input.ReadAsync(buffer, token)) != 0) |
| 94 | { |
| 95 | BinaryPrimitives.WriteUInt32LittleEndian(header, (uint)n); |
| 96 | await output.WriteAsync(header, token); await output.WriteAsync(buffer.AsMemory(0, n), token); |
| 97 | } |
| 98 | Array.Clear(header); await output.WriteAsync(header, token); await output.FlushAsync(token); |
| 99 | } |
| 100 | |
| 101 | internal static async Task ReceiveFrames(Stream input, Stream output, CancellationToken token) |
| 102 | { |
| 103 | var buffer = new byte[64 << 10]; var header = new byte[4]; |
| 104 | while (true) |
| 105 | { |
| 106 | await input.ReadExactlyAsync(header, token); |
| 107 | var n = BinaryPrimitives.ReadUInt32LittleEndian(header); |
| 108 | if (n == 0) break; |
| 109 | if (n > buffer.Length) throw new InvalidDataException("frame_invalid"); |
| 110 | await input.ReadExactlyAsync(buffer.AsMemory(0, (int)n), token); |
| 111 | await output.WriteAsync(buffer.AsMemory(0, (int)n), token); |
| 112 | } |
| 113 | await output.FlushAsync(token); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | internal sealed class HyperVEndPoint(Guid vm, Guid service) : EndPoint |
| 118 | { |
| 119 | internal Guid VM { get; } = vm; |
| 120 | internal Guid Service { get; } = service; |
| 121 | public override AddressFamily AddressFamily => (AddressFamily)34; |
| 122 | public override SocketAddress Serialize() |
| 123 | { |
| 124 | var address = new SocketAddress(AddressFamily, 36); |
| 125 | var bytes = VM.ToByteArray().Concat(Service.ToByteArray()).ToArray(); |
| 126 | for (var i = 0; i < bytes.Length; i++) address[i + 4] = bytes[i]; |
| 127 | return address; |
| 128 | } |
| 129 | public override EndPoint Create(SocketAddress address) |
| 130 | { |
| 131 | if (address.Family != AddressFamily || address.Size != 36) throw new InvalidDataException("endpoint_invalid"); |
| 132 | var vmBytes = new byte[16]; var serviceBytes = new byte[16]; |
| 133 | for (var i = 0; i < 16; i++) { vmBytes[i] = address[i + 4]; serviceBytes[i] = address[i + 20]; } |
| 134 | return new HyperVEndPoint(new Guid(vmBytes), new Guid(serviceBytes)); |
| 135 | } |
| 136 | internal static Socket Socket() => new((AddressFamily)34, SocketType.Stream, (ProtocolType)1); |
| 137 | } |