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