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