╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭───────────────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭ find file ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ ╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │ │ │http│ ssh │ │ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
937 // stream as a transport close, so callers handle both the same way. 938 if (packet[0] == SSH_MSG_DISCONNECT) { 939 conn.allocator.free(packet); 940 return error.EndOfStream; 941 } 942 if (packet[0] == SSH_MSG_KEXINIT) { 943 defer conn.allocator.free(packet); 944 _ = conn.idle.activity.fetchAdd(1, .acq_rel); 945 try runRekey(conn, packet); 946 continue; 947 } 948 _ = conn.idle.activity.fetchAdd(1, .acq_rel); 949 return packet; 950 } 951 } 952 953 /// RFC 4253 §11.4 — an unrecognized message must be answered with 954 /// SSH_MSG_UNIMPLEMENTED carrying the offending packet's sequence number. 955 fn sendUnimplemented(conn: *Conn) !void { 956 var packet: [5]u8 = undefined; 957 packet[0] = SSH_MSG_UNIMPLEMENTED; 958 // the read already advanced past the packet we're rejecting 959 std.mem.writeInt(u32, packet[1..5], @truncate(conn.cs_cipher.seq - 1), .big); 960 try conn.writePacket(&.{&packet}); 961 } 962 963 // --------------------------------------------------------------------------- 964 // SSH field encoders / decoders (RFC 4251 §5) 965 // --------------------------------------------------------------------------- 966 967 pub fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 968 var len_bytes: [4]u8 = undefined; 969 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 970 try buf.appendSlice(allocator, &len_bytes); 971 try buf.appendSlice(allocator, bytes); 972 } 973 974 pub fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 975 var total: usize = 0; 976 for (names, 0..) |name, i| { 977 if (i > 0) total += 1; // comma separator 978 total += name.len; 979 } 980 var len_bytes: [4]u8 = undefined; 981 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 982 try buf.appendSlice(allocator, &len_bytes); 983 for (names, 0..) |name, i| { 984 if (i > 0) try buf.append(allocator, ','); 985 try buf.appendSlice(allocator, name); 986 } 987 } 988 989 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 990 /// our use (X25519 shared secret) the value is always non-negative, so we 991 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 992 /// the most-significant byte is set (to keep it parsed as positive). 993 pub fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 994 var start: usize = 0; 995 while (start < bytes.len and bytes[start] == 0) start += 1; 996 const trimmed = bytes[start..]; 997 if (trimmed.len == 0) { 998 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 999 return; 1000 } 1001 const prepend = (trimmed[0] & 0x80) != 0; 1002 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 1003 var len_bytes: [4]u8 = undefined; 1004 std.mem.writeInt(u32, &len_bytes, out_len, .big); 1005 try buf.appendSlice(allocator, &len_bytes); 1006 if (prepend) try buf.append(allocator, 0); 1007 try buf.appendSlice(allocator, trimmed); 1008 } 1009 1010 /// a string field's bytes, borrowed from the packet behind a fixed reader 1011 pub fn takeString(reader: *std.Io.Reader, max_len: u32) ![]const u8 { 1012 const len = try reader.takeInt(u32, .big); 1013 if (len > max_len) return error.FieldTooLarge; 1014 return reader.take(len); 1015 } 1016 1017 // the first name in the peer's preference list that we also support (RFC 1018 // 4253 §7.1) 1019 fn firstCommonName(peer_names: []const u8, our_names: []const []const u8) ?[]const u8 { 1020 var iter = std.mem.splitScalar(u8, peer_names, ','); 1021 while (iter.next()) |name| { 1022 for (our_names) |ours| { 1023 if (std.mem.eql(u8, name, ours)) return ours; 1024 } 1025 } 1026 return null; 1027 } 1028 1029 // --------------------------------------------------------------------------- 1030 // KEXINIT (RFC 4253 §7.1) 1031 // --------------------------------------------------------------------------- 1032 1033 pub const our_kex_algos = [_][]const u8{ "mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org" }; 1034 1035 // strict kex markers (Terrapin / CVE-2023-48795 mitigation). pseudo-algorithms 1036 // carried in the initial KEXINIT's kex list: we advertise the -s form, the 1037 // client advertises the -c form. they are never selected as an actual kex 1038 // algorithm because the matcher only picks from our_kex_algos. 1039 pub const kex_strict_server = "kex-strict-s-v00@openssh.com"; 1040 pub const kex_strict_client = "kex-strict-c-v00@openssh.com"; 1041 // the client asks for EXT_INFO after the initial NEWKEYS (RFC 8308) 1042 pub const ext_info_client = "ext-info-c"; 1043 1044 const MLKem768 = std.crypto.kem.ml_kem.MLKem768; 1045 const hybrid_client_blob_len = MLKem768.PublicKey.encoded_length + X25519.public_length; // 1216 1046 const hybrid_server_blob_len = MLKem768.ciphertext_length + X25519.public_length; // 1120 1047 pub const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 1048 pub const our_userauth_algos = [_][]const u8{ "ssh-ed25519", "rsa-sha2-512", "rsa-sha2-256" }; 1049 pub const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 1050 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 1051 const our_compression = [_][]const u8{"none"}; 1052 1053 /// build a KEXINIT payload with the given algorithm name-lists 1054 pub fn buildKexInit( 1055 io: std.Io, 1056 allocator: std.mem.Allocator, 1057 kex_algos: []const []const u8, 1058 host_key_algos: []const []const u8, 1059 ciphers: []const []const u8, 1060 ) ![]u8 { 1061 var buf: std.ArrayList(u8) = .empty; 1062 errdefer buf.deinit(allocator); 1063 1064 try buf.append(allocator, SSH_MSG_KEXINIT); 1065 1066 var cookie: [16]u8 = undefined; 1067 io.random(&cookie); 1068 try buf.appendSlice(allocator, &cookie); 1069 1070 try writeNameList(&buf, allocator, kex_algos); 1071 try writeNameList(&buf, allocator, host_key_algos); 1072 try writeNameList(&buf, allocator, ciphers); // c->s 1073 try writeNameList(&buf, allocator, ciphers); // s->c 1074 try writeNameList(&buf, allocator, &our_macs); 1075 try writeNameList(&buf, allocator, &our_macs); 1076 try writeNameList(&buf, allocator, &our_compression); 1077 try writeNameList(&buf, allocator, &our_compression); 1078 try writeNameList(&buf, allocator, &.{}); // langs c->s 1079 try writeNameList(&buf, allocator, &.{}); // langs s->c 1080 try buf.append(allocator, 0); // first_kex_packet_follows = false 1081 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 1082 1083 return try buf.toOwnedSlice(allocator); 1084 } 1085 1086 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 1087 return buildKexInit(io, allocator, &(our_kex_algos ++ [_][]const u8{kex_strict_server}), &our_host_key_algos, &our_ciphers); 1088 } 1089 1090 // the name-lists borrow from the KEXINIT payload 1091 const ParsedKexInit = struct { 1092 kex_algos: []const u8, 1093 host_key_algos: []const u8, 1094 cs_cipher: []const u8, 1095 sc_cipher: []const u8, 1096 first_kex_packet_follows: bool, 1097 }; 1098 1099 fn parseClientKexInit(payload: []const u8) !ParsedKexInit { 1100 if (payload.len < 1 + 16) return error.KexInitTruncated; 1101 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 1102 1103 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 1104 1105 const kex_algos = try takeString(&reader, max_name_list_len); 1106 const host_key_algos = try takeString(&reader, max_name_list_len); 1107 const cs_cipher = try takeString(&reader, max_name_list_len); 1108 const sc_cipher = try takeString(&reader, max_name_list_len); 1109 1110 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 1111 for (0..6) |_| _ = try takeString(&reader, max_name_list_len); 1112 const first_kex_packet_follows = (try reader.takeByte()) != 0; 1113 _ = try reader.takeInt(u32, .big); // reserved 1114 1115 return .{ 1116 .kex_algos = kex_algos, 1117 .host_key_algos = host_key_algos, 1118 .cs_cipher = cs_cipher, 1119 .sc_cipher = sc_cipher, 1120 .first_kex_packet_follows = first_kex_packet_follows, 1121 }; 1122 } 1123 1124 // --------------------------------------------------------------------------- 1125 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 1126 // --------------------------------------------------------------------------- 1127 1128 fn runKex( 1129 io: std.Io, 1130 allocator: std.mem.Allocator, 1131 reader: *std.Io.Reader, 1132 writer: *std.Io.Writer, 1133 host_key: *const HostKey, 1134 client_version: []const u8, 1135 idle: *IdleState, 1136 ) !Conn { 1137 var seqs: PlainSeqs = .{}; 1138 const transport = KexTransport{ .plain = &seqs }; 1139 1140 // exchange KEXINITs 1141 const server_kex_init = try buildServerKexInit(io, allocator); 1142 defer allocator.free(server_kex_init); 1143 try transport.writePacket(io, writer, server_kex_init); 1144 1145 const client_kex_init = try transport.readPacket(allocator, reader, false); 1146 defer allocator.free(client_kex_init); 1147 1148 const parsed = try parseClientKexInit(client_kex_init); 1149 1150 // strict kex: when the client advertises it, its KEXINIT must be the 1151 // first packet, ignorable messages are banned until NEWKEYS, and both 1152 // seqnos reset to 0 after every NEWKEYS. 1153 const strict = firstCommonName(parsed.kex_algos, &.{kex_strict_client}) != null; 1154 if (strict and seqs.read != 1) return error.StrictKexViolation; 1155 const ext_info = firstCommonName(parsed.kex_algos, &.{ext_info_client}) != null; 1156 1157 var keys: SessionKeys = undefined; 1158 defer std.crypto.secureZero(u8, std.mem.asBytes(&keys)); 1159 const session_id = try exchangeKeys( 1160 io, 1161 allocator, 1162 reader, 1163 writer, 1164 transport, 1165 strict, 1166 host_key, 1167 client_version, 1168 client_kex_init, 1169 server_kex_init, 1170 &parsed, 1171 null, 1172 &keys, 1173 ); 1174 1175 // post-KEX everything is encrypted with chacha20-poly1305@openssh.com. 1176 // each cipher continues its own direction's count; the read side 1177 // includes any skipped IGNORE/DEBUG packets. 1178 var conn: Conn = .{ 1179 .io = io, 1180 .allocator = allocator, 1181 .reader = reader, 1182 .writer = writer, 1183 .cs_cipher = .init(&keys.cs_enc, if (strict) 0 else seqs.read), 1184 .sc_cipher = .init(&keys.sc_enc, if (strict) 0 else seqs.written), 1185 .rekey = .{ 1186 .host_key = host_key, 1187 .client_version = client_version, 1188 .session_id = session_id, 1189 .strict = strict, 1190 }, 1191 .idle = idle, 1192 }; 1193 if (ext_info) try sendExtInfo(&conn); 1194 return conn; 1195 } 1196 1197 // advertise server-sig-algs so clients will offer rsa-sha2 keys (RFC 8308 §3.1) 1198 fn sendExtInfo(conn: *Conn) !void { 1199 var buf: std.ArrayList(u8) = .empty; 1200 defer buf.deinit(conn.allocator); 1201 try buf.append(conn.allocator, SSH_MSG_EXT_INFO); 1202 try writeU32(&buf, conn.allocator, 1); // one extension 1203 try writeStringField(&buf, conn.allocator, "server-sig-algs"); 1204 try writeNameList(&buf, conn.allocator, &our_userauth_algos); 1205 try conn.writePacket(&.{buf.items}); 1206 } 1207 1208 /// everything needed to service a client-initiated rekey mid-session. 1209 const RekeyState = struct { 1210 host_key: *const HostKey, 1211 client_version: []const u8, 1212 session_id: [Sha256.digest_length]u8, 1213 strict: bool, 1214 }; 1215 1216 // service a rekey whose triggering KEXINIT payload has just been read: run 1217 // the whole exchange under the current keys, then swap the new keys into 1218 // both ciphers in place. 1219 fn runRekey(conn: *Conn, client_kex_init: []const u8) !void { 1220 const parsed = try parseClientKexInit(client_kex_init); 1221 1222 // the exchange reads and writes through the ciphers directly 1223 conn.idle.waiting.store(true, .release); 1224 defer conn.idle.waiting.store(false, .release); 1225 1226 const server_kex_init = try buildServerKexInit(conn.io, conn.allocator); 1227 defer conn.allocator.free(server_kex_init); 1228 try conn.sc_cipher.writePacket(conn.io, conn.writer, &.{server_kex_init}); 1229 1230 var keys: SessionKeys = undefined; 1231 defer std.crypto.secureZero(u8, std.mem.asBytes(&keys)); 1232 _ = try exchangeKeys( 1233 conn.io, 1234 conn.allocator, 1235 conn.reader, 1236 conn.writer, 1237 .{ .encrypted = .{ .cs = &conn.cs_cipher, .sc = &conn.sc_cipher } }, 1238 false, // strict kex message rules apply to the initial exchange only 1239 conn.rekey.host_key, 1240 conn.rekey.client_version, 1241 client_kex_init, 1242 server_kex_init, 1243 &parsed, 1244 &conn.rekey.session_id, 1245 &keys, 1246 ); 1247 1248 // seqnos continue across a rekey unless strict kex was negotiated, 1249 // which resets them after every NEWKEYS 1250 conn.cs_cipher = .init(&keys.cs_enc, if (conn.rekey.strict) 0 else conn.cs_cipher.seq); 1251 conn.sc_cipher = .init(&keys.sc_enc, if (conn.rekey.strict) 0 else conn.sc_cipher.seq); 1252 } 1253 1254 // the KEX core shared by the initial exchange and rekeys: pick algorithms, 1255 // run the (hybrid) ECDH round trip, exchange NEWKEYS, derive keys. both 1256 // KEXINIT payloads have already been exchanged by the caller, which also owns 1257 // `parsed`; the client's raw payload comes along too because the exchange hash 1258 // covers it verbatim. session_id is null on the initial exchange (where it 1259 // becomes the exchange hash) and the original session id on a rekey. fills 1260 // `keys` and returns the exchange hash. 1261 fn exchangeKeys( 1262 io: std.Io, 1263 allocator: std.mem.Allocator, 1264 reader: *std.Io.Reader, 1265 writer: *std.Io.Writer, 1266 transport: KexTransport, 1267 strict: bool, 1268 host_key: *const HostKey, 1269 client_version: []const u8, 1270 client_kex_init: []const u8, 1271 server_kex_init: []const u8, 1272 parsed: *const ParsedKexInit, 1273 session_id: ?*const [Sha256.digest_length]u8, 1274 keys: *SessionKeys, 1275 ) ![Sha256.digest_length]u8 { 1276 const kex_algo = firstCommonName(parsed.kex_algos, &our_kex_algos) orelse return error.NoCommonKexAlgorithm; 1277 if (firstCommonName(parsed.host_key_algos, &our_host_key_algos) == null) return error.NoCommonHostKeyAlgorithm; 1278 if (firstCommonName(parsed.cs_cipher, &our_ciphers) == null) return error.NoCommonCipher; 1279 if (firstCommonName(parsed.sc_cipher, &our_ciphers) == null) return error.NoCommonCipher; 1280 const hybrid = std.mem.eql(u8, kex_algo, "mlkem768x25519-sha256"); 1281 1282 // a client may follow its KEXINIT with a kex packet for its guess. the 1283 // guess is right only when both sides' first kex and host key algorithms 1284 // match (RFC 4253 §7.1) — not when the client's first choice merely 1285 // happens to be kex_algo, so this compares against our list. a client 1286 // whose guess was wrong re-sends an init for the negotiated method. 1287 if (parsed.first_kex_packet_follows) { 1288 var kex_iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 1289 var host_key_iter = std.mem.splitScalar(u8, parsed.host_key_algos, ','); 1290 const guessed_right = std.mem.eql(u8, kex_iter.first(), our_kex_algos[0]) and 1291 std.mem.eql(u8, host_key_iter.first(), our_host_key_algos[0]); 1292 if (!guessed_right) { 1293 const wrong_guess = try transport.readPacket(allocator, reader, strict); 1294 allocator.free(wrong_guess); 1295 } 1296 } 1297 1298 // receive KEX_ECDH_INIT (mlkem768x25519 reuses message code 30 — same 1299 // wire shape, only the string size differs). 1300 const ecdh_init = try transport.readPacket(allocator, reader, strict); 1301 defer allocator.free(ecdh_init); 1302 if (ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 1303 1304 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 1305 const expected_client_len: u32 = if (hybrid) hybrid_client_blob_len else X25519.public_length; 1306 const client_blob = try takeString(&ecdh_init_reader, expected_client_len); 1307 if (client_blob.len != expected_client_len) return error.InvalidEphemeralKey; 1308 1309 // derive server reply blob (S_REPLY) + shared secret K. 1310 // ECDH: server_blob = X25519 server pub (32B); K = X25519(s, c_pub). 1311 // hybrid: server_blob = MLKEM ciphertext (1088B) || X25519 server pub (32B); 1312 // K = SHA-256(K_MLKEM || K_X25519). 1313 var server_blob_buf: [hybrid_server_blob_len]u8 = undefined; 1314 var k: [Sha256.digest_length]u8 = undefined; 1315 defer std.crypto.secureZero(u8, &k); 1316 const server_blob: []const u8 = blk: { 1317 const x25519_offset: usize = if (hybrid) MLKem768.PublicKey.encoded_length else 0; 1318 var x25519_client_pub: [X25519.public_length]u8 = undefined; 1319 @memcpy(&x25519_client_pub, client_blob[x25519_offset..]); 1320 var server_kp = X25519.KeyPair.generate(io); 1321 defer std.crypto.secureZero(u8, &server_kp.secret_key); 1322 var x25519_shared = try X25519.scalarmult(server_kp.secret_key, x25519_client_pub); 1323 defer std.crypto.secureZero(u8, &x25519_shared); 1324 1325 if (!hybrid) { 1326 server_blob_buf[0..X25519.public_length].* = server_kp.public_key; 1327 k = x25519_shared; 1328 break :blk server_blob_buf[0..X25519.public_length]; 1329 } 1330 1331 var pq_pub_bytes: [MLKem768.PublicKey.encoded_length]u8 = undefined; 1332 @memcpy(&pq_pub_bytes, client_blob[0..MLKem768.PublicKey.encoded_length]); 1333 const pq_pub = try MLKem768.PublicKey.fromBytes(&pq_pub_bytes); 1334 var encap = pq_pub.encaps(io); 1335 defer std.crypto.secureZero(u8, &encap.shared_secret); 1336 1337 server_blob_buf[0..MLKem768.ciphertext_length].* = encap.ciphertext; 1338 server_blob_buf[MLKem768.ciphertext_length..].* = server_kp.public_key; 1339 1340 var h = Sha256.init(.{}); 1341 defer std.crypto.secureZero(u8, std.mem.asBytes(&h)); 1342 h.update(&encap.shared_secret); 1343 h.update(&x25519_shared); 1344 h.final(&k); 1345 break :blk &server_blob_buf; 1346 }; 1347 1348 // build host key blob (K_S) 1349 var host_key_blob: std.ArrayList(u8) = .empty; 1350 defer host_key_blob.deinit(allocator); 1351 try host_key.appendPublicBlob(&host_key_blob, allocator); 1352 1353 // build exchange hash input and compute H 1354 const exchange_hash = try computeExchangeHash( 1355 allocator, 1356 client_version, 1357 server_version, 1358 client_kex_init, 1359 server_kex_init, 1360 host_key_blob.items, 1361 client_blob, 1362 server_blob, 1363 &k, 1364 hybrid, 1365 ); 1366 1367 // sign H with the host key, format as ssh signature blob 1368 var signature_blob: std.ArrayList(u8) = .empty; 1369 defer signature_blob.deinit(allocator); 1370 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 1371 1372 // build & send KEX_ECDH_REPLY (msg code 31 reused as KEX_HYBRID_REPLY) 1373 var reply: std.ArrayList(u8) = .empty; 1374 defer reply.deinit(allocator); 1375 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 1376 try writeStringField(&reply, allocator, host_key_blob.items); 1377 try writeStringField(&reply, allocator, server_blob); 1378 try writeStringField(&reply, allocator, signature_blob.items); 1379 try transport.writePacket(io, writer, reply.items); 1380 1381 // NEWKEYS — both sides switch to the new keys after this is sent and 1382 // the peer's NEWKEYS is received. 1383 try transport.writePacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 1384 1385 const peer_newkeys = try transport.readPacket(allocator, reader, strict); 1386 defer allocator.free(peer_newkeys); 1387 if (peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 1388 1389 // derive session keys per RFC 4253 §7.2. only the encrypt keys are 1390 // needed for chacha20-poly1305 (no separate MAC/IV). 1391 try deriveSessionKeys(allocator, &k, &exchange_hash, if (session_id) |sid| sid else &exchange_hash, keys, hybrid); 1392 return exchange_hash; 1393 } 1394 1395 // --------------------------------------------------------------------------- 1396 // exchange hash (RFC 4253 §8, RFC 5656 §4) 1397 // --------------------------------------------------------------------------- 1398 1399 pub fn computeExchangeHash( 1400 allocator: std.mem.Allocator, 1401 client_version: []const u8, 1402 server_version_str: []const u8, 1403 client_kex_init: []const u8, 1404 server_kex_init: []const u8, 1405 host_key_blob: []const u8, 1406 client_ephemeral: []const u8, 1407 server_ephemeral: []const u8, 1408 shared_secret: []const u8, 1409 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 1410 /// as a plain SSH string (length-prefixed bytes). 1411 k_is_string: bool, 1412 ) ![Sha256.digest_length]u8 { 1413 var buf: std.ArrayList(u8) = .empty; 1414 defer buf.deinit(allocator); 1415 defer std.crypto.secureZero(u8, buf.items); 1416 // reserved up front so a reallocation can't leave K behind 1417 try buf.ensureTotalCapacityPrecise(allocator, 8 * 4 + 1 + client_version.len + server_version_str.len + 1418 client_kex_init.len + server_kex_init.len + host_key_blob.len + client_ephemeral.len + 1419 server_ephemeral.len + shared_secret.len); 1420 1421 try writeStringField(&buf, allocator, client_version); 1422 try writeStringField(&buf, allocator, server_version_str); 1423 try writeStringField(&buf, allocator, client_kex_init); 1424 try writeStringField(&buf, allocator, server_kex_init); 1425 try writeStringField(&buf, allocator, host_key_blob); 1426 try writeStringField(&buf, allocator, client_ephemeral); 1427 try writeStringField(&buf, allocator, server_ephemeral); 1428 if (k_is_string) { 1429 try writeStringField(&buf, allocator, shared_secret); 1430 } else { 1431 try writeMpint(&buf, allocator, shared_secret); 1432 } 1433 1434 var hasher = Sha256.init(.{}); 1435 defer std.crypto.secureZero(u8, std.mem.asBytes(&hasher)); 1436 hasher.update(buf.items); 1437 return hasher.finalResult(); 1438 } 1439 1440 // --------------------------------------------------------------------------- 1441 // key derivation (RFC 4253 §7.2) 1442 // --------------------------------------------------------------------------- 1443 1444 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1445 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1446 // blocks chained per RFC 4253. 1447 pub const SessionKeys = struct { 1448 cs_enc: [64]u8, 1449 sc_enc: [64]u8, 1450 }; 1451 1452 pub fn deriveSessionKeys( 1453 allocator: std.mem.Allocator, 1454 shared_secret: []const u8, 1455 exchange_hash: []const u8, 1456 session_id: []const u8, 1457 out: *SessionKeys, 1458 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1459 k_is_string: bool, 1460 ) !void { 1461 // pre-build the K || H prefix once; reused for every derivation 1462 var prefix: std.ArrayList(u8) = .empty; 1463 defer prefix.deinit(allocator); 1464 defer std.crypto.secureZero(u8, prefix.items); 1465 // reserved up front so a reallocation can't leave K behind 1466 try prefix.ensureTotalCapacityPrecise(allocator, 4 + 1 + shared_secret.len + exchange_hash.len); 1467 if (k_is_string) { 1468 try writeStringField(&prefix, allocator, shared_secret); 1469 } else { 1470 try writeMpint(&prefix, allocator, shared_secret); 1471 } 1472 try prefix.appendSlice(allocator, exchange_hash); 1473 1474 deriveKey(prefix.items, 'C', session_id, &out.cs_enc); 1475 deriveKey(prefix.items, 'D', session_id, &out.sc_enc); 1476 } 1477 1478 fn deriveKey( 1479 prefix: []const u8, // K || H, already encoded 1480 letter: u8, 1481 session_id: []const u8, 1482 out: *[2 * Sha256.digest_length]u8, 1483 ) void { 1484 // a finished context still holds its digest and last input block 1485 // K_1 = HASH(K || H || letter || session_id) 1486 var first = Sha256.init(.{}); 1487 defer std.crypto.secureZero(u8, std.mem.asBytes(&first)); 1488 first.update(prefix); 1489 first.update(&.{letter}); 1490 first.update(session_id); 1491 first.final(out[0..Sha256.digest_length]); 1492 1493 // K_2 = HASH(K || H || K_1) 1494 var second = Sha256.init(.{}); 1495 defer std.crypto.secureZero(u8, std.mem.asBytes(&second)); 1496 second.update(prefix); 1497 second.update(out[0..Sha256.digest_length]); 1498 second.final(out[Sha256.digest_length..]); 1499 } 1500 1501 // --------------------------------------------------------------------------- 1502 // chacha20-poly1305@openssh.com packet codec 1503 // --------------------------------------------------------------------------- 1504 // 1505 // per openssh's PROTOCOL.chacha20poly1305: 1506 // K_2 = first 32 bytes of key material — encrypts the packet body 1507 // K_1 = next 32 bytes — encrypts the 4-byte length field 1508 // nonce = 64-bit big-endian sequence number 1509 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1510 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1511 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1512 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1513 // 1514 // padding is computed on the body alone (padding_length byte + payload + 1515 // padding) — the 4-byte length field is excluded from alignment. body must 1516 // be a multiple of 8 bytes; minimum padding 4 bytes. 1517 1518 pub const Cipher = struct { 1519 main_key: [32]u8, // K_2 1520 header_key: [32]u8, // K_1 1521 // wider than the 32-bit wire seqno, so a peer that never rekeys fails the 1522 // mac at 2^32 packets instead of wrapping into nonce reuse 1523 seq: u64, 1524 1525 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1526 return .{ 1527 .main_key = key_material[0..32].*, 1528 .header_key = key_material[32..64].*, 1529 .seq = initial_seq, 1530 }; 1531 } 1532 1533 fn makeNonce(seq: u64) [8]u8 { 1534 var nonce: [8]u8 = undefined; 1535 std.mem.writeInt(u64, &nonce, seq, .big); 1536 return nonce; 1537 } 1538 1539 fn bodyLength(self: *const Cipher, enc_length: *const [4]u8) !u32 { 1540 var plain: [4]u8 = undefined; 1541 ChaCha20.xor(&plain, enc_length, 0, self.header_key, makeNonce(self.seq)); 1542 const len = std.mem.readInt(u32, &plain, .big); 1543 if (len < 8 or len > max_packet_len or len % 8 != 0) return error.InvalidPacketLength; 1544 return len; 1545 } 1546 1547 fn peekPacket(self: *const Cipher, reader: *std.Io.Reader) !void { 1548 const len = 4 + (try self.bodyLength(try reader.peekArray(4))) + Poly1305.mac_length; 1549 if (len > reader.buffer.len) return error.ReadBufferTooSmall; 1550 _ = try reader.peek(len); 1551 } 1552 1553 fn hasBufferedPacket(self: *const Cipher, reader: *std.Io.Reader) !bool { 1554 const bytes = reader.buffered(); 1555 if (bytes.len < 4) return false; 1556 return bytes.len >= 4 + (try self.bodyLength(bytes[0..4])) + Poly1305.mac_length; 1557 } 1558 1559 /// the payload is the concatenation of `parts` 1560 pub fn writePacket( 1561 self: *Cipher, 1562 io: std.Io, 1563 writer: *std.Io.Writer, 1564 parts: []const []const u8, 1565 ) !void { 1566 var payload_len: usize = 0; 1567 for (parts) |part| payload_len += part.len; 1568 1569 const block: usize = 8; 1570 const initial_pad = block - ((1 + payload_len) % block); 1571 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1572 const body_len = 1 + payload_len + padding_len; 1573 if (body_len > max_packet_len) return error.PacketTooLarge; 1574 1575 const nonce = makeNonce(self.seq); 1576 1577 // encrypted length || body || mac, contiguous so the packet goes out 1578 // in one write. stack-allocated to avoid a heap alloc on every packet. 1579 var packet_buf: [packet_buffer_size]u8 = undefined; 1580 const packet = packet_buf[0 .. 4 + body_len + Poly1305.mac_length]; 1581 const enc_length = packet[0..4]; 1582 const body = packet[4..][0..body_len]; 1583 1584 // plaintext body = padding_length || payload || random padding 1585 body[0] = padding_len; 1586 var end: usize = 1; 1587 for (parts) |part| { 1588 @memcpy(body[end..][0..part.len], part); 1589 end += part.len; 1590 } 1591 io.random(body[end..]); 1592 1593 // encrypt body in place with counter=1 1594 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1595 1596 // encrypt length field with header key, counter=0 1597 std.mem.writeInt(u32, enc_length, @intCast(body_len), .big); 1598 ChaCha20.xor(enc_length, enc_length, 0, self.header_key, nonce); 1599 1600 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1601 var poly_key: [Poly1305.key_length]u8 = undefined; 1602 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1603 1604 // mac over encrypted_length || encrypted_body 1605 var poly = Poly1305.init(&poly_key); 1606 poly.update(packet[0 .. 4 + body_len]); 1607 poly.final(packet[4 + body_len ..][0..Poly1305.mac_length]); 1608 1609 try writer.writeAll(packet); 1610 try writer.flush(); 1611 1612 self.seq += 1; 1613 } 1614 1615 pub fn readPacket( 1616 self: *Cipher, 1617 allocator: std.mem.Allocator, 1618 reader: *std.Io.Reader, 1619 ) ![]u8 { 1620 const nonce = makeNonce(self.seq); 1621 1622 var enc_length: [4]u8 = undefined; 1623 try reader.readSliceAll(&enc_length); 1624 1625 const body_len = try self.bodyLength(&enc_length); 1626 1627 // the body allocation becomes the returned payload, so a packet only 1628 // ever costs one allocation 1629 const body = try allocator.alloc(u8, body_len); 1630 errdefer allocator.free(body); 1631 try reader.readSliceAll(body); 1632 1633 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1634 try reader.readSliceAll(&tag_recv); 1635 1636 var poly_key: [Poly1305.key_length]u8 = undefined; 1637 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1638 1639 var poly = Poly1305.init(&poly_key); 1640 poly.update(&enc_length); 1641 poly.update(body); 1642 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1643 poly.final(&tag_computed); 1644 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1645 return error.MacVerificationFailed; 1646 } 1647 1648 // decrypt the body in place 1649 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1650 1651 const padding_len = body[0]; 1652 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1653 const payload_len = body_len - 1 - @as(u32, padding_len); 1654 // a payload starts with its message type 1655 if (payload_len == 0) return error.EmptyPacket; 1656 1657 // shift the payload over the padding_length byte, then release the 1658 // trailing padding (caller owns the result) 1659 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1660 const payload = try allocator.realloc(body, payload_len); 1661 1662 self.seq += 1; 1663 return payload; 1664 } 1665 }; 1666 1667 // --------------------------------------------------------------------------- 1668 // post-KEX: service request + user authentication (RFC 4252) 1669 // --------------------------------------------------------------------------- 1670 1671 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1672 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1673 /// `Offering public key: … SHA256:…`. 1674 pub const fingerprint_len = 50; 1675 1676 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1677 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1678 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1679 var digest: [Sha256.digest_length]u8 = undefined; 1680 Sha256.hash(pubkey_blob, &digest, .{}); 1681 1682 var out: [fingerprint_len]u8 = undefined; 1683 @memcpy(out[0..7], "SHA256:"); 1684 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1685 std.debug.assert(encoded.len == fingerprint_len - 7); 1686 return out; 1687 } 1688 1689 /// the pubkey a client authenticated with 1690 const ClientKey = struct { 1691 fingerprint: [fingerprint_len]u8, 1692 /// owned by the connection's allocator 1693 blob: []const u8, 1694 }; 1695 1696 fn runAuth(conn: *Conn) !ClientKey { 1697 const allocator = conn.allocator; 1698 1699 // step 1: service request for ssh-userauth → service accept 1700 { 1701 const req = try readSessionPacket(conn); 1702 defer allocator.free(req); 1703 if (req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1704 1705 var req_reader = std.Io.Reader.fixed(req[1..]); 1706 const service = try takeString(&req_reader, 64); 1707 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1708 1709 var accept: std.ArrayList(u8) = .empty; 1710 defer accept.deinit(allocator); 1711 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1712 try writeStringField(&accept, allocator, "ssh-userauth"); 1713 try conn.writePacket(&.{accept.items}); 1714 } 1715 1716 // step 2: USERAUTH loop until SUCCESS. accept any supported key whose 1717 // signature verifies against the offered pubkey. 1718 var auth_attempts: u32 = 0; 1719 while (true) { 1720 const req = try readSessionPacket(conn); 1721 defer allocator.free(req); 1722 if (req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1723 1724 // every request counts, probes included, so a client can't loop here 1725 // forever 1726 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1727 auth_attempts += 1; 1728 1729 var req_reader = std.Io.Reader.fixed(req[1..]); 1730 const user_name = try takeString(&req_reader, 256); 1731 const service_name = try takeString(&req_reader, 64); 1732 const method = try takeString(&req_reader, 64); 1733 1734 // RFC 4252 §5: the server must verify the requested service 1735 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1736 try sendUserauthFailure(conn); 1737 continue; 1738 } 1739 1740 if (!std.mem.eql(u8, method, "publickey")) { 1741 try sendUserauthFailure(conn); 1742 continue; 1743 } 1744 1745 const has_signature = (try req_reader.takeByte()) != 0; 1746 const algo = try takeString(&req_reader, 64); 1747 const pubkey_blob = try takeString(&req_reader, 4096); 1748 1749 if (firstCommonName(algo, &our_userauth_algos) == null) { 1750 try sendUserauthFailure(conn); 1751 continue; 1752 } 1753 1754 if (!has_signature) { 1755 // probe — tell the client this key is acceptable so it'll send 1756 // the signed version next. 1757 var pk_ok: std.ArrayList(u8) = .empty; 1758 defer pk_ok.deinit(allocator); 1759 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1760 try writeStringField(&pk_ok, allocator, algo); 1761 try writeStringField(&pk_ok, allocator, pubkey_blob); 1762 try conn.writePacket(&.{pk_ok.items}); 1763 continue; 1764 } 1765 1766 // has signature — verify it 1767 const signature_blob = try takeString(&req_reader, 1024); 1768 1769 const ok = verifyUserauthSignature( 1770 allocator, 1771 &conn.rekey.session_id, 1772 user_name, 1773 service_name, 1774 algo, 1775 pubkey_blob, 1776 signature_blob, 1777 ) catch |err| switch (err) { 1778 error.OutOfMemory => return err, 1779 // a malformed key or signature blob 1780 else => false, 1781 }; 1782 1783 if (!ok) { 1784 try sendUserauthFailure(conn); 1785 continue; 1786 } 1787 1788 try conn.writePacket(&.{&[_]u8{SSH_MSG_USERAUTH_SUCCESS}}); 1789 return .{ .fingerprint = formatFingerprint(pubkey_blob), .blob = try allocator.dupe(u8, pubkey_blob) }; 1790 } 1791 } 1792 1793 fn sendUserauthFailure(conn: *Conn) !void { 1794 var buf: std.ArrayList(u8) = .empty; 1795 defer buf.deinit(conn.allocator); 1796 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1797 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1798 try buf.append(conn.allocator, 0); // partial_success = false 1799 try conn.writePacket(&.{buf.items}); 1800 } 1801 1802 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1803 /// used by the server to recompute the signed input for verification 1804 pub fn appendPublickeySignedData( 1805 buf: *std.ArrayList(u8), 1806 allocator: std.mem.Allocator, 1807 session_id: []const u8, 1808 user_name: []const u8, 1809 service_name: []const u8, 1810 algo: []const u8, 1811 pubkey_blob: []const u8, 1812 ) !void { 1813 try writeStringField(buf, allocator, session_id); 1814 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1815 try writeStringField(buf, allocator, user_name); 1816 try writeStringField(buf, allocator, service_name); 1817 try writeStringField(buf, allocator, "publickey"); 1818 try buf.append(allocator, 1); 1819 try writeStringField(buf, allocator, algo); 1820 try writeStringField(buf, allocator, pubkey_blob); 1821 } 1822 1823 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1824 // verify the supplied signature against them. 1825 fn verifyUserauthSignature( 1826 allocator: std.mem.Allocator, 1827 session_id: *const [Sha256.digest_length]u8, 1828 user_name: []const u8, 1829 service_name: []const u8, 1830 algo: []const u8, 1831 pubkey_blob: []const u8, 1832 signature_blob: []const u8, 1833 ) !bool { 1834 var signed: std.ArrayList(u8) = .empty; 1835 defer signed.deinit(allocator); 1836 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1837 1838 if (std.mem.eql(u8, algo, "ssh-ed25519")) return verifyEd25519(pubkey_blob, signature_blob, signed.items); 1839 if (std.mem.eql(u8, algo, "rsa-sha2-512")) return verifyRsa(Sha512, algo, pubkey_blob, signature_blob, signed.items); 1840 if (std.mem.eql(u8, algo, "rsa-sha2-256")) return verifyRsa(Sha256, algo, pubkey_blob, signature_blob, signed.items); 1841 return false; 1842 } 1843 1844 fn verifyEd25519(pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1845 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1846 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1847 const pk_algo = try takeString(&pubkey_reader, 64); 1848 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1849 const raw_pubkey = try takeString(&pubkey_reader, 64); 1850 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1851 // the fingerprint hashes the whole blob, so it must hold nothing else 1852 if (pubkey_reader.bufferedLen() != 0) return false; 1853 1854 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1855 var sig_reader = std.Io.Reader.fixed(signature_blob); 1856 const sig_algo = try takeString(&sig_reader, 64); 1857 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1858 const raw_sig = try takeString(&sig_reader, Ed25519.Signature.encoded_length); 1859 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1860 1861 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1862 @memcpy(&pubkey_bytes, raw_pubkey); 1863 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1864 @memcpy(&sig_bytes, raw_sig); 1865 1866 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1867 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1868 sig.verify(signed, pk) catch return false; 1869 return true; 1870 } 1871 1872 fn verifyRsa(comptime Hash: type, algo: []const u8, pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1873 // parse pubkey_blob: string "ssh-rsa" || mpint e || mpint n 1874 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1875 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), "ssh-rsa")) return false; 1876 // the fingerprint hashes the whole blob, so one key must have one encoding 1877 const e = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1878 const n = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1879 if (pubkey_reader.bufferedLen() != 0) return false; 1880 1881 // parse signature_blob: string algo || string sig 1882 var sig_reader = std.Io.Reader.fixed(signature_blob); 1883 if (!std.mem.eql(u8, try takeString(&sig_reader, 64), algo)) return false; 1884 const sig = try takeString(&sig_reader, 1024); 1885 if (sig.len != n.len) return false; 1886 1887 const pk = rsa.PublicKey.fromBytes(e, n) catch return false; 1888 switch (n.len) { 1889 inline 256, 384, 512 => |len| { 1890 rsa.PKCS1v1_5Signature.verify(len, sig[0..len], signed, pk, Hash) catch return false; 1891 return true; 1892 }, 1893 else => return false, 1894 } 1895 } 1896 1897 // the unsigned bytes of a positive mpint in its shortest encoding (RFC 4251 1898 // §5), or null for zero, negative, or padded encodings 1899 fn canonicalMpintMagnitude(bytes: []const u8) ?[]const u8 { 1900 if (bytes.len == 0 or bytes[0] & 0x80 != 0) return null; 1901 if (bytes[0] != 0) return bytes; 1902 if (bytes.len < 2 or bytes[1] & 0x80 == 0) return null; 1903 return bytes[1..]; 1904 } 1905 1906 // --------------------------------------------------------------------------- 1907 // connection layer (RFC 4254): channels, requests, data, flow control 1908 // --------------------------------------------------------------------------- 1909 1910 const Channel = struct { 1911 local_id: u32, 1912 remote_id: u32, 1913 local_window: u32, // bytes peer may still send us before we adjust 1914 remote_window: u32, // bytes we may still send to peer before they adjust 1915 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1916 pty: ?PtySize = null, 1917 // value of GIT_PROTOCOL, one of the two env variables we keep 1918 git_protocol_buf: [64]u8 = undefined, 1919 git_protocol_len: ?usize = null, 1920 // false when NO_COLOR is set, the other env variable we keep 1921 color: bool = true, 1922 }; 1923 1924 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1925 1926 // take the uint32 width/height cell counts of a pty-req or window-change, 1927 // bounded before either initial rendering or a resize can allocate grids. 1928 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1929 fn takePtySize(r: *std.Io.Reader) !PtySize { 1930 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1931 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1932 return .{ 1933 .width_cells = @intCast(width), 1934 .height_cells = @intCast(height), 1935 }; 1936 } 1937 1938 fn runChannelLayer( 1939 conn: *Conn, 1940 client_key: *const ClientKey, 1941 handler: anytype, 1942 ) !void { 1943 const allocator = conn.allocator; 1944 var channel: ?Channel = null; 1945 1946 while (true) { 1947 const packet = try readSessionPacket(conn); 1948 defer allocator.free(packet); 1949 const msg_type = packet[0]; 1950 1951 switch (msg_type) { 1952 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1953 1954 SSH_MSG_CHANNEL_OPEN => { 1955 channel = try handleChannelOpen(conn, packet, channel != null) orelse continue; 1956 }, 1957 1958 SSH_MSG_CHANNEL_REQUEST => { 1959 const ch = if (channel) |*c| c else return error.UnknownChannel; 1960 const start_request = try handleChannelRequest(conn, ch, packet); 1961 // the request borrows from the packet, which outlives the session 1962 if (start_request) |request| { 1963 // any key authenticates, so the deadline holds until here 1964 conn.idle.session_started.store(true, .release); 1965 var sess = SessionCtx{ 1966 .conn = conn, 1967 .channel = ch, 1968 .fingerprint = client_key.fingerprint, 1969 .public_key = client_key.blob, 1970 }; 1971 defer sess.deinit(); 1972 handler.handleSession(&sess, request) catch |session_err| { 1973 // a failed read leaves the protocol unusable, so the 1974 // disconnect names it instead of a clean close 1975 if (sess.read_err) |read_err| return read_err; 1976 // try to send a non-zero exit status before closing 1977 sess.exit(1) catch {}; 1978 return sess.underlyingError(session_err); 1979 }; 1980 if (!sess.closed) try sess.exit(0); 1981 return; 1982 } 1983 }, 1984 1985 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1986 const ch = if (channel) |*c| c else return error.UnknownChannel; 1987 try handleWindowAdjust(ch, packet); 1988 }, 1989 1990 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1991 const ch = if (channel) |*c| c else return error.UnknownChannel; 1992 // before shell/exec the client shouldn't be sending data, but 1993 // some clients are chatty; discard and refill window. nothing 1994 // is buffered yet, so the whole window is available to credit. 1995 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1996 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1997 }, 1998 1999 SSH_MSG_CHANNEL_EOF => { 2000 const ch = if (channel) |*c| c else return error.UnknownChannel; 2001 try parseChannelId(packet, ch.local_id); 2002 }, 2003 2004 SSH_MSG_CHANNEL_CLOSE => { 2005 const ch = if (channel) |*c| c else return error.UnknownChannel; 2006 try parseChannelId(packet, ch.local_id); 2007 try sendChannelMessage(conn, ch, SSH_MSG_CHANNEL_CLOSE); 2008 drainConnection(conn); 2009 return; 2010 }, 2011 2012 // RFC 4252 §5.1: silently ignored once authenticated 2013 SSH_MSG_USERAUTH_REQUEST => {}, 2014 else => try sendUnimplemented(conn), 2015 } 2016 } 2017 } 2018 2019 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 2020 // byte SSH_MSG_GLOBAL_REQUEST 2021 // string request_name 2022 // boolean want_reply 2023 // …request-specific data we ignore 2024 var r = std.Io.Reader.fixed(packet[1..]); 2025 _ = try takeString(&r, 256); 2026 const want_reply = (try r.takeByte()) != 0; 2027 if (want_reply) { 2028 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 2029 } 2030 } 2031 2032 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 2033 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 2034 /// return null. 2035 fn handleChannelOpen(conn: *Conn, packet: []const u8, has_channel: bool) !?Channel { 2036 // byte SSH_MSG_CHANNEL_OPEN 2037 // string channel_type 2038 // uint32 sender_channel (peer's id) 2039 // uint32 initial_window 2040 // uint32 max_packet 2041 var r = std.Io.Reader.fixed(packet[1..]); 2042 const ch_type = try takeString(&r, 64); 2043 const remote_id = try r.takeInt(u32, .big); 2044 const initial_window = try r.takeInt(u32, .big); 2045 const max_packet = try r.takeInt(u32, .big); 2046 2047 if (has_channel) { 2048 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 2049 return null; 2050 } 2051 2052 if (!std.mem.eql(u8, ch_type, "session")) { 2053 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2054 return null; 2055 } 2056 2057 // a zero max_packet would leave writeBytes looping without progress 2058 if (max_packet == 0) { 2059 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2060 return null; 2061 } 2062 2063 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2064 var reply: [17]u8 = undefined; 2065 reply[0] = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; 2066 std.mem.writeInt(u32, reply[1..5], remote_id, .big); 2067 std.mem.writeInt(u32, reply[5..9], local_id, .big); 2068 std.mem.writeInt(u32, reply[9..13], initial_recv_window, .big); 2069 std.mem.writeInt(u32, reply[13..17], max_packet_size, .big); 2070 try conn.writePacket(&.{&reply}); 2071 2072 return .{ 2073 .local_id = local_id, 2074 .remote_id = remote_id, 2075 .local_window = initial_recv_window, 2076 .remote_window = initial_window, 2077 .max_packet = max_packet, 2078 }; 2079 } 2080 2081 fn sendChannelOpenFailure(conn: *Conn, remote_id: u32, reason: u32, description: []const u8) !void { 2082 const allocator = conn.allocator; 2083 2084 var reply: std.ArrayList(u8) = .empty; 2085 defer reply.deinit(allocator); 2086 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2087 try writeU32(&reply, allocator, remote_id); 2088 try writeU32(&reply, allocator, reason); 2089 try writeStringField(&reply, allocator, description); 2090 try writeStringField(&reply, allocator, ""); // language tag 2091 try conn.writePacket(&.{reply.items}); 2092 } 2093 2094 /// returns the session request if this one triggered it, else null. an exec 2095 /// command borrows from `packet`. 2096 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2097 // byte SSH_MSG_CHANNEL_REQUEST 2098 // uint32 recipient_channel (== our local_id) 2099 // string request_type 2100 // boolean want_reply 2101 // …request-specific data 2102 var r = std.Io.Reader.fixed(packet[1..]); 2103 const recipient_channel = try r.takeInt(u32, .big); 2104 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2105 const req_type = try takeString(&r, 64); 2106 const want_reply = (try r.takeByte()) != 0; 2107 2108 if (std.mem.eql(u8, req_type, "pty-req")) { 2109 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2110 // uint32 height px, string modes 2111 _ = try takeString(&r, 64); 2112 ch.pty = try takePtySize(&r); 2113 try replyChannelRequest(conn, ch, want_reply, true); 2114 return null; 2115 } 2116 2117 if (std.mem.eql(u8, req_type, "env")) { 2118 // string name, string value. the rest are ignored silently. 2119 const name = try takeString(&r, max_packet_len); 2120 const value = try takeString(&r, max_packet_len); 2121 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2122 @memcpy(ch.git_protocol_buf[0..value.len], value); 2123 ch.git_protocol_len = value.len; 2124 } else if (std.mem.eql(u8, name, "NO_COLOR")) { 2125 ch.color = value.len == 0; 2126 } 2127 try replyChannelRequest(conn, ch, want_reply, true); 2128 return null; 2129 } 2130 2131 if (std.mem.eql(u8, req_type, "window-change")) { 2132 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2133 const sz = try takePtySize(&r); 2134 if (ch.pty != null) ch.pty = sz; 2135 // spec: window-change MUST NOT request a reply, but accept either 2136 try replyChannelRequest(conn, ch, want_reply, true); 2137 return null; 2138 } 2139 2140 if (std.mem.eql(u8, req_type, "shell")) { 2141 try replyChannelRequest(conn, ch, want_reply, true); 2142 return .{ .shell = .{ .pty = ch.pty, .color = ch.color } }; 2143 } 2144 2145 if (std.mem.eql(u8, req_type, "exec")) { 2146 // capture the command string for the handler to inspect 2147 const cmd = try takeString(&r, 4096); 2148 try replyChannelRequest(conn, ch, want_reply, true); 2149 return .{ .exec = .{ 2150 .command = cmd, 2151 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2152 } }; 2153 } 2154 2155 // unknown request kind — fail it 2156 try replyChannelRequest(conn, ch, want_reply, false); 2157 return null; 2158 } 2159 2160 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2161 if (!want_reply) return; 2162 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2163 } 2164 2165 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2166 var packet: [5]u8 = undefined; 2167 packet[0] = msg_type; 2168 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2169 try conn.writePacket(&.{&packet}); 2170 } 2171 2172 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2173 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2174 // uint32 recipient_channel 2175 // uint32 bytes_to_add 2176 var r = std.Io.Reader.fixed(packet[1..]); 2177 const recipient_channel = try r.takeInt(u32, .big); 2178 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2179 const add = try r.takeInt(u32, .big); 2180 ch.remote_window +|= add; 2181 } 2182 2183 // charge a payload's bytes against the receive window without keeping them. 2184 // the caller credits the window back, choosing the budget that suits it. 2185 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2186 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2187 // uint32 recipient_channel 2188 // [if extended: uint32 type_code] 2189 // string data 2190 const payload = try parseChannelData(packet, extended, ch.local_id); 2191 const data_len: u32 = @intCast(payload.len); 2192 2193 if (data_len > ch.local_window) return error.WindowExceeded; 2194 ch.local_window -= data_len; 2195 } 2196 2197 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2198 if (packet.len < 1) return error.EmptyPacket; 2199 var r = std.Io.Reader.fixed(packet[1..]); 2200 const recipient_channel = try r.takeInt(u32, .big); 2201 if (recipient_channel != expected_channel) return error.UnknownChannel; 2202 if (extended) { 2203 const data_type = try r.takeInt(u32, .big); 2204 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2205 } 2206 const data_len = try r.takeInt(u32, .big); 2207 // catches both data_len > remaining (would otherwise be a bounds-check 2208 // panic on the slice) and trailing junk after the declared payload. 2209 if (data_len != r.buffered().len) return error.InvalidChannelData; 2210 return r.buffered(); 2211 } 2212 2213 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2214 var r = std.Io.Reader.fixed(packet[1..]); 2215 const recipient_channel = try r.takeInt(u32, .big); 2216 if (recipient_channel != expected_channel) return error.UnknownChannel; 2217 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2218 } 2219 2220 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2221 /// of `budget`, the credit we're willing to have outstanding. used both for 2222 /// the pre-session discard path and by SessionCtx after it consumes a 2223 /// CHANNEL_DATA payload. 2224 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2225 if (ch.local_window >= budget / 2) return; 2226 const add = budget - ch.local_window; 2227 ch.local_window += add; 2228 var packet: [9]u8 = undefined; 2229 packet[0] = SSH_MSG_CHANNEL_WINDOW_ADJUST; 2230 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2231 std.mem.writeInt(u32, packet[5..9], add, .big); 2232 try conn.writePacket(&.{&packet}); 2233 } 2234 2235 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2236 var bytes: [4]u8 = undefined; 2237 std.mem.writeInt(u32, &bytes, value, .big); 2238 try buf.appendSlice(allocator, &bytes); 2239 } 2240 2241 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2242 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2243 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2244 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2245 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2246 }) |case| { 2247 var bytes: [8]u8 = undefined; 2248 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2249 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2250 var reader = std.Io.Reader.fixed(&bytes); 2251 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2252 } 2253 } 2254 2255 test "channel close before shell or exec is acknowledged" { 2256 const io = std.testing.io; 2257 const allocator = std.testing.allocator; 2258 const key: [64]u8 = @splat(0x5a); 2259 var encoded: [256]u8 = undefined; 2260 var encoded_writer = std.Io.Writer.fixed(&encoded); 2261 var sender = Cipher.init(&key, 0); 2262 var open: std.ArrayList(u8) = .empty; 2263 defer open.deinit(allocator); 2264 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2265 try writeStringField(&open, allocator, "session"); 2266 try writeU32(&open, allocator, 7); 2267 try writeU32(&open, allocator, 32768); 2268 try writeU32(&open, allocator, 32768); 2269 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2270 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2271 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2272 var output: [256]u8 = undefined; 2273 var writer = std.Io.Writer.fixed(&output); 2274 var idle = IdleState{}; 2275 var conn = Conn{ 2276 .io = io, 2277 .allocator = allocator, 2278 .reader = &reader, 2279 .writer = &writer, 2280 .cs_cipher = Cipher.init(&key, 0), 2281 .sc_cipher = Cipher.init(&key, 0), 2282 .rekey = undefined, 2283 .idle = &idle, 2284 }; 2285 const Handler = struct { 2286 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2287 return error.UnexpectedSession; 2288 } 2289 }; 2290 var handler = Handler{}; 2291 try runChannelLayer(&conn, &.{ .fingerprint = @splat(0), .blob = "" }, &handler); 2292 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2293 var receiver = Cipher.init(&key, 0); 2294 const confirmation = try receiver.readPacket(allocator, &output_reader); 2295 defer allocator.free(confirmation); 2296 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2297 const close = try receiver.readPacket(allocator, &output_reader); 2298 defer allocator.free(close); 2299 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2300 try std.testing.expectEqual(0, output_reader.buffered().len); 2301 } 2302