// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Sendspin's encryption: a Noise handshake at the start of the connection, //! then every message sealed. //! //! The handshake is `Noise_KKpsk2_25519_ChaChaPoly_SHA256`, the server the //! initiator and the client the responder, run in cleartext JSON: //! //! 1. the client sends `client/init`: its `client_id` -- its static public //! key, base64url -- the protocol `version` and the `suite`; //! 2. the server sends `server/init`, its own `server_id` and `version`, and //! at once `noise/handshake` with Noise message 1, whose payload names //! the PSK in play by `psk_id`; //! 3. the client sends `noise/handshake` with message 2, payload `{}`. //! //! The prologue is the two init messages exactly as they were sent. After //! the handshake every WebSocket frame is binary and sealed; a sealed //! plaintext's first byte says what it is -- 0 a JSON message, anything //! else a binary one, whose own type byte it is -- and a message longer than //! a Noise message can be goes as fragments, types 2 (more follows, the //! first carrying the message's type after it) and 3 (the last). //! //! A client that has never paired is admitted with the sentinel PSK, a //! published constant: the connection is encrypted and knows its peer's key, //! but nothing about either is proven. That is enough for a player, which //! the server approves as a guest; a paired client has a long-term PSK //! instead, which this does not implement. const std = @import("std"); const noise = @import("noise"); const Sha256 = std.crypto.hash.sha2.Sha256; const b64url = std.base64.url_safe_no_pad; pub const version = 1; pub const suite = "25519_ChaChaPoly_SHA256"; pub const protocol_name = "Noise_KKpsk2_" ++ suite; /// The published PSK used when no other applies: authenticates nothing. pub const sentinel_psk: [32]u8 = blk: { @setEvalBranchQuota(10_000); var out: [32]u8 = undefined; Sha256.hash("sendspin-sentinel-psk-v1", &out, .{}); break :blk out; }; /// How long a peer id is: a 32-byte key in unpadded base64url. pub const peer_id_len = 43; pub const PeerId = [peer_id_len]u8; /// A static public key as the protocol names it: `client_id`, `server_id`. pub fn peerId(public: [32]u8) PeerId { var out: PeerId = undefined; _ = b64url.Encoder.encode(&out, &public); return out; } /// The key a peer id names; `error.InvalidPeerId` if it names none. pub fn peerKey(id: []const u8) error{InvalidPeerId}![32]u8 { if (id.len != peer_id_len) return error.InvalidPeerId; var out: [32]u8 = undefined; b64url.Decoder.decode(&out, id) catch return error.InvalidPeerId; return out; } /// `psk_id`: base64url of SHA-256 over a label and the PSK. pub fn pskId(psk: [32]u8) PeerId { var digest: [32]u8 = undefined; var h = Sha256.init(.{}); h.update("sendspin-psk-id-v1"); h.update(&psk); h.final(&digest); return peerId(digest); } pub const Error = noise.HandshakeState.Error || error{ /// The server said something the handshake does not allow at that /// point, or said it in a form that does not parse. UnexpectedMessage, /// A protocol version other than 1. UnsupportedVersion, InvalidPeerId, /// Message 1 named a PSK this client does not hold, or holds for another /// server: the server believes it is paired with it. UnknownPsk, /// `client/init` asked for a cipher suite other than the two there are. UnsupportedSuite, OutOfMemory, }; /// The two cipher suites a client may pick, and the Noise protocol each /// names. pub const suites = [_][]const u8{ "25519_ChaChaPoly_SHA256", "25519_AESGCM_SHA256" }; fn protocolFor(s: []const u8) Error![]const u8 { inline for (suites) |known| if (std.mem.eql(u8, s, known)) return "Noise_KKpsk2_" ++ known; return error.UnsupportedSuite; } /// Where a server keeps the long-term PSKs it has made by pairing: the one /// it holds for the client `client_id`, if it has paired with it. pub const ServerPskStore = struct { context: *anyopaque, lookup: *const fn (context: *anyopaque, client_id: []const u8) ?[32]u8, }; /// The server's side of the handshake: in Sendspin the server is Noise's /// initiator, though the client speaks first. Fed the client's text frames /// and handing back its own. pub const ServerHandshake = struct { gpa: std.mem.Allocator, identity: noise.KeyPair, random: std.Random, psks: ?ServerPskStore = null, hs: ?noise.HandshakeState = null, /// Who the client is, from `client/init`: its key, which the handshake /// then proves. client_id: PeerId = undefined, /// The PSK message 1 named. category: Category = .sentinel, /// What `clientInit` hands back, owned here. server_init: []u8 = &.{}, message_1: []u8 = &.{}, pub fn init(gpa: std.mem.Allocator, identity: noise.KeyPair, random: std.Random, psks: ?ServerPskStore) ServerHandshake { return .{ .gpa = gpa, .identity = identity, .random = random, .psks = psks }; } /// The handshake again, inside the sealed channel, after pairing, on /// the long-term PSK it made: the previous handshake's hash as the /// prologue. `message1Sealed` is the first message, to go out sealed /// as an ordinary JSON message; the client's reply comes back the same /// way, to `message2`. pub fn initRehandshake(gpa: std.mem.Allocator, identity: noise.KeyPair, random: std.Random, client_id: PeerId, prologue: []const u8, psk: [32]u8) Error!ServerHandshake { var self: ServerHandshake = .{ .gpa = gpa, .identity = identity, .random = random, .client_id = client_id, .category = .long_term }; self.hs = try noise.HandshakeState.init(.{ .protocol_name = protocol_name, .role = .initiator, .prologue = prologue, .s = identity, .rs = try peerKey(&client_id), .psks = &.{psk}, .random = random, }); self.message_1 = try self.writeMessage1(psk); return self; } pub fn deinit(self: *ServerHandshake) void { self.gpa.free(self.server_init); self.gpa.free(self.message_1); } pub const Reply = struct { /// `server/init`, to send first. server_init: []const u8, /// `noise/handshake` with message 1, to send straight after. message_1: []const u8, }; /// Take `client/init`, and return what goes back: `server/init` and /// message 1, on the client's long-term PSK if the store has one for /// it, the sentinel if not. Both are owned by the handshake. pub fn clientInit(self: *ServerHandshake, text: []const u8) Error!Reply { var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); const a = arena.allocator(); const Msg = struct { type: []const u8, payload: struct { client_id: []const u8, version: i64, suite: []const u8 = suite } }; const m = std.json.parseFromSliceLeaky(Msg, a, text, .{ .ignore_unknown_fields = true }) catch return error.UnexpectedMessage; if (!std.mem.eql(u8, m.type, "client/init")) return error.UnexpectedMessage; if (m.payload.version != version) return error.UnsupportedVersion; const name = try protocolFor(m.payload.suite); const client_key = try peerKey(m.payload.client_id); self.client_id = m.payload.client_id[0..peer_id_len].*; const psk: [32]u8 = blk: { if (self.psks) |store| if (store.lookup(store.context, &self.client_id)) |found| { self.category = .long_term; break :blk found; }; self.category = .sentinel; break :blk sentinel_psk; }; const server_id = peerId(self.identity.public); self.server_init = try std.fmt.allocPrint(self.gpa, \\{{"type":"server/init","payload":{{"server_id":"{s}","version":{d}}}}} , .{ &server_id, version }); const prologue = try std.mem.concat(a, u8, &.{ text, self.server_init }); self.hs = try noise.HandshakeState.init(.{ .protocol_name = name, .role = .initiator, .prologue = prologue, .s = self.identity, .rs = client_key, .psks = &.{psk}, .random = self.random, }); self.message_1 = try self.writeMessage1(psk); return .{ .server_init = self.server_init, .message_1 = self.message_1 }; } fn writeMessage1(self: *ServerHandshake, psk: [32]u8) Error![]u8 { const hs = &self.hs.?; var payload_buf: [96]u8 = undefined; const payload = std.fmt.bufPrint(&payload_buf, "{{\"psk_id\":\"{s}\"}}", .{&pskId(psk)}) catch unreachable; var out: [256]u8 = undefined; const m1 = try hs.writeMessage(payload, &out); var data_buf: [b64url.Encoder.calcSize(256)]u8 = undefined; return std.fmt.allocPrint(self.gpa, \\{{"type":"noise/handshake","payload":{{"data":"{s}"}}}} , .{b64url.Encoder.encode(&data_buf, m1)}); } /// Message 1 of a re-handshake, to send sealed. pub fn message1Sealed(self: *const ServerHandshake) []const u8 { return self.message_1; } /// Take `noise/handshake` with message 2, whose payload is the empty /// object. After this, `transport` has the ciphers. pub fn message2(self: *ServerHandshake, text: []const u8) Error!void { const hs = &(self.hs orelse return error.UnexpectedMessage); var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); const a = arena.allocator(); const ciphertext = try handshakeData(a, text); const payload = try hs.readMessage(ciphertext, try a.alloc(u8, ciphertext.len)); const v = std.json.parseFromSliceLeaky(std.json.Value, a, payload, .{}) catch return error.UnexpectedMessage; if (v != .object) return error.UnexpectedMessage; } pub fn handshakeHash(self: *const ServerHandshake) [32]u8 { return self.hs.?.handshakeHash()[0..32].*; } pub fn transport(self: *const ServerHandshake) Error!noise.Transport { const hs = &(self.hs orelse return error.Unfinished); return hs.split(); } }; /// Where a client keeps the long-term PSKs it has made by pairing: the one /// for `psk_id`, if it has it and it was made with the server `server_id`. /// A PSK is only ever good with the server it was paired with. pub const PskLookup = struct { context: *anyopaque, lookup: *const fn (context: *anyopaque, psk_id: []const u8, server_id: []const u8) ?[32]u8, }; /// Which PSK a handshake ended on: the sentinel, which anyone knows and /// which proves nothing, or a long-term one made by pairing. pub const Category = enum { sentinel, long_term }; /// The client's side of the handshake, fed the server's text frames one at /// a time and handing back its own. pub const ClientHandshake = struct { gpa: std.mem.Allocator, identity: noise.KeyPair, random: std.Random, /// `client/init` exactly as it was sent, for the prologue. init_text: []u8 = &.{}, hs: ?noise.HandshakeState = null, server_id: PeerId = undefined, /// The long-term PSKs a message 1 may name, besides the sentinel. psks: ?PskLookup = null, /// The PSK message 1 named, once it has been read. category: Category = .sentinel, pub fn init(gpa: std.mem.Allocator, identity: noise.KeyPair, random: std.Random) ClientHandshake { return .{ .gpa = gpa, .identity = identity, .random = random }; } /// The handshake again, inside the sealed channel, after pairing: with /// the same server and no `client/init` or `server/init`, the previous /// handshake's hash as the prologue, and the long-term PSK the pairing /// made. Message 1 arrives, sealed, as the next text message; the reply /// goes out sealed under the old keys, and `transport` has the new. pub fn initRehandshake(gpa: std.mem.Allocator, identity: noise.KeyPair, random: std.Random, server_id: PeerId, prologue: []const u8, psks: ?PskLookup) Error!ClientHandshake { var self: ClientHandshake = .{ .gpa = gpa, .identity = identity, .random = random, .server_id = server_id, .psks = psks }; self.hs = try noise.HandshakeState.init(.{ .protocol_name = protocol_name, .role = .responder, .prologue = prologue, .s = identity, .rs = try peerKey(&server_id), .random = random, }); return self; } /// The handshake hash, once it is over: what pairing binds its PIN and /// its PAKE to, and the prologue of the next handshake on the same /// connection. pub fn handshakeHash(self: *const ClientHandshake) [32]u8 { return self.hs.?.handshakeHash()[0..32].*; } pub fn deinit(self: *ClientHandshake) void { self.gpa.free(self.init_text); } /// The `client/init` to send first. pub fn begin(self: *ClientHandshake) Error![]const u8 { const id = peerId(self.identity.public); self.init_text = try std.fmt.allocPrint(self.gpa, \\{{"type":"client/init","payload":{{"client_id":"{s}","version":{d},"suite":"{s}"}}}} , .{ &id, version, suite }); return self.init_text; } /// Take `server/init`: who the server is, which the handshake is then /// built around. pub fn serverInit(self: *ClientHandshake, text: []const u8) Error!void { var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); const Msg = struct { type: []const u8, payload: struct { server_id: []const u8, version: i64 } }; const m = std.json.parseFromSliceLeaky(Msg, arena.allocator(), text, .{ .ignore_unknown_fields = true }) catch return error.UnexpectedMessage; if (!std.mem.eql(u8, m.type, "server/init")) return error.UnexpectedMessage; if (m.payload.version != version) return error.UnsupportedVersion; const server_key = try peerKey(m.payload.server_id); self.server_id = m.payload.server_id[0..peer_id_len].*; const prologue = try std.mem.concat(arena.allocator(), u8, &.{ self.init_text, text }); self.hs = try noise.HandshakeState.init(.{ .protocol_name = protocol_name, .role = .responder, .prologue = prologue, .s = self.identity, .rs = server_key, .random = self.random, }); } /// Take `noise/handshake` with message 1, and return the one to send /// back with message 2. After this, `transport` has the ciphers. pub fn message1(self: *ClientHandshake, text: []const u8) Error![]u8 { const hs = &(self.hs orelse return error.UnexpectedMessage); var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); const a = arena.allocator(); const ciphertext = try handshakeData(a, text); const payload = try hs.readMessage(ciphertext, try a.alloc(u8, ciphertext.len)); const P = struct { psk_id: []const u8 }; const p = std.json.parseFromSliceLeaky(P, a, payload, .{ .ignore_unknown_fields = true }) catch return error.UnexpectedMessage; const psk: [32]u8 = if (std.mem.eql(u8, p.psk_id, &pskId(sentinel_psk))) blk: { self.category = .sentinel; break :blk sentinel_psk; } else blk: { const store = self.psks orelse return error.UnknownPsk; const found = store.lookup(store.context, p.psk_id, &self.server_id) orelse return error.UnknownPsk; self.category = .long_term; break :blk found; }; try hs.setPsk(0, psk); var out: [256]u8 = undefined; const message = try hs.writeMessage("{}", &out); var data_buf: [b64url.Encoder.calcSize(256)]u8 = undefined; const data = b64url.Encoder.encode(&data_buf, message); return std.fmt.allocPrint(self.gpa, \\{{"type":"noise/handshake","payload":{{"data":"{s}"}}}} , .{data}); } /// The ciphers for the rest of the connection. pub fn transport(self: *const ClientHandshake) Error!noise.Transport { const hs = &(self.hs orelse return error.Unfinished); return hs.split(); } }; fn handshakeData(a: std.mem.Allocator, text: []const u8) Error![]u8 { const Msg = struct { type: []const u8, payload: struct { data: []const u8 } }; const m = std.json.parseFromSliceLeaky(Msg, a, text, .{ .ignore_unknown_fields = true }) catch return error.UnexpectedMessage; if (!std.mem.eql(u8, m.type, "noise/handshake")) return error.UnexpectedMessage; const len = b64url.Decoder.calcSizeForSlice(m.payload.data) catch return error.UnexpectedMessage; const out = try a.alloc(u8, len); b64url.Decoder.decode(out, m.payload.data) catch return error.UnexpectedMessage; return out; } /// Plaintext type bytes. const json_body = 0; const fragment_more = 2; const fragment_end = 3; /// The most plaintext one sealed frame carries: Noise's 65535 less the tag. pub const max_plaintext = noise.HandshakeState.max_message_len - noise.Cipher.tag_len; /// The most a reassembled message may come to, against a peer sending /// fragments without end. pub const max_message = 64 << 20; /// A message opened from the channel, borrowed until the next `open`. pub const Opened = union(enum) { /// A JSON message. text: []const u8, /// A binary message, its type byte first. binary: []const u8, }; /// The sealed channel after the handshake. Sending and receiving each have a /// cipher of their own, and each side must be used from one task at a time /// -- the nonces go out in the order the frames do. pub const Channel = struct { gpa: std.mem.Allocator, transport: noise.Transport, /// Where each frame is sealed and each is opened: one Noise message. seal_buf: []u8, open_buf: []u8, /// A fragmented message being put back together, its type byte first. reassembly: std.ArrayList(u8) = .empty, reassembling: bool = false, pub fn init(gpa: std.mem.Allocator, transport: noise.Transport) error{OutOfMemory}!Channel { const seal_buf = try gpa.alloc(u8, noise.HandshakeState.max_message_len); errdefer gpa.free(seal_buf); return .{ .gpa = gpa, .transport = transport, .seal_buf = seal_buf, .open_buf = try gpa.alloc(u8, noise.HandshakeState.max_message_len), }; } pub fn deinit(self: *Channel) void { self.gpa.free(self.seal_buf); self.gpa.free(self.open_buf); self.reassembly.deinit(self.gpa); } /// Seal a JSON message, handing each frame to `sink`. pub fn sealText(self: *Channel, text: []const u8, sink: anytype) !void { return self.sealTyped(json_body, text, sink); } /// Seal a binary message -- `data` starting with its own type byte -- /// handing each frame to `sink`. The type bytes that mark a sealed /// frame as JSON or as a fragment are not binary types, and a message /// with one would open as something else: `error.InvalidMessageType`. pub fn sealBinary(self: *Channel, data: []const u8, sink: anytype) !void { if (data.len == 0) return error.InvalidMessageType; switch (data[0]) { json_body, fragment_more, fragment_end => return error.InvalidMessageType, else => {}, } return self.sealTyped(data[0], data[1..], sink); } /// `sink.frame(bytes)` is called once for each frame, in order, and must /// send it before returning: the next seal reuses the buffer. fn sealTyped(self: *Channel, kind: u8, body: []const u8, sink: anytype) !void { var plain: [max_plaintext]u8 = undefined; if (body.len + 1 <= max_plaintext) { plain[0] = kind; @memcpy(plain[1..][0..body.len], body); try sink.frame(try self.transport.encrypt(plain[0 .. body.len + 1], self.seal_buf)); return; } // The first fragment carries the message's type after its own. var rest = body; plain[0] = fragment_more; plain[1] = kind; const first = max_plaintext - 2; @memcpy(plain[2..][0..first], rest[0..first]); try sink.frame(try self.transport.encrypt(plain[0..max_plaintext], self.seal_buf)); rest = rest[first..]; while (rest.len > 0) { const n = @min(rest.len, max_plaintext - 1); plain[0] = if (n == rest.len) fragment_end else fragment_more; @memcpy(plain[1..][0..n], rest[0..n]); try sink.frame(try self.transport.encrypt(plain[0 .. n + 1], self.seal_buf)); rest = rest[n..]; } } pub const OpenError = noise.symmetric.Error || error{ OutOfMemory, InvalidFrame, MessageTooLarge }; /// Open one frame: the message it completes, or null while a /// fragmented one is still arriving. pub fn open(self: *Channel, frame: []const u8) OpenError!?Opened { const plain = try self.transport.decrypt(frame, self.open_buf); if (plain.len == 0) return error.InvalidFrame; switch (plain[0]) { fragment_more => { if (!self.reassembling) { if (plain.len < 2) return error.InvalidFrame; self.reassembly.clearRetainingCapacity(); try self.reassembly.append(self.gpa, plain[1]); try self.reassembly.appendSlice(self.gpa, plain[2..]); self.reassembling = true; } else { if (self.reassembly.items.len + plain.len > max_message) return error.MessageTooLarge; try self.reassembly.appendSlice(self.gpa, plain[1..]); } return null; }, fragment_end => { if (!self.reassembling) return error.InvalidFrame; if (self.reassembly.items.len + plain.len > max_message) return error.MessageTooLarge; try self.reassembly.appendSlice(self.gpa, plain[1..]); self.reassembling = false; return typed(self.reassembly.items); }, else => { if (self.reassembling) return error.InvalidFrame; return typed(plain); }, } } fn typed(plain: []const u8) Opened { return if (plain[0] == json_body) .{ .text = plain[1..] } else .{ .binary = plain }; } }; const testing = std.testing; test "peer ids and the sentinel's psk_id" { var key: [32]u8 = undefined; for (&key, 0..) |*b, i| b.* = @intCast(i); const id = peerId(key); try testing.expectEqual(@as(usize, 43), id.len); try testing.expectEqualSlices(u8, &key, &try peerKey(&id)); try testing.expectError(error.InvalidPeerId, peerKey("short")); // What aiosendspin 9.1.1 computes for its sentinel: base64url, no // padding, of SHA-256("sendspin-psk-id-v1" || SHA-256("sendspin-sentinel-psk-v1")). var check: [32]u8 = undefined; Sha256.hash("sendspin-sentinel-psk-v1", &check, .{}); try testing.expectEqualSlices(u8, &check, &sentinel_psk); } /// Frames a test keeps, as a WebSocket would carry them. const Frames = struct { list: std.ArrayList([]u8) = .empty, fn frame(self: *Frames, bytes: []const u8) !void { try self.list.append(testing.allocator, try testing.allocator.dupe(u8, bytes)); } fn deinit(self: *Frames) void { for (self.list.items) |f| testing.allocator.free(f); self.list.deinit(testing.allocator); } }; test "the client's handshake against a server played by zig-noise" { var prng: std.Random.DefaultPrng = .init(7); const random = prng.random(); const server = noise.KeyPair.generate(random); const client = noise.KeyPair.generate(random); var ch: ClientHandshake = .init(testing.allocator, client, random); defer ch.deinit(); const client_init = try ch.begin(); // The server's side, as aiosendspin runs it. const server_id = peerId(server.public); const server_init = try std.fmt.allocPrint(testing.allocator, \\{{"type":"server/init","payload":{{"server_id":"{s}","version":1}}}} , .{&server_id}); defer testing.allocator.free(server_init); const prologue = try std.mem.concat(testing.allocator, u8, &.{ client_init, server_init }); defer testing.allocator.free(prologue); var s = try noise.HandshakeState.init(.{ .protocol_name = protocol_name, .role = .initiator, .prologue = prologue, .s = server, .rs = client.public, .psks = &.{sentinel_psk}, .random = random, }); var m1_buf: [256]u8 = undefined; const psk_payload = try std.fmt.allocPrint(testing.allocator, "{{\"psk_id\":\"{s}\"}}", .{&pskId(sentinel_psk)}); defer testing.allocator.free(psk_payload); const m1 = try s.writeMessage(psk_payload, &m1_buf); var data_buf: [512]u8 = undefined; const hs1 = try std.fmt.allocPrint(testing.allocator, \\{{"type":"noise/handshake","payload":{{"data":"{s}"}}}} , .{b64url.Encoder.encode(&data_buf, m1)}); defer testing.allocator.free(hs1); try ch.serverInit(server_init); const hs2 = try ch.message1(hs1); defer testing.allocator.free(hs2); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var payload_buf: [64]u8 = undefined; try testing.expectEqualStrings("{}", try s.readMessage(try handshakeData(arena.allocator(), hs2), &payload_buf)); // And then messages both ways, one of them too big for one frame. var client_channel: Channel = try .init(testing.allocator, try ch.transport()); defer client_channel.deinit(); var server_channel: Channel = try .init(testing.allocator, try s.split()); defer server_channel.deinit(); var frames: Frames = .{}; defer frames.deinit(); try server_channel.sealText("{\"type\":\"server/hello\"}", &frames); const big = try testing.allocator.alloc(u8, 150_000); defer testing.allocator.free(big); for (big, 0..) |*b, i| b.* = @truncate(i); big[0] = 4; // audio try server_channel.sealBinary(big, &frames); try testing.expectEqual(@as(usize, 1 + 3), frames.list.items.len); const hello = (try client_channel.open(frames.list.items[0])).?; try testing.expectEqualStrings("{\"type\":\"server/hello\"}", hello.text); try testing.expectEqual(@as(?Opened, null), try client_channel.open(frames.list.items[1])); try testing.expectEqual(@as(?Opened, null), try client_channel.open(frames.list.items[2])); const audio = (try client_channel.open(frames.list.items[3])).?; try testing.expectEqualSlices(u8, big, audio.binary); var back: Frames = .{}; defer back.deinit(); try client_channel.sealText("{\"type\":\"client/hello\"}", &back); try testing.expectEqualStrings("{\"type\":\"client/hello\"}", (try server_channel.open(back.list.items[0])).?.text); } test "a message 1 naming a PSK the client does not hold is refused" { var prng: std.Random.DefaultPrng = .init(8); const random = prng.random(); const server = noise.KeyPair.generate(random); const client = noise.KeyPair.generate(random); var ch: ClientHandshake = .init(testing.allocator, client, random); defer ch.deinit(); const client_init = try ch.begin(); const server_id = peerId(server.public); const server_init = try std.fmt.allocPrint(testing.allocator, \\{{"type":"server/init","payload":{{"server_id":"{s}","version":1}}}} , .{&server_id}); defer testing.allocator.free(server_init); const prologue = try std.mem.concat(testing.allocator, u8, &.{ client_init, server_init }); defer testing.allocator.free(prologue); const long_term: [32]u8 = @splat(5); var s = try noise.HandshakeState.init(.{ .protocol_name = protocol_name, .role = .initiator, .prologue = prologue, .s = server, .rs = client.public, .psks = &.{long_term}, .random = random }); var buf: [256]u8 = undefined; const psk_payload = try std.fmt.allocPrint(testing.allocator, "{{\"psk_id\":\"{s}\"}}", .{&pskId(long_term)}); defer testing.allocator.free(psk_payload); const m1 = try s.writeMessage(psk_payload, &buf); var data_buf: [512]u8 = undefined; const hs1 = try std.fmt.allocPrint(testing.allocator, \\{{"type":"noise/handshake","payload":{{"data":"{s}"}}}} , .{b64url.Encoder.encode(&data_buf, m1)}); defer testing.allocator.free(hs1); try ch.serverInit(server_init); try testing.expectError(error.UnknownPsk, ch.message1(hs1)); } /// A long-term PSK store holding one client's PSK. const OnePsk = struct { client_id: PeerId, psk: [32]u8, fn store(self: *OnePsk) ServerPskStore { return .{ .context = self, .lookup = lookup }; } fn lookup(context: *anyopaque, client_id: []const u8) ?[32]u8 { const self: *OnePsk = @ptrCast(@alignCast(context)); return if (std.mem.eql(u8, client_id, &self.client_id)) self.psk else null; } fn clientLookup(context: *anyopaque, psk_id: []const u8, _: []const u8) ?[32]u8 { const self: *OnePsk = @ptrCast(@alignCast(context)); return if (std.mem.eql(u8, psk_id, &pskId(self.psk))) self.psk else null; } }; /// Both sides of a handshake, each this module's own, and a message each /// way after it. fn shake(random: std.Random, server: noise.KeyPair, client: noise.KeyPair, server_psks: ?ServerPskStore, client_psks: ?PskLookup, client_suite: []const u8) !struct { Category, Category } { var sh: ServerHandshake = .init(testing.allocator, server, random, server_psks); defer sh.deinit(); var ch: ClientHandshake = .init(testing.allocator, client, random); defer ch.deinit(); ch.psks = client_psks; const init_text = try ch.begin(); const sent = if (std.mem.eql(u8, client_suite, suite)) init_text else blk: { // A client that picks the other suite. const other = try std.mem.replaceOwned(u8, testing.allocator, init_text, suite, client_suite); testing.allocator.free(ch.init_text); ch.init_text = other; break :blk other; }; const reply = try sh.clientInit(sent); try testing.expectEqualSlices(u8, &peerId(client.public), &sh.client_id); try ch.serverInit(reply.server_init); if (!std.mem.eql(u8, client_suite, suite)) { // The client here only speaks ChaChaPoly; the other suite is the // server's to accept, which getting this far shows. return .{ sh.category, ch.category }; } const m2 = try ch.message1(reply.message_1); defer testing.allocator.free(m2); try sh.message2(m2); try testing.expectEqual(sh.handshakeHash(), ch.handshakeHash()); var server_channel: Channel = try .init(testing.allocator, try sh.transport()); defer server_channel.deinit(); var client_channel: Channel = try .init(testing.allocator, try ch.transport()); defer client_channel.deinit(); var frames: Frames = .{}; defer frames.deinit(); try server_channel.sealText("{\"type\":\"server/hello\"}", &frames); try testing.expectEqualStrings("{\"type\":\"server/hello\"}", (try client_channel.open(frames.list.items[0])).?.text); var back: Frames = .{}; defer back.deinit(); try client_channel.sealText("{\"type\":\"client/hello\"}", &back); try testing.expectEqualStrings("{\"type\":\"client/hello\"}", (try server_channel.open(back.list.items[0])).?.text); return .{ sh.category, ch.category }; } test "the server's handshake against the client's: sentinel, long-term, and the other suite" { var prng: std.Random.DefaultPrng = .init(9); const random = prng.random(); const server = noise.KeyPair.generate(random); const client = noise.KeyPair.generate(random); // Never paired: the sentinel, on both sides. const unpaired = try shake(random, server, client, null, null, suite); try testing.expectEqual(Category.sentinel, unpaired[0]); try testing.expectEqual(Category.sentinel, unpaired[1]); // Paired: the server finds the client's PSK, and the client its own. var one: OnePsk = .{ .client_id = peerId(client.public), .psk = @splat(0x42) }; const paired = try shake(random, server, client, one.store(), .{ .context = &one, .lookup = OnePsk.clientLookup }, suite); try testing.expectEqual(Category.long_term, paired[0]); try testing.expectEqual(Category.long_term, paired[1]); // A PSK for some other client is not this one's. var other: OnePsk = .{ .client_id = peerId(server.public), .psk = @splat(0x42) }; try testing.expectEqual(Category.sentinel, (try shake(random, server, client, other.store(), null, suite))[0]); _ = try shake(random, server, client, null, null, "25519_AESGCM_SHA256"); } test "the server refuses a client/init it cannot answer" { var prng: std.Random.DefaultPrng = .init(10); const random = prng.random(); const server = noise.KeyPair.generate(random); const id = peerId(noise.KeyPair.generate(random).public); const cases = .{ .{ "{\"type\":\"client/hello\",\"payload\":{}}", error.UnexpectedMessage }, .{ "not json", error.UnexpectedMessage }, .{ "{\"type\":\"client/init\",\"payload\":{\"client_id\":\"" ++ id ++ "\",\"version\":2,\"suite\":\"25519_ChaChaPoly_SHA256\"}}", error.UnsupportedVersion }, .{ "{\"type\":\"client/init\",\"payload\":{\"client_id\":\"" ++ id ++ "\",\"version\":1,\"suite\":\"448_ChaChaPoly_BLAKE2b\"}}", error.UnsupportedSuite }, .{ "{\"type\":\"client/init\",\"payload\":{\"client_id\":\"short\",\"version\":1,\"suite\":\"25519_ChaChaPoly_SHA256\"}}", error.InvalidPeerId }, }; inline for (cases) |c| { var sh: ServerHandshake = .init(testing.allocator, server, random, null); defer sh.deinit(); try testing.expectError(c[1], sh.clientInit(c[0])); } } test "the re-handshake after pairing, server and client both this module's" { var prng: std.Random.DefaultPrng = .init(11); const random = prng.random(); const server = noise.KeyPair.generate(random); const client = noise.KeyPair.generate(random); const hash: [32]u8 = @splat(0x17); const psk: [32]u8 = @splat(0x99); var one: OnePsk = .{ .client_id = peerId(client.public), .psk = psk }; var sh: ServerHandshake = try .initRehandshake(testing.allocator, server, random, peerId(client.public), &hash, psk); defer sh.deinit(); var ch: ClientHandshake = try .initRehandshake(testing.allocator, client, random, peerId(server.public), &hash, .{ .context = &one, .lookup = OnePsk.clientLookup }); defer ch.deinit(); const m2 = try ch.message1(sh.message1Sealed()); defer testing.allocator.free(m2); try sh.message2(m2); try testing.expectEqual(Category.long_term, ch.category); try testing.expectEqual(sh.handshakeHash(), ch.handshakeHash()); }