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