╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1144 ) ![Sha256.digest_length]u8 { 1145 var buf: std.ArrayList(u8) = .empty; 1146 defer buf.deinit(allocator); 1147 1148 try writeStringField(&buf, allocator, client_version); 1149 try writeStringField(&buf, allocator, server_version_str); 1150 try writeStringField(&buf, allocator, client_kex_init); 1151 try writeStringField(&buf, allocator, server_kex_init); 1152 try writeStringField(&buf, allocator, host_key_blob); 1153 try writeStringField(&buf, allocator, client_ephemeral); 1154 try writeStringField(&buf, allocator, server_ephemeral); 1155 if (k_is_string) { 1156 try writeStringField(&buf, allocator, shared_secret); 1157 } else { 1158 try writeMpint(&buf, allocator, shared_secret); 1159 } 1160 1161 var hasher = Sha256.init(.{}); 1162 hasher.update(buf.items); 1163 return hasher.finalResult(); 1164 } 1165 1166 // --------------------------------------------------------------------------- 1167 // key derivation (RFC 4253 §7.2) 1168 // --------------------------------------------------------------------------- 1169 1170 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1171 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1172 // blocks chained per RFC 4253. 1173 pub const SessionKeys = struct { 1174 cs_enc: [64]u8, 1175 sc_enc: [64]u8, 1176 }; 1177 1178 pub fn deriveSessionKeys( 1179 allocator: std.mem.Allocator, 1180 shared_secret: []const u8, 1181 exchange_hash: []const u8, 1182 session_id: []const u8, 1183 out: *SessionKeys, 1184 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1185 k_is_string: bool, 1186 ) !void { 1187 // pre-build the K || H prefix once; reused for every derivation 1188 var prefix: std.ArrayList(u8) = .empty; 1189 defer prefix.deinit(allocator); 1190 if (k_is_string) { 1191 try writeStringField(&prefix, allocator, shared_secret); 1192 } else { 1193 try writeMpint(&prefix, allocator, shared_secret); 1194 } 1195 try prefix.appendSlice(allocator, exchange_hash); 1196 1197 try deriveKey(allocator, prefix.items, 'C', session_id, &out.cs_enc); 1198 try deriveKey(allocator, prefix.items, 'D', session_id, &out.sc_enc); 1199 } 1200 1201 fn deriveKey( 1202 allocator: std.mem.Allocator, 1203 prefix: []const u8, // K || H, already encoded 1204 letter: u8, 1205 session_id: []const u8, 1206 out: []u8, 1207 ) !void { 1208 // first block: HASH(K || H || letter || session_id) 1209 var first_block: [Sha256.digest_length]u8 = undefined; 1210 { 1211 var hasher = Sha256.init(.{}); 1212 hasher.update(prefix); 1213 hasher.update(&[_]u8{letter}); 1214 hasher.update(session_id); 1215 first_block = hasher.finalResult(); 1216 } 1217 const first_copy = @min(out.len, first_block.len); 1218 @memcpy(out[0..first_copy], first_block[0..first_copy]); 1219 1220 // chain additional blocks if requested length exceeds one hash: 1221 // K_{n+1} = HASH(K || H || K_1 || K_2 || … || K_n) 1222 var chained: std.ArrayList(u8) = .empty; 1223 defer chained.deinit(allocator); 1224 try chained.appendSlice(allocator, first_block[0..]); 1225 1226 var produced: usize = first_copy; 1227 while (produced < out.len) { 1228 var hasher = Sha256.init(.{}); 1229 hasher.update(prefix); 1230 hasher.update(chained.items); 1231 const block = hasher.finalResult(); 1232 const copy_len = @min(out.len - produced, block.len); 1233 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 1234 produced += copy_len; 1235 try chained.appendSlice(allocator, block[0..]); 1236 } 1237 } 1238 1239 // --------------------------------------------------------------------------- 1240 // chacha20-poly1305@openssh.com packet codec 1241 // --------------------------------------------------------------------------- 1242 // 1243 // per openssh's PROTOCOL.chacha20poly1305: 1244 // K_2 = first 32 bytes of key material — encrypts the packet body 1245 // K_1 = next 32 bytes — encrypts the 4-byte length field 1246 // nonce = 64-bit big-endian sequence number 1247 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1248 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1249 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1250 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1251 // 1252 // padding is computed on the body alone (padding_length byte + payload + 1253 // padding) — the 4-byte length field is excluded from alignment. body must 1254 // be a multiple of 8 bytes; minimum padding 4 bytes. 1255 1256 pub const Cipher = struct { 1257 main_key: [32]u8, // K_2 1258 header_key: [32]u8, // K_1 1259 seq: u64, 1260 idle: ?*IdleState = null, 1261 1262 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1263 return .{ 1264 .main_key = key_material[0..32].*, 1265 .header_key = key_material[32..64].*, 1266 .seq = initial_seq, 1267 }; 1268 } 1269 1270 /// swap in new key material after a rekey, leaving the rest of the 1271 /// cipher state alone 1272 fn setKeys(self: *Cipher, key_material: *const [64]u8, seq: u64) void { 1273 self.main_key = key_material[0..32].*; 1274 self.header_key = key_material[32..64].*; 1275 self.seq = seq; 1276 } 1277 1278 fn makeNonce(seq: u64) [8]u8 { 1279 var nonce: [8]u8 = undefined; 1280 std.mem.writeInt(u64, &nonce, seq, .big); 1281 return nonce; 1282 } 1283 1284 pub fn writePacket( 1285 self: *Cipher, 1286 io: std.Io, 1287 writer: *std.Io.Writer, 1288 payload: []const u8, 1289 ) !void { 1290 const block: usize = 8; 1291 const initial_pad = block - ((1 + payload.len) % block); 1292 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1293 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1294 1295 const nonce = makeNonce(self.seq); 1296 1297 // plaintext body = padding_length || payload || random padding. 1298 // stack-allocated to avoid a heap alloc on every packet. 1299 var body_buf: [max_packet_len]u8 = undefined; 1300 if (body_len > body_buf.len) return error.PacketTooLarge; 1301 const body = body_buf[0..body_len]; 1302 body[0] = padding_len; 1303 @memcpy(body[1 .. 1 + payload.len], payload); 1304 io.random(body[1 + payload.len ..]); 1305 1306 // encrypt body in place with counter=1 1307 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1308 1309 // encrypt length field with header key, counter=0 1310 var enc_length: [4]u8 = undefined; 1311 var length_plain: [4]u8 = undefined; 1312 std.mem.writeInt(u32, &length_plain, body_len, .big); 1313 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1314 1315 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1316 var poly_key: [Poly1305.key_length]u8 = undefined; 1317 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1318 1319 // mac over encrypted_length || encrypted_body 1320 var poly = Poly1305.init(&poly_key); 1321 poly.update(&enc_length); 1322 poly.update(body); 1323 var tag: [Poly1305.mac_length]u8 = undefined; 1324 poly.final(&tag); 1325 1326 try writer.writeAll(&enc_length); 1327 try writer.writeAll(body); 1328 try writer.writeAll(&tag); 1329 try writer.flush(); 1330 1331 self.seq += 1; 1332 } 1333 1334 pub fn readPacket( 1335 self: *Cipher, 1336 allocator: std.mem.Allocator, 1337 reader: *std.Io.Reader, 1338 ) ![]u8 { 1339 const nonce = makeNonce(self.seq); 1340 1341 var enc_length: [4]u8 = undefined; 1342 try reader.readSliceAll(&enc_length); 1343 1344 var length_plain: [4]u8 = undefined; 1345 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1346 const body_len = std.mem.readInt(u32, &length_plain, .big); 1347 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1348 1349 const enc_body = try allocator.alloc(u8, body_len); 1350 defer allocator.free(enc_body); 1351 try reader.readSliceAll(enc_body); 1352 1353 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1354 try reader.readSliceAll(&tag_recv); 1355 1356 var poly_key: [Poly1305.key_length]u8 = undefined; 1357 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1358 1359 var poly = Poly1305.init(&poly_key); 1360 poly.update(&enc_length); 1361 poly.update(enc_body); 1362 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1363 poly.final(&tag_computed); 1364 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1365 return error.MacVerificationFailed; 1366 } 1367 1368 // decrypt the body in place, then copy out the payload (caller owns) 1369 ChaCha20.xor(enc_body, enc_body, 1, self.main_key, nonce); 1370 1371 const padding_len = enc_body[0]; 1372 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1373 const payload_len = body_len - 1 - @as(u32, padding_len); 1374 1375 const payload = try allocator.dupe(u8, enc_body[1 .. 1 + payload_len]); 1376 1377 self.seq += 1; 1378 if (self.idle) |idle| _ = idle.activity.fetchAdd(1, .monotonic); 1379 return payload; 1380 } 1381 }; 1382 1383 // --------------------------------------------------------------------------- 1384 // post-KEX: service request + user authentication (RFC 4252) 1385 // --------------------------------------------------------------------------- 1386 1387 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1388 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1389 /// `Offering public key: … SHA256:…`. 1390 pub const fingerprint_len = 50; 1391 1392 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1393 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1394 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1395 var digest: [Sha256.digest_length]u8 = undefined; 1396 Sha256.hash(pubkey_blob, &digest, .{}); 1397 1398 var out: [fingerprint_len]u8 = undefined; 1399 @memcpy(out[0..7], "SHA256:"); 1400 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1401 std.debug.assert(encoded.len == fingerprint_len - 7); 1402 return out; 1403 } 1404 1405 fn runAuth(conn: *Conn) ![fingerprint_len]u8 { 1406 const allocator = conn.allocator; 1407 1408 // step 1: service request for ssh-userauth → service accept 1409 { 1410 const req = try readSessionPacket(conn); 1411 defer allocator.free(req); 1412 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1413 1414 var req_reader = std.Io.Reader.fixed(req[1..]); 1415 const service = try takeStringField(allocator, &req_reader, 64); 1416 defer allocator.free(service); 1417 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1418 1419 var accept: std.ArrayList(u8) = .empty; 1420 defer accept.deinit(allocator); 1421 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1422 try writeStringField(&accept, allocator, "ssh-userauth"); 1423 try conn.sc_cipher.writePacket(conn.io, conn.writer, accept.items); 1424 } 1425 1426 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1427 // signature verifies against the offered pubkey. 1428 var auth_attempts: u32 = 0; 1429 while (true) { 1430 const req = try readSessionPacket(conn); 1431 defer allocator.free(req); 1432 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1433 1434 var req_reader = std.Io.Reader.fixed(req[1..]); 1435 const user_name = try takeStringField(allocator, &req_reader, 256); 1436 defer allocator.free(user_name); 1437 const service_name = try takeStringField(allocator, &req_reader, 64); 1438 defer allocator.free(service_name); 1439 const method = try takeStringField(allocator, &req_reader, 64); 1440 defer allocator.free(method); 1441 1442 // RFC 4252 §5: the server must verify the requested service 1443 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1444 auth_attempts += 1; 1445 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1446 try sendUserauthFailure(conn); 1447 continue; 1448 } 1449 1450 if (!std.mem.eql(u8, method, "publickey")) { 1451 auth_attempts += 1; 1452 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1453 try sendUserauthFailure(conn); 1454 continue; 1455 } 1456 1457 const has_signature = (try req_reader.takeByte()) != 0; 1458 const algo = try takeStringField(allocator, &req_reader, 64); 1459 defer allocator.free(algo); 1460 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1461 defer allocator.free(pubkey_blob); 1462 1463 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1464 auth_attempts += 1; 1465 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1466 try sendUserauthFailure(conn); 1467 continue; 1468 } 1469 1470 if (!has_signature) { 1471 // probes count as attempts so a client can't loop here forever 1472 auth_attempts += 1; 1473 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1474 // probe — tell the client this key is acceptable so it'll send 1475 // the signed version next. 1476 var pk_ok: std.ArrayList(u8) = .empty; 1477 defer pk_ok.deinit(allocator); 1478 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1479 try writeStringField(&pk_ok, allocator, algo); 1480 try writeStringField(&pk_ok, allocator, pubkey_blob); 1481 try conn.sc_cipher.writePacket(conn.io, conn.writer, pk_ok.items); 1482 continue; 1483 } 1484 1485 // has signature — verify it 1486 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1487 defer allocator.free(signature_blob); 1488 1489 const ok = verifyUserauthSignature( 1490 allocator, 1491 &conn.rekey.session_id, 1492 user_name, 1493 service_name, 1494 algo, 1495 pubkey_blob, 1496 signature_blob, 1497 ) catch false; 1498 1499 if (!ok) { 1500 auth_attempts += 1; 1501 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1502 try sendUserauthFailure(conn); 1503 continue; 1504 } 1505 1506 try conn.sc_cipher.writePacket(conn.io, conn.writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1507 return formatFingerprint(pubkey_blob); 1508 } 1509 } 1510 1511 fn sendUserauthFailure(conn: *Conn) !void { 1512 var buf: std.ArrayList(u8) = .empty; 1513 defer buf.deinit(conn.allocator); 1514 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1515 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1516 try buf.append(conn.allocator, 0); // partial_success = false 1517 try conn.sc_cipher.writePacket(conn.io, conn.writer, buf.items); 1518 } 1519 1520 /// Append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1521 /// Used by the server to recompute the signed input for verification 1522 pub fn appendPublickeySignedData( 1523 buf: *std.ArrayList(u8), 1524 allocator: std.mem.Allocator, 1525 session_id: []const u8, 1526 user_name: []const u8, 1527 service_name: []const u8, 1528 algo: []const u8, 1529 pubkey_blob: []const u8, 1530 ) !void { 1531 try writeStringField(buf, allocator, session_id); 1532 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1533 try writeStringField(buf, allocator, user_name); 1534 try writeStringField(buf, allocator, service_name); 1535 try writeStringField(buf, allocator, "publickey"); 1536 try buf.append(allocator, 1); 1537 try writeStringField(buf, allocator, algo); 1538 try writeStringField(buf, allocator, pubkey_blob); 1539 } 1540 1541 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1542 // verify the supplied signature against them. 1543 fn verifyUserauthSignature( 1544 allocator: std.mem.Allocator, 1545 session_id: *const [Sha256.digest_length]u8, 1546 user_name: []const u8, 1547 service_name: []const u8, 1548 algo: []const u8, 1549 pubkey_blob: []const u8, 1550 signature_blob: []const u8, 1551 ) !bool { 1552 var signed: std.ArrayList(u8) = .empty; 1553 defer signed.deinit(allocator); 1554 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1555 1556 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1557 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1558 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1559 defer allocator.free(pk_algo); 1560 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1561 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1562 defer allocator.free(raw_pubkey); 1563 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1564 1565 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1566 var sig_reader = std.Io.Reader.fixed(signature_blob); 1567 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1568 defer allocator.free(sig_algo); 1569 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1570 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1571 defer allocator.free(raw_sig); 1572 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1573 1574 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1575 @memcpy(&pubkey_bytes, raw_pubkey); 1576 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1577 @memcpy(&sig_bytes, raw_sig); 1578 1579 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1580 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1581 sig.verify(signed.items, pk) catch return false; 1582 return true; 1583 } 1584 1585 // --------------------------------------------------------------------------- 1586 // connection layer (RFC 4254): channels, requests, data, flow control 1587 // --------------------------------------------------------------------------- 1588 1589 const Channel = struct { 1590 local_id: u32, 1591 remote_id: u32, 1592 local_window: u32, // bytes peer may still send us before we adjust 1593 remote_window: u32, // bytes we may still send to peer before they adjust 1594 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1595 pty: ?PtySize = null, 1596 }; 1597 1598 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1599 1600 // take the uint32 width/height cell counts of a pty-req or window-change, 1601 // clamped to u16 1602 fn takePtySize(r: *std.Io.Reader) !PtySize { 1603 const width = try r.takeInt(u32, .big); 1604 const height = try r.takeInt(u32, .big); 1605 return .{ 1606 .width_cells = @intCast(@min(width, 0xFFFF)), 1607 .height_cells = @intCast(@min(height, 0xFFFF)), 1608 }; 1609 } 1610 1611 fn runChannelLayer( 1612 conn: *Conn, 1613 fingerprint: *const [fingerprint_len]u8, 1614 handler: anytype, 1615 ) !void { 1616 const allocator = conn.allocator; 1617 var channel: ?Channel = null; 1618 var pending_exec: ?[]u8 = null; 1619 defer if (pending_exec) |s| allocator.free(s); 1620 1621 while (true) { 1622 const packet = try readSessionPacket(conn); 1623 defer allocator.free(packet); 1624 if (packet.len < 1) return error.EmptyPacket; 1625 const msg_type = packet[0]; 1626 1627 switch (msg_type) { 1628 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1629 1630 SSH_MSG_CHANNEL_OPEN => { 1631 if (channel != null) { 1632 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1633 continue; 1634 } 1635 channel = try handleChannelOpen(conn, packet) orelse continue; 1636 }, 1637 1638 SSH_MSG_CHANNEL_REQUEST => { 1639 const ch = if (channel) |*c| c else continue; 1640 const start_request = try handleChannelRequest(conn, ch, packet, &pending_exec); 1641 if (start_request) |req_kind| { 1642 const request: Request = switch (req_kind) { 1643 .shell => .{ .shell = ch.pty }, 1644 .exec => .{ .exec = pending_exec.? }, 1645 }; 1646 var sess = SessionCtx{ 1647 .conn = conn, 1648 .channel = ch, 1649 .fingerprint = fingerprint.*, 1650 }; 1651 defer sess.deinit(); 1652 handler.handleSession(&sess, request) catch |session_err| { 1653 // try to send a non-zero exit status before closing 1654 sess.exit(1) catch {}; 1655 return session_err; 1656 }; 1657 if (!sess.closed) try sess.exit(0); 1658 return; 1659 } 1660 }, 1661 1662 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1663 const ch = if (channel) |*c| c else continue; 1664 try handleWindowAdjust(ch, packet); 1665 }, 1666 1667 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1668 const ch = if (channel) |*c| c else continue; 1669 // before shell/exec the client shouldn't be sending data, but 1670 // some clients are chatty; discard and refill window. 1671 try discardChannelData(conn, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1672 }, 1673 1674 SSH_MSG_CHANNEL_EOF => { 1675 if (channel) |*c| try parseChannelId(packet, c.local_id); 1676 }, 1677 1678 SSH_MSG_CHANNEL_CLOSE => { 1679 if (channel) |*c| try parseChannelId(packet, c.local_id); 1680 return; 1681 }, 1682 1683 else => {}, // ignore unknown messages 1684 } 1685 } 1686 } 1687 1688 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1689 // byte SSH_MSG_GLOBAL_REQUEST 1690 // string request_name 1691 // boolean want_reply 1692 // …request-specific data we ignore 1693 var r = std.Io.Reader.fixed(packet[1..]); 1694 const name = try takeStringField(conn.allocator, &r, 256); 1695 defer conn.allocator.free(name); 1696 const want_reply = (try r.takeByte()) != 0; 1697 if (want_reply) { 1698 try conn.sc_cipher.writePacket(conn.io, conn.writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1699 } 1700 } 1701 1702 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1703 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1704 /// return null. 1705 fn handleChannelOpen(conn: *Conn, packet: []const u8) !?Channel { 1706 const allocator = conn.allocator; 1707 1708 // byte SSH_MSG_CHANNEL_OPEN 1709 // string channel_type 1710 // uint32 sender_channel (peer's id) 1711 // uint32 initial_window 1712 // uint32 max_packet 1713 var r = std.Io.Reader.fixed(packet[1..]); 1714 const ch_type = try takeStringField(allocator, &r, 64); 1715 defer allocator.free(ch_type); 1716 const remote_id = try r.takeInt(u32, .big); 1717 const initial_window = try r.takeInt(u32, .big); 1718 const max_packet = try r.takeInt(u32, .big); 1719 1720 if (!std.mem.eql(u8, ch_type, "session")) { 1721 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1722 return null; 1723 } 1724 1725 // a zero max_packet would leave writeChannel looping without progress 1726 if (max_packet == 0) { 1727 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1728 return null; 1729 } 1730 1731 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1732 var reply: std.ArrayList(u8) = .empty; 1733 defer reply.deinit(allocator); 1734 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1735 try writeU32(&reply, allocator, remote_id); 1736 try writeU32(&reply, allocator, local_id); 1737 try writeU32(&reply, allocator, initial_recv_window); 1738 try writeU32(&reply, allocator, max_packet_size); 1739 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1740 1741 return .{ 1742 .local_id = local_id, 1743 .remote_id = remote_id, 1744 .local_window = initial_recv_window, 1745 .remote_window = initial_window, 1746 .max_packet = max_packet, 1747 }; 1748 } 1749 1750 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 1751 const allocator = conn.allocator; 1752 1753 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1754 // address the failure to the correct id 1755 var r = std.Io.Reader.fixed(open_packet[1..]); 1756 const ch_type_len = try r.takeInt(u32, .big); 1757 try r.discardAll(ch_type_len); 1758 const remote_id = try r.takeInt(u32, .big); 1759 1760 var reply: std.ArrayList(u8) = .empty; 1761 defer reply.deinit(allocator); 1762 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1763 try writeU32(&reply, allocator, remote_id); 1764 try writeU32(&reply, allocator, reason); 1765 try writeStringField(&reply, allocator, description); 1766 try writeStringField(&reply, allocator, ""); // language tag 1767 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1768 } 1769 1770 const RequestKind = enum { shell, exec }; 1771 1772 /// Returns the kind of session request if this triggered one, else null. 1773 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8, pending_exec: *?[]u8) !?RequestKind { 1774 const allocator = conn.allocator; 1775 1776 // byte SSH_MSG_CHANNEL_REQUEST 1777 // uint32 recipient_channel (== our local_id) 1778 // string request_type 1779 // boolean want_reply 1780 // …request-specific data 1781 var r = std.Io.Reader.fixed(packet[1..]); 1782 const recipient_channel = try r.takeInt(u32, .big); 1783 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1784 const req_type = try takeStringField(allocator, &r, 64); 1785 defer allocator.free(req_type); 1786 const want_reply = (try r.takeByte()) != 0; 1787 1788 if (std.mem.eql(u8, req_type, "pty-req")) { 1789 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1790 // uint32 height px, string modes 1791 const term = try takeStringField(allocator, &r, 64); 1792 defer allocator.free(term); 1793 ch.pty = try takePtySize(&r); 1794 try replyChannelRequest(conn, ch, want_reply, true); 1795 return null; 1796 } 1797 1798 if (std.mem.eql(u8, req_type, "env")) { 1799 // ignore environment variables silently (we don't pass them anywhere) 1800 try replyChannelRequest(conn, ch, want_reply, true); 1801 return null; 1802 } 1803 1804 if (std.mem.eql(u8, req_type, "window-change")) { 1805 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1806 const sz = try takePtySize(&r); 1807 if (ch.pty != null) ch.pty = sz; 1808 // spec: window-change MUST NOT request a reply, but accept either 1809 try replyChannelRequest(conn, ch, want_reply, true); 1810 return null; 1811 } 1812 1813 if (std.mem.eql(u8, req_type, "shell")) { 1814 try replyChannelRequest(conn, ch, want_reply, true); 1815 return .shell; 1816 } 1817 1818 if (std.mem.eql(u8, req_type, "exec")) { 1819 // capture the command string for the handler to inspect 1820 const cmd = try takeStringField(allocator, &r, 4096); 1821 if (pending_exec.*) |old| allocator.free(old); 1822 pending_exec.* = cmd; 1823 try replyChannelRequest(conn, ch, want_reply, true); 1824 return .exec; 1825 } 1826 1827 // unknown request kind — fail it 1828 try replyChannelRequest(conn, ch, want_reply, false); 1829 return null; 1830 } 1831 1832 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 1833 if (!want_reply) return; 1834 var reply: std.ArrayList(u8) = .empty; 1835 defer reply.deinit(conn.allocator); 1836 try reply.append(conn.allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1837 try writeU32(&reply, conn.allocator, ch.remote_id); 1838 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1839 } 1840 1841 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1842 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1843 // uint32 recipient_channel 1844 // uint32 bytes_to_add 1845 var r = std.Io.Reader.fixed(packet[1..]); 1846 const recipient_channel = try r.takeInt(u32, .big); 1847 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1848 const add = try r.takeInt(u32, .big); 1849 ch.remote_window +|= add; 1850 } 1851 1852 fn discardChannelData(conn: *Conn, ch: *Channel, packet: []const u8, extended: bool) !void { 1853 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1854 // uint32 recipient_channel 1855 // [if extended: uint32 type_code] 1856 // string data 1857 const payload = try parseChannelData(packet, extended, ch.local_id); 1858 const data_len: u32 = @intCast(payload.len); 1859 1860 if (data_len > ch.local_window) return error.WindowExceeded; 1861 ch.local_window -= data_len; 1862 try maybeRefillRecvWindow(conn, ch); 1863 } 1864 1865 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1866 if (packet.len < 1) return error.EmptyPacket; 1867 var r = std.Io.Reader.fixed(packet[1..]); 1868 const recipient_channel = try r.takeInt(u32, .big); 1869 if (recipient_channel != expected_channel) return error.UnknownChannel; 1870 if (extended) { 1871 const data_type = try r.takeInt(u32, .big); 1872 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1873 } 1874 const data_len = try r.takeInt(u32, .big); 1875 // catches both data_len > remaining (would otherwise be a bounds-check 1876 // panic on the slice) and trailing junk after the declared payload. 1877 if (data_len != r.buffered().len) return error.InvalidChannelData; 1878 return r.buffered(); 1879 } 1880 1881 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1882 if (packet.len < 1) return error.EmptyPacket; 1883 var r = std.Io.Reader.fixed(packet[1..]); 1884 const recipient_channel = try r.takeInt(u32, .big); 1885 if (recipient_channel != expected_channel) return error.UnknownChannel; 1886 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1887 } 1888 1889 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1890 /// of the initial value. Used both for the pre-session discard path and by 1891 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1892 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel) !void { 1893 if (ch.local_window >= initial_recv_window / 2) return; 1894 const add = initial_recv_window - ch.local_window; 1895 ch.local_window += add; 1896 var adj: std.ArrayList(u8) = .empty; 1897 defer adj.deinit(conn.allocator); 1898 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1899 try writeU32(&adj, conn.allocator, ch.remote_id); 1900 try writeU32(&adj, conn.allocator, add); 1901 try conn.sc_cipher.writePacket(conn.io, conn.writer, adj.items); 1902 } 1903 1904 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1905 var bytes: [4]u8 = undefined; 1906 std.mem.writeInt(u32, &bytes, value, .big); 1907 try buf.appendSlice(allocator, &bytes); 1908 } 1909