╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1368 return exchange_hash; 1369 } 1370 1371 // --------------------------------------------------------------------------- 1372 // exchange hash (RFC 4253 §8, RFC 5656 §4) 1373 // --------------------------------------------------------------------------- 1374 1375 pub fn computeExchangeHash( 1376 allocator: std.mem.Allocator, 1377 client_version: []const u8, 1378 server_version_str: []const u8, 1379 client_kex_init: []const u8, 1380 server_kex_init: []const u8, 1381 host_key_blob: []const u8, 1382 client_ephemeral: []const u8, 1383 server_ephemeral: []const u8, 1384 shared_secret: []const u8, 1385 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 1386 /// as a plain SSH string (length-prefixed bytes). 1387 k_is_string: bool, 1388 ) ![Sha256.digest_length]u8 { 1389 var buf: std.ArrayList(u8) = .empty; 1390 defer buf.deinit(allocator); 1391 defer std.crypto.secureZero(u8, buf.items); 1392 // reserved up front so a reallocation can't leave K behind 1393 try buf.ensureTotalCapacityPrecise(allocator, 8 * 4 + 1 + client_version.len + server_version_str.len + 1394 client_kex_init.len + server_kex_init.len + host_key_blob.len + client_ephemeral.len + 1395 server_ephemeral.len + shared_secret.len); 1396 1397 try writeStringField(&buf, allocator, client_version); 1398 try writeStringField(&buf, allocator, server_version_str); 1399 try writeStringField(&buf, allocator, client_kex_init); 1400 try writeStringField(&buf, allocator, server_kex_init); 1401 try writeStringField(&buf, allocator, host_key_blob); 1402 try writeStringField(&buf, allocator, client_ephemeral); 1403 try writeStringField(&buf, allocator, server_ephemeral); 1404 if (k_is_string) { 1405 try writeStringField(&buf, allocator, shared_secret); 1406 } else { 1407 try writeMpint(&buf, allocator, shared_secret); 1408 } 1409 1410 var hasher = Sha256.init(.{}); 1411 defer std.crypto.secureZero(u8, std.mem.asBytes(&hasher)); 1412 hasher.update(buf.items); 1413 return hasher.finalResult(); 1414 } 1415 1416 // --------------------------------------------------------------------------- 1417 // key derivation (RFC 4253 §7.2) 1418 // --------------------------------------------------------------------------- 1419 1420 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1421 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1422 // blocks chained per RFC 4253. 1423 pub const SessionKeys = struct { 1424 cs_enc: [64]u8, 1425 sc_enc: [64]u8, 1426 }; 1427 1428 pub fn deriveSessionKeys( 1429 allocator: std.mem.Allocator, 1430 shared_secret: []const u8, 1431 exchange_hash: []const u8, 1432 session_id: []const u8, 1433 out: *SessionKeys, 1434 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1435 k_is_string: bool, 1436 ) !void { 1437 // pre-build the K || H prefix once; reused for every derivation 1438 var prefix: std.ArrayList(u8) = .empty; 1439 defer prefix.deinit(allocator); 1440 defer std.crypto.secureZero(u8, prefix.items); 1441 // reserved up front so a reallocation can't leave K behind 1442 try prefix.ensureTotalCapacityPrecise(allocator, 4 + 1 + shared_secret.len + exchange_hash.len); 1443 if (k_is_string) { 1444 try writeStringField(&prefix, allocator, shared_secret); 1445 } else { 1446 try writeMpint(&prefix, allocator, shared_secret); 1447 } 1448 try prefix.appendSlice(allocator, exchange_hash); 1449 1450 deriveKey(prefix.items, 'C', session_id, &out.cs_enc); 1451 deriveKey(prefix.items, 'D', session_id, &out.sc_enc); 1452 } 1453 1454 fn deriveKey( 1455 prefix: []const u8, // K || H, already encoded 1456 letter: u8, 1457 session_id: []const u8, 1458 out: *[2 * Sha256.digest_length]u8, 1459 ) void { 1460 // a finished context still holds its digest and last input block 1461 // K_1 = HASH(K || H || letter || session_id) 1462 var first = Sha256.init(.{}); 1463 defer std.crypto.secureZero(u8, std.mem.asBytes(&first)); 1464 first.update(prefix); 1465 first.update(&.{letter}); 1466 first.update(session_id); 1467 first.final(out[0..Sha256.digest_length]); 1468 1469 // K_2 = HASH(K || H || K_1) 1470 var second = Sha256.init(.{}); 1471 defer std.crypto.secureZero(u8, std.mem.asBytes(&second)); 1472 second.update(prefix); 1473 second.update(out[0..Sha256.digest_length]); 1474 second.final(out[Sha256.digest_length..]); 1475 } 1476 1477 // --------------------------------------------------------------------------- 1478 // chacha20-poly1305@openssh.com packet codec 1479 // --------------------------------------------------------------------------- 1480 // 1481 // per openssh's PROTOCOL.chacha20poly1305: 1482 // K_2 = first 32 bytes of key material — encrypts the packet body 1483 // K_1 = next 32 bytes — encrypts the 4-byte length field 1484 // nonce = 64-bit big-endian sequence number 1485 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1486 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1487 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1488 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1489 // 1490 // padding is computed on the body alone (padding_length byte + payload + 1491 // padding) — the 4-byte length field is excluded from alignment. body must 1492 // be a multiple of 8 bytes; minimum padding 4 bytes. 1493 1494 pub const Cipher = struct { 1495 main_key: [32]u8, // K_2 1496 header_key: [32]u8, // K_1 1497 // wider than the 32-bit wire seqno, so a peer that never rekeys fails the 1498 // mac at 2^32 packets instead of wrapping into nonce reuse 1499 seq: u64, 1500 1501 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1502 return .{ 1503 .main_key = key_material[0..32].*, 1504 .header_key = key_material[32..64].*, 1505 .seq = initial_seq, 1506 }; 1507 } 1508 1509 fn makeNonce(seq: u64) [8]u8 { 1510 var nonce: [8]u8 = undefined; 1511 std.mem.writeInt(u64, &nonce, seq, .big); 1512 return nonce; 1513 } 1514 1515 fn bodyLength(self: *const Cipher, enc_length: *const [4]u8) !u32 { 1516 var plain: [4]u8 = undefined; 1517 ChaCha20.xor(&plain, enc_length, 0, self.header_key, makeNonce(self.seq)); 1518 const len = std.mem.readInt(u32, &plain, .big); 1519 if (len < 8 or len > max_packet_len or len % 8 != 0) return error.InvalidPacketLength; 1520 return len; 1521 } 1522 1523 fn peekPacket(self: *const Cipher, reader: *std.Io.Reader) !void { 1524 const len = 4 + (try self.bodyLength(try reader.peekArray(4))) + Poly1305.mac_length; 1525 if (len > reader.buffer.len) return error.ReadBufferTooSmall; 1526 _ = try reader.peek(len); 1527 } 1528 1529 fn hasBufferedPacket(self: *const Cipher, reader: *std.Io.Reader) !bool { 1530 const bytes = reader.buffered(); 1531 if (bytes.len < 4) return false; 1532 return bytes.len >= 4 + (try self.bodyLength(bytes[0..4])) + Poly1305.mac_length; 1533 } 1534 1535 /// the payload is the concatenation of `parts` 1536 pub fn writePacket( 1537 self: *Cipher, 1538 io: std.Io, 1539 writer: *std.Io.Writer, 1540 parts: []const []const u8, 1541 ) !void { 1542 var payload_len: usize = 0; 1543 for (parts) |part| payload_len += part.len; 1544 1545 const block: usize = 8; 1546 const initial_pad = block - ((1 + payload_len) % block); 1547 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1548 const body_len = 1 + payload_len + padding_len; 1549 if (body_len > max_packet_len) return error.PacketTooLarge; 1550 1551 const nonce = makeNonce(self.seq); 1552 1553 // encrypted length || body || mac, contiguous so the packet goes out 1554 // in one write. stack-allocated to avoid a heap alloc on every packet. 1555 var packet_buf: [packet_buffer_size]u8 = undefined; 1556 const packet = packet_buf[0 .. 4 + body_len + Poly1305.mac_length]; 1557 const enc_length = packet[0..4]; 1558 const body = packet[4..][0..body_len]; 1559 1560 // plaintext body = padding_length || payload || random padding 1561 body[0] = padding_len; 1562 var end: usize = 1; 1563 for (parts) |part| { 1564 @memcpy(body[end..][0..part.len], part); 1565 end += part.len; 1566 } 1567 io.random(body[end..]); 1568 1569 // encrypt body in place with counter=1 1570 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1571 1572 // encrypt length field with header key, counter=0 1573 std.mem.writeInt(u32, enc_length, @intCast(body_len), .big); 1574 ChaCha20.xor(enc_length, enc_length, 0, self.header_key, nonce); 1575 1576 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1577 var poly_key: [Poly1305.key_length]u8 = undefined; 1578 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1579 1580 // mac over encrypted_length || encrypted_body 1581 var poly = Poly1305.init(&poly_key); 1582 poly.update(packet[0 .. 4 + body_len]); 1583 poly.final(packet[4 + body_len ..][0..Poly1305.mac_length]); 1584 1585 try writer.writeAll(packet); 1586 try writer.flush(); 1587 1588 self.seq += 1; 1589 } 1590 1591 pub fn readPacket( 1592 self: *Cipher, 1593 allocator: std.mem.Allocator, 1594 reader: *std.Io.Reader, 1595 ) ![]u8 { 1596 const nonce = makeNonce(self.seq); 1597 1598 var enc_length: [4]u8 = undefined; 1599 try reader.readSliceAll(&enc_length); 1600 1601 const body_len = try self.bodyLength(&enc_length); 1602 1603 // the body allocation becomes the returned payload, so a packet only 1604 // ever costs one allocation 1605 const body = try allocator.alloc(u8, body_len); 1606 errdefer allocator.free(body); 1607 try reader.readSliceAll(body); 1608 1609 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1610 try reader.readSliceAll(&tag_recv); 1611 1612 var poly_key: [Poly1305.key_length]u8 = undefined; 1613 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1614 1615 var poly = Poly1305.init(&poly_key); 1616 poly.update(&enc_length); 1617 poly.update(body); 1618 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1619 poly.final(&tag_computed); 1620 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1621 return error.MacVerificationFailed; 1622 } 1623 1624 // decrypt the body in place 1625 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1626 1627 const padding_len = body[0]; 1628 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1629 const payload_len = body_len - 1 - @as(u32, padding_len); 1630 // a payload starts with its message type 1631 if (payload_len == 0) return error.EmptyPacket; 1632 1633 // shift the payload over the padding_length byte, then release the 1634 // trailing padding (caller owns the result) 1635 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1636 const payload = try allocator.realloc(body, payload_len); 1637 1638 self.seq += 1; 1639 return payload; 1640 } 1641 }; 1642 1643 // --------------------------------------------------------------------------- 1644 // post-KEX: service request + user authentication (RFC 4252) 1645 // --------------------------------------------------------------------------- 1646 1647 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1648 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1649 /// `Offering public key: … SHA256:…`. 1650 pub const fingerprint_len = 50; 1651 1652 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1653 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1654 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1655 var digest: [Sha256.digest_length]u8 = undefined; 1656 Sha256.hash(pubkey_blob, &digest, .{}); 1657 1658 var out: [fingerprint_len]u8 = undefined; 1659 @memcpy(out[0..7], "SHA256:"); 1660 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1661 std.debug.assert(encoded.len == fingerprint_len - 7); 1662 return out; 1663 } 1664 1665 fn runAuth(conn: *Conn) ![fingerprint_len]u8 { 1666 const allocator = conn.allocator; 1667 1668 // step 1: service request for ssh-userauth → service accept 1669 { 1670 const req = try readSessionPacket(conn); 1671 defer allocator.free(req); 1672 if (req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1673 1674 var req_reader = std.Io.Reader.fixed(req[1..]); 1675 const service = try takeString(&req_reader, 64); 1676 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1677 1678 var accept: std.ArrayList(u8) = .empty; 1679 defer accept.deinit(allocator); 1680 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1681 try writeStringField(&accept, allocator, "ssh-userauth"); 1682 try conn.writePacket(&.{accept.items}); 1683 } 1684 1685 // step 2: USERAUTH loop until SUCCESS. accept any supported key whose 1686 // signature verifies against the offered pubkey. 1687 var auth_attempts: u32 = 0; 1688 while (true) { 1689 const req = try readSessionPacket(conn); 1690 defer allocator.free(req); 1691 if (req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1692 1693 // every request counts, probes included, so a client can't loop here 1694 // forever 1695 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1696 auth_attempts += 1; 1697 1698 var req_reader = std.Io.Reader.fixed(req[1..]); 1699 const user_name = try takeString(&req_reader, 256); 1700 const service_name = try takeString(&req_reader, 64); 1701 const method = try takeString(&req_reader, 64); 1702 1703 // RFC 4252 §5: the server must verify the requested service 1704 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1705 try sendUserauthFailure(conn); 1706 continue; 1707 } 1708 1709 if (!std.mem.eql(u8, method, "publickey")) { 1710 try sendUserauthFailure(conn); 1711 continue; 1712 } 1713 1714 const has_signature = (try req_reader.takeByte()) != 0; 1715 const algo = try takeString(&req_reader, 64); 1716 const pubkey_blob = try takeString(&req_reader, 4096); 1717 1718 if (firstCommonName(algo, &our_userauth_algos) == null) { 1719 try sendUserauthFailure(conn); 1720 continue; 1721 } 1722 1723 if (!has_signature) { 1724 // probe — tell the client this key is acceptable so it'll send 1725 // the signed version next. 1726 var pk_ok: std.ArrayList(u8) = .empty; 1727 defer pk_ok.deinit(allocator); 1728 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1729 try writeStringField(&pk_ok, allocator, algo); 1730 try writeStringField(&pk_ok, allocator, pubkey_blob); 1731 try conn.writePacket(&.{pk_ok.items}); 1732 continue; 1733 } 1734 1735 // has signature — verify it 1736 const signature_blob = try takeString(&req_reader, 1024); 1737 1738 const ok = verifyUserauthSignature( 1739 allocator, 1740 &conn.rekey.session_id, 1741 user_name, 1742 service_name, 1743 algo, 1744 pubkey_blob, 1745 signature_blob, 1746 ) catch |err| switch (err) { 1747 error.OutOfMemory => return err, 1748 // a malformed key or signature blob 1749 else => false, 1750 }; 1751 1752 if (!ok) { 1753 try sendUserauthFailure(conn); 1754 continue; 1755 } 1756 1757 try conn.writePacket(&.{&[_]u8{SSH_MSG_USERAUTH_SUCCESS}}); 1758 return formatFingerprint(pubkey_blob); 1759 } 1760 } 1761 1762 fn sendUserauthFailure(conn: *Conn) !void { 1763 var buf: std.ArrayList(u8) = .empty; 1764 defer buf.deinit(conn.allocator); 1765 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1766 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1767 try buf.append(conn.allocator, 0); // partial_success = false 1768 try conn.writePacket(&.{buf.items}); 1769 } 1770 1771 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1772 /// used by the server to recompute the signed input for verification 1773 pub fn appendPublickeySignedData( 1774 buf: *std.ArrayList(u8), 1775 allocator: std.mem.Allocator, 1776 session_id: []const u8, 1777 user_name: []const u8, 1778 service_name: []const u8, 1779 algo: []const u8, 1780 pubkey_blob: []const u8, 1781 ) !void { 1782 try writeStringField(buf, allocator, session_id); 1783 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1784 try writeStringField(buf, allocator, user_name); 1785 try writeStringField(buf, allocator, service_name); 1786 try writeStringField(buf, allocator, "publickey"); 1787 try buf.append(allocator, 1); 1788 try writeStringField(buf, allocator, algo); 1789 try writeStringField(buf, allocator, pubkey_blob); 1790 } 1791 1792 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1793 // verify the supplied signature against them. 1794 fn verifyUserauthSignature( 1795 allocator: std.mem.Allocator, 1796 session_id: *const [Sha256.digest_length]u8, 1797 user_name: []const u8, 1798 service_name: []const u8, 1799 algo: []const u8, 1800 pubkey_blob: []const u8, 1801 signature_blob: []const u8, 1802 ) !bool { 1803 var signed: std.ArrayList(u8) = .empty; 1804 defer signed.deinit(allocator); 1805 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1806 1807 if (std.mem.eql(u8, algo, "ssh-ed25519")) return verifyEd25519(pubkey_blob, signature_blob, signed.items); 1808 if (std.mem.eql(u8, algo, "rsa-sha2-512")) return verifyRsa(Sha512, algo, pubkey_blob, signature_blob, signed.items); 1809 if (std.mem.eql(u8, algo, "rsa-sha2-256")) return verifyRsa(Sha256, algo, pubkey_blob, signature_blob, signed.items); 1810 return false; 1811 } 1812 1813 fn verifyEd25519(pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1814 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1815 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1816 const pk_algo = try takeString(&pubkey_reader, 64); 1817 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1818 const raw_pubkey = try takeString(&pubkey_reader, 64); 1819 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1820 1821 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1822 var sig_reader = std.Io.Reader.fixed(signature_blob); 1823 const sig_algo = try takeString(&sig_reader, 64); 1824 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1825 const raw_sig = try takeString(&sig_reader, Ed25519.Signature.encoded_length); 1826 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1827 1828 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1829 @memcpy(&pubkey_bytes, raw_pubkey); 1830 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1831 @memcpy(&sig_bytes, raw_sig); 1832 1833 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1834 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1835 sig.verify(signed, pk) catch return false; 1836 return true; 1837 } 1838 1839 fn verifyRsa(comptime Hash: type, algo: []const u8, pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1840 // parse pubkey_blob: string "ssh-rsa" || mpint e || mpint n 1841 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1842 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), "ssh-rsa")) return false; 1843 const e = std.mem.trimStart(u8, try takeString(&pubkey_reader, 1024), &.{0}); 1844 const n = std.mem.trimStart(u8, try takeString(&pubkey_reader, 1024), &.{0}); 1845 1846 // parse signature_blob: string algo || string sig 1847 var sig_reader = std.Io.Reader.fixed(signature_blob); 1848 if (!std.mem.eql(u8, try takeString(&sig_reader, 64), algo)) return false; 1849 const sig = try takeString(&sig_reader, 1024); 1850 if (sig.len != n.len) return false; 1851 1852 const pk = rsa.PublicKey.fromBytes(e, n) catch return false; 1853 switch (n.len) { 1854 inline 256, 384, 512 => |len| { 1855 rsa.PKCS1v1_5Signature.verify(len, sig[0..len].*, signed, pk, Hash) catch return false; 1856 return true; 1857 }, 1858 else => return false, 1859 } 1860 } 1861 1862 // --------------------------------------------------------------------------- 1863 // connection layer (RFC 4254): channels, requests, data, flow control 1864 // --------------------------------------------------------------------------- 1865 1866 const Channel = struct { 1867 local_id: u32, 1868 remote_id: u32, 1869 local_window: u32, // bytes peer may still send us before we adjust 1870 remote_window: u32, // bytes we may still send to peer before they adjust 1871 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1872 pty: ?PtySize = null, 1873 // value of GIT_PROTOCOL, the one env variable we keep 1874 git_protocol_buf: [64]u8 = undefined, 1875 git_protocol_len: ?usize = null, 1876 }; 1877 1878 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1879 1880 // take the uint32 width/height cell counts of a pty-req or window-change, 1881 // bounded before either initial rendering or a resize can allocate grids. 1882 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1883 fn takePtySize(r: *std.Io.Reader) !PtySize { 1884 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1885 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1886 return .{ 1887 .width_cells = @intCast(width), 1888 .height_cells = @intCast(height), 1889 }; 1890 } 1891 1892 fn runChannelLayer( 1893 conn: *Conn, 1894 fingerprint: *const [fingerprint_len]u8, 1895 handler: anytype, 1896 ) !void { 1897 const allocator = conn.allocator; 1898 var channel: ?Channel = null; 1899 1900 while (true) { 1901 const packet = try readSessionPacket(conn); 1902 defer allocator.free(packet); 1903 const msg_type = packet[0]; 1904 1905 switch (msg_type) { 1906 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1907 1908 SSH_MSG_CHANNEL_OPEN => { 1909 channel = try handleChannelOpen(conn, packet, channel != null) orelse continue; 1910 }, 1911 1912 SSH_MSG_CHANNEL_REQUEST => { 1913 const ch = if (channel) |*c| c else continue; 1914 const start_request = try handleChannelRequest(conn, ch, packet); 1915 // the request borrows from the packet, which outlives the session 1916 if (start_request) |request| { 1917 // any key authenticates, so the deadline holds until here 1918 conn.idle.session_started.store(true, .release); 1919 var sess = SessionCtx{ 1920 .conn = conn, 1921 .channel = ch, 1922 .fingerprint = fingerprint.*, 1923 }; 1924 defer sess.deinit(); 1925 handler.handleSession(&sess, request) catch |session_err| { 1926 // try to send a non-zero exit status before closing 1927 sess.exit(1) catch {}; 1928 return sess.underlyingError(session_err); 1929 }; 1930 if (!sess.closed) try sess.exit(0); 1931 return; 1932 } 1933 }, 1934 1935 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1936 const ch = if (channel) |*c| c else continue; 1937 try handleWindowAdjust(ch, packet); 1938 }, 1939 1940 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1941 const ch = if (channel) |*c| c else continue; 1942 // before shell/exec the client shouldn't be sending data, but 1943 // some clients are chatty; discard and refill window. nothing 1944 // is buffered yet, so the whole window is available to credit. 1945 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1946 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1947 }, 1948 1949 SSH_MSG_CHANNEL_EOF => { 1950 if (channel) |*c| try parseChannelId(packet, c.local_id); 1951 }, 1952 1953 SSH_MSG_CHANNEL_CLOSE => { 1954 if (channel) |*c| { 1955 try parseChannelId(packet, c.local_id); 1956 try sendChannelMessage(conn, c, SSH_MSG_CHANNEL_CLOSE); 1957 drainConnection(conn); 1958 } 1959 return; 1960 }, 1961 1962 // RFC 4252 §5.1: silently ignored once authenticated 1963 SSH_MSG_USERAUTH_REQUEST => {}, 1964 else => try sendUnimplemented(conn), 1965 } 1966 } 1967 } 1968 1969 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1970 // byte SSH_MSG_GLOBAL_REQUEST 1971 // string request_name 1972 // boolean want_reply 1973 // …request-specific data we ignore 1974 var r = std.Io.Reader.fixed(packet[1..]); 1975 _ = try takeString(&r, 256); 1976 const want_reply = (try r.takeByte()) != 0; 1977 if (want_reply) { 1978 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 1979 } 1980 } 1981 1982 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 1983 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 1984 /// return null. 1985 fn handleChannelOpen(conn: *Conn, packet: []const u8, has_channel: bool) !?Channel { 1986 // byte SSH_MSG_CHANNEL_OPEN 1987 // string channel_type 1988 // uint32 sender_channel (peer's id) 1989 // uint32 initial_window 1990 // uint32 max_packet 1991 var r = std.Io.Reader.fixed(packet[1..]); 1992 const ch_type = try takeString(&r, 64); 1993 const remote_id = try r.takeInt(u32, .big); 1994 const initial_window = try r.takeInt(u32, .big); 1995 const max_packet = try r.takeInt(u32, .big); 1996 1997 if (has_channel) { 1998 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1999 return null; 2000 } 2001 2002 if (!std.mem.eql(u8, ch_type, "session")) { 2003 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2004 return null; 2005 } 2006 2007 // a zero max_packet would leave writeBytes looping without progress 2008 if (max_packet == 0) { 2009 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2010 return null; 2011 } 2012 2013 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2014 var reply: [17]u8 = undefined; 2015 reply[0] = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; 2016 std.mem.writeInt(u32, reply[1..5], remote_id, .big); 2017 std.mem.writeInt(u32, reply[5..9], local_id, .big); 2018 std.mem.writeInt(u32, reply[9..13], initial_recv_window, .big); 2019 std.mem.writeInt(u32, reply[13..17], max_packet_size, .big); 2020 try conn.writePacket(&.{&reply}); 2021 2022 return .{ 2023 .local_id = local_id, 2024 .remote_id = remote_id, 2025 .local_window = initial_recv_window, 2026 .remote_window = initial_window, 2027 .max_packet = max_packet, 2028 }; 2029 } 2030 2031 fn sendChannelOpenFailure(conn: *Conn, remote_id: u32, reason: u32, description: []const u8) !void { 2032 const allocator = conn.allocator; 2033 2034 var reply: std.ArrayList(u8) = .empty; 2035 defer reply.deinit(allocator); 2036 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2037 try writeU32(&reply, allocator, remote_id); 2038 try writeU32(&reply, allocator, reason); 2039 try writeStringField(&reply, allocator, description); 2040 try writeStringField(&reply, allocator, ""); // language tag 2041 try conn.writePacket(&.{reply.items}); 2042 } 2043 2044 /// returns the session request if this one triggered it, else null. an exec 2045 /// command borrows from `packet`. 2046 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2047 // byte SSH_MSG_CHANNEL_REQUEST 2048 // uint32 recipient_channel (== our local_id) 2049 // string request_type 2050 // boolean want_reply 2051 // …request-specific data 2052 var r = std.Io.Reader.fixed(packet[1..]); 2053 const recipient_channel = try r.takeInt(u32, .big); 2054 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2055 const req_type = try takeString(&r, 64); 2056 const want_reply = (try r.takeByte()) != 0; 2057 2058 if (std.mem.eql(u8, req_type, "pty-req")) { 2059 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2060 // uint32 height px, string modes 2061 _ = try takeString(&r, 64); 2062 ch.pty = try takePtySize(&r); 2063 try replyChannelRequest(conn, ch, want_reply, true); 2064 return null; 2065 } 2066 2067 if (std.mem.eql(u8, req_type, "env")) { 2068 // string name, string value. the rest are ignored silently. 2069 const name = try takeString(&r, max_packet_len); 2070 const value = try takeString(&r, max_packet_len); 2071 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2072 @memcpy(ch.git_protocol_buf[0..value.len], value); 2073 ch.git_protocol_len = value.len; 2074 } 2075 try replyChannelRequest(conn, ch, want_reply, true); 2076 return null; 2077 } 2078 2079 if (std.mem.eql(u8, req_type, "window-change")) { 2080 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2081 const sz = try takePtySize(&r); 2082 if (ch.pty != null) ch.pty = sz; 2083 // spec: window-change MUST NOT request a reply, but accept either 2084 try replyChannelRequest(conn, ch, want_reply, true); 2085 return null; 2086 } 2087 2088 if (std.mem.eql(u8, req_type, "shell")) { 2089 try replyChannelRequest(conn, ch, want_reply, true); 2090 return .{ .shell = ch.pty }; 2091 } 2092 2093 if (std.mem.eql(u8, req_type, "exec")) { 2094 // capture the command string for the handler to inspect 2095 const cmd = try takeString(&r, 4096); 2096 try replyChannelRequest(conn, ch, want_reply, true); 2097 return .{ .exec = .{ 2098 .command = cmd, 2099 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2100 } }; 2101 } 2102 2103 // unknown request kind — fail it 2104 try replyChannelRequest(conn, ch, want_reply, false); 2105 return null; 2106 } 2107 2108 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2109 if (!want_reply) return; 2110 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2111 } 2112 2113 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2114 var packet: [5]u8 = undefined; 2115 packet[0] = msg_type; 2116 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2117 try conn.writePacket(&.{&packet}); 2118 } 2119 2120 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2121 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2122 // uint32 recipient_channel 2123 // uint32 bytes_to_add 2124 var r = std.Io.Reader.fixed(packet[1..]); 2125 const recipient_channel = try r.takeInt(u32, .big); 2126 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2127 const add = try r.takeInt(u32, .big); 2128 ch.remote_window +|= add; 2129 } 2130 2131 // charge a payload's bytes against the receive window without keeping them. 2132 // the caller credits the window back, choosing the budget that suits it. 2133 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2134 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2135 // uint32 recipient_channel 2136 // [if extended: uint32 type_code] 2137 // string data 2138 const payload = try parseChannelData(packet, extended, ch.local_id); 2139 const data_len: u32 = @intCast(payload.len); 2140 2141 if (data_len > ch.local_window) return error.WindowExceeded; 2142 ch.local_window -= data_len; 2143 } 2144 2145 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2146 if (packet.len < 1) return error.EmptyPacket; 2147 var r = std.Io.Reader.fixed(packet[1..]); 2148 const recipient_channel = try r.takeInt(u32, .big); 2149 if (recipient_channel != expected_channel) return error.UnknownChannel; 2150 if (extended) { 2151 const data_type = try r.takeInt(u32, .big); 2152 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2153 } 2154 const data_len = try r.takeInt(u32, .big); 2155 // catches both data_len > remaining (would otherwise be a bounds-check 2156 // panic on the slice) and trailing junk after the declared payload. 2157 if (data_len != r.buffered().len) return error.InvalidChannelData; 2158 return r.buffered(); 2159 } 2160 2161 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2162 var r = std.Io.Reader.fixed(packet[1..]); 2163 const recipient_channel = try r.takeInt(u32, .big); 2164 if (recipient_channel != expected_channel) return error.UnknownChannel; 2165 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2166 } 2167 2168 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2169 /// of `budget`, the credit we're willing to have outstanding. used both for 2170 /// the pre-session discard path and by SessionCtx after it consumes a 2171 /// CHANNEL_DATA payload. 2172 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2173 if (ch.local_window >= budget / 2) return; 2174 const add = budget - ch.local_window; 2175 ch.local_window += add; 2176 var packet: [9]u8 = undefined; 2177 packet[0] = SSH_MSG_CHANNEL_WINDOW_ADJUST; 2178 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2179 std.mem.writeInt(u32, packet[5..9], add, .big); 2180 try conn.writePacket(&.{&packet}); 2181 } 2182 2183 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2184 var bytes: [4]u8 = undefined; 2185 std.mem.writeInt(u32, &bytes, value, .big); 2186 try buf.appendSlice(allocator, &bytes); 2187 } 2188 2189 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2190 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2191 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2192 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2193 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2194 }) |case| { 2195 var bytes: [8]u8 = undefined; 2196 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2197 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2198 var reader = std.Io.Reader.fixed(&bytes); 2199 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2200 } 2201 } 2202 2203 test "channel close before shell or exec is acknowledged" { 2204 const io = std.testing.io; 2205 const allocator = std.testing.allocator; 2206 const key = [_]u8{0x5a} ** 64; 2207 var encoded: [256]u8 = undefined; 2208 var encoded_writer = std.Io.Writer.fixed(&encoded); 2209 var sender = Cipher.init(&key, 0); 2210 var open: std.ArrayList(u8) = .empty; 2211 defer open.deinit(allocator); 2212 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2213 try writeStringField(&open, allocator, "session"); 2214 try writeU32(&open, allocator, 7); 2215 try writeU32(&open, allocator, 32768); 2216 try writeU32(&open, allocator, 32768); 2217 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2218 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2219 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2220 var output: [256]u8 = undefined; 2221 var writer = std.Io.Writer.fixed(&output); 2222 var idle = IdleState{}; 2223 var conn = Conn{ 2224 .io = io, 2225 .allocator = allocator, 2226 .reader = &reader, 2227 .writer = &writer, 2228 .cs_cipher = Cipher.init(&key, 0), 2229 .sc_cipher = Cipher.init(&key, 0), 2230 .rekey = undefined, 2231 .idle = &idle, 2232 }; 2233 const Handler = struct { 2234 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2235 return error.UnexpectedSession; 2236 } 2237 }; 2238 var handler = Handler{}; 2239 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2240 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2241 var receiver = Cipher.init(&key, 0); 2242 const confirmation = try receiver.readPacket(allocator, &output_reader); 2243 defer allocator.free(confirmation); 2244 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2245 const close = try receiver.readPacket(allocator, &output_reader); 2246 defer allocator.free(close); 2247 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2248 try std.testing.expectEqual(0, output_reader.buffered().len); 2249 } 2250