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