╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1381 allocator: std.mem.Allocator, 1382 session_id: *const [Sha256.digest_length]u8, 1383 user_name: []const u8, 1384 service_name: []const u8, 1385 algo: []const u8, 1386 pubkey_blob: []const u8, 1387 signature_blob: []const u8, 1388 ) !bool { 1389 var signed: std.ArrayList(u8) = .empty; 1390 defer signed.deinit(allocator); 1391 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1392 1393 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1394 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1395 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1396 defer allocator.free(pk_algo); 1397 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1398 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1399 defer allocator.free(raw_pubkey); 1400 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1401 1402 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1403 var sig_reader = std.Io.Reader.fixed(signature_blob); 1404 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1405 defer allocator.free(sig_algo); 1406 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1407 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1408 defer allocator.free(raw_sig); 1409 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1410 1411 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1412 @memcpy(&pubkey_bytes, raw_pubkey); 1413 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1414 @memcpy(&sig_bytes, raw_sig); 1415 1416 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1417 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1418 sig.verify(signed.items, pk) catch return false; 1419 return true; 1420 } 1421 1422 // --------------------------------------------------------------------------- 1423 // connection layer (RFC 4254): channels, requests, data, flow control 1424 // --------------------------------------------------------------------------- 1425 1426 const Channel = struct { 1427 local_id: u32, 1428 remote_id: u32, 1429 local_window: u32, // bytes peer may still send us before we adjust 1430 remote_window: u32, // bytes we may still send to peer before they adjust 1431 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1432 pty: ?PtySize = null, 1433 }; 1434 1435 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1436 1437 fn runChannelLayer( 1438 io: std.Io, 1439 allocator: std.mem.Allocator, 1440 reader: *std.Io.Reader, 1441 writer: *std.Io.Writer, 1442 cs_cipher: *Cipher, 1443 sc_cipher: *Cipher, 1444 fingerprint: *const [fingerprint_len]u8, 1445 handler: anytype, 1446 ) !void { 1447 var channel: ?Channel = null; 1448 var pending_exec: ?[]u8 = null; 1449 defer if (pending_exec) |s| allocator.free(s); 1450 1451 while (true) { 1452 const packet = try cs_cipher.readPacket(allocator, reader); 1453 defer allocator.free(packet); 1454 if (packet.len < 1) return error.EmptyPacket; 1455 const msg_type = packet[0]; 1456 1457 switch (msg_type) { 1458 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1459 1460 SSH_MSG_KEXINIT => { 1461 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1462 return error.RekeyUnsupported; 1463 }, 1464 1465 SSH_MSG_CHANNEL_OPEN => { 1466 if (channel != null) { 1467 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1468 continue; 1469 } 1470 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1471 }, 1472 1473 SSH_MSG_CHANNEL_REQUEST => { 1474 const ch = if (channel) |*c| c else continue; 1475 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1476 if (start_request) |req_kind| { 1477 const request: Request = switch (req_kind) { 1478 .shell => .{ .shell = ch.pty }, 1479 .exec => .{ .exec = pending_exec.? }, 1480 }; 1481 var sess = SessionCtx{ 1482 .io = io, 1483 .allocator = allocator, 1484 .reader = reader, 1485 .writer = writer, 1486 .cs_cipher = cs_cipher, 1487 .sc_cipher = sc_cipher, 1488 .channel = ch, 1489 .fingerprint = fingerprint.*, 1490 }; 1491 defer sess.deinit(); 1492 handler.handleSession(&sess, request) catch |session_err| { 1493 // try to send a non-zero exit status before closing 1494 sess.exit(1) catch {}; 1495 return session_err; 1496 }; 1497 if (!sess.closed) try sess.exit(0); 1498 return; 1499 } 1500 }, 1501 1502 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1503 const ch = if (channel) |*c| c else continue; 1504 try handleWindowAdjust(ch, packet); 1505 }, 1506 1507 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1508 const ch = if (channel) |*c| c else continue; 1509 // before shell/exec the client shouldn't be sending data, but 1510 // some clients are chatty; discard and refill window. 1511 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1512 }, 1513 1514 SSH_MSG_CHANNEL_EOF => { 1515 if (channel) |*c| try parseChannelId(packet, c.local_id); 1516 }, 1517 1518 SSH_MSG_CHANNEL_CLOSE => { 1519 if (channel) |*c| try parseChannelId(packet, c.local_id); 1520 return; 1521 }, 1522 1523 else => {}, // ignore unknown messages 1524 } 1525 } 1526 } 1527 1528 fn handleGlobalRequest( 1529 io: std.Io, 1530 allocator: std.mem.Allocator, 1531 sc_cipher: *Cipher, 1532 writer: *std.Io.Writer, 1533 packet: []const u8, 1534 ) !void { 1535 // byte SSH_MSG_GLOBAL_REQUEST 1536 // string request_name 1537 // boolean want_reply 1538 // …request-specific data we ignore 1539 var r = std.Io.Reader.fixed(packet[1..]); 1540 const name = try takeStringField(allocator, &r, 256); 1541 defer allocator.free(name); 1542 const want_reply = (try r.takeByte()) != 0; 1543 if (want_reply) { 1544 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1545 } 1546 } 1547 1548 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1549 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1550 /// return null. 1551 fn handleChannelOpen( 1552 io: std.Io, 1553 allocator: std.mem.Allocator, 1554 sc_cipher: *Cipher, 1555 writer: *std.Io.Writer, 1556 packet: []const u8, 1557 ) !?Channel { 1558 // byte SSH_MSG_CHANNEL_OPEN 1559 // string channel_type 1560 // uint32 sender_channel (peer's id) 1561 // uint32 initial_window 1562 // uint32 max_packet 1563 var r = std.Io.Reader.fixed(packet[1..]); 1564 const ch_type = try takeStringField(allocator, &r, 64); 1565 defer allocator.free(ch_type); 1566 const remote_id = try r.takeInt(u32, .big); 1567 const initial_window = try r.takeInt(u32, .big); 1568 const max_packet = try r.takeInt(u32, .big); 1569 1570 if (!std.mem.eql(u8, ch_type, "session")) { 1571 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1572 return null; 1573 } 1574 1575 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1576 var reply: std.ArrayList(u8) = .empty; 1577 defer reply.deinit(allocator); 1578 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1579 try writeU32(&reply, allocator, remote_id); 1580 try writeU32(&reply, allocator, local_id); 1581 try writeU32(&reply, allocator, initial_recv_window); 1582 try writeU32(&reply, allocator, max_packet_size); 1583 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1584 1585 return .{ 1586 .local_id = local_id, 1587 .remote_id = remote_id, 1588 .local_window = initial_recv_window, 1589 .remote_window = initial_window, 1590 .max_packet = max_packet, 1591 }; 1592 } 1593 1594 fn sendChannelOpenFailure( 1595 io: std.Io, 1596 allocator: std.mem.Allocator, 1597 sc_cipher: *Cipher, 1598 writer: *std.Io.Writer, 1599 open_packet: []const u8, 1600 reason: u32, 1601 description: []const u8, 1602 ) !void { 1603 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1604 // address the failure to the correct id 1605 var r = std.Io.Reader.fixed(open_packet[1..]); 1606 const ch_type_len = try r.takeInt(u32, .big); 1607 try r.discardAll(ch_type_len); 1608 const remote_id = try r.takeInt(u32, .big); 1609 1610 var reply: std.ArrayList(u8) = .empty; 1611 defer reply.deinit(allocator); 1612 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1613 try writeU32(&reply, allocator, remote_id); 1614 try writeU32(&reply, allocator, reason); 1615 try writeStringField(&reply, allocator, description); 1616 try writeStringField(&reply, allocator, ""); // language tag 1617 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1618 } 1619 1620 const RequestKind = enum { shell, exec }; 1621 1622 /// Returns the kind of session request if this triggered one, else null. 1623 fn handleChannelRequest( 1624 io: std.Io, 1625 allocator: std.mem.Allocator, 1626 sc_cipher: *Cipher, 1627 writer: *std.Io.Writer, 1628 ch: *Channel, 1629 packet: []const u8, 1630 pending_exec: *?[]u8, 1631 ) !?RequestKind { 1632 // byte SSH_MSG_CHANNEL_REQUEST 1633 // uint32 recipient_channel (== our local_id) 1634 // string request_type 1635 // boolean want_reply 1636 // …request-specific data 1637 var r = std.Io.Reader.fixed(packet[1..]); 1638 const recipient_channel = try r.takeInt(u32, .big); 1639 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1640 const req_type = try takeStringField(allocator, &r, 64); 1641 defer allocator.free(req_type); 1642 const want_reply = (try r.takeByte()) != 0; 1643 1644 if (std.mem.eql(u8, req_type, "pty-req")) { 1645 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1646 // uint32 height px, string modes 1647 const term = try takeStringField(allocator, &r, 64); 1648 defer allocator.free(term); 1649 const width = try r.takeInt(u32, .big); 1650 const height = try r.takeInt(u32, .big); 1651 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1652 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1653 return null; 1654 } 1655 1656 if (std.mem.eql(u8, req_type, "env")) { 1657 // ignore environment variables silently (we don't pass them anywhere) 1658 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1659 return null; 1660 } 1661 1662 if (std.mem.eql(u8, req_type, "window-change")) { 1663 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1664 const width = try r.takeInt(u32, .big); 1665 const height = try r.takeInt(u32, .big); 1666 if (ch.pty != null) { 1667 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1668 } 1669 // spec: window-change MUST NOT request a reply, but accept either 1670 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1671 return null; 1672 } 1673 1674 if (std.mem.eql(u8, req_type, "shell")) { 1675 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1676 return .shell; 1677 } 1678 1679 if (std.mem.eql(u8, req_type, "exec")) { 1680 // capture the command string for the handler to inspect 1681 const cmd = try takeStringField(allocator, &r, 4096); 1682 if (pending_exec.*) |old| allocator.free(old); 1683 pending_exec.* = cmd; 1684 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1685 return .exec; 1686 } 1687 1688 // unknown request kind — fail it 1689 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1690 return null; 1691 } 1692 1693 fn replyChannelRequest( 1694 io: std.Io, 1695 allocator: std.mem.Allocator, 1696 sc_cipher: *Cipher, 1697 writer: *std.Io.Writer, 1698 ch: *Channel, 1699 want_reply: bool, 1700 success: bool, 1701 ) !void { 1702 if (!want_reply) return; 1703 var reply: std.ArrayList(u8) = .empty; 1704 defer reply.deinit(allocator); 1705 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1706 try writeU32(&reply, allocator, ch.remote_id); 1707 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1708 } 1709 1710 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1711 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1712 // uint32 recipient_channel 1713 // uint32 bytes_to_add 1714 var r = std.Io.Reader.fixed(packet[1..]); 1715 const recipient_channel = try r.takeInt(u32, .big); 1716 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1717 const add = try r.takeInt(u32, .big); 1718 ch.remote_window +|= add; 1719 } 1720 1721 fn discardChannelData( 1722 io: std.Io, 1723 allocator: std.mem.Allocator, 1724 sc_cipher: *Cipher, 1725 writer: *std.Io.Writer, 1726 ch: *Channel, 1727 packet: []const u8, 1728 extended: bool, 1729 ) !void { 1730 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1731 // uint32 recipient_channel 1732 // [if extended: uint32 type_code] 1733 // string data 1734 const payload = try parseChannelData(packet, extended, ch.local_id); 1735 const data_len: u32 = @intCast(payload.len); 1736 1737 if (data_len > ch.local_window) return error.WindowExceeded; 1738 ch.local_window -= data_len; 1739 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1740 } 1741 1742 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1743 if (packet.len < 1) return error.EmptyPacket; 1744 var r = std.Io.Reader.fixed(packet[1..]); 1745 const recipient_channel = try r.takeInt(u32, .big); 1746 if (recipient_channel != expected_channel) return error.UnknownChannel; 1747 if (extended) { 1748 const data_type = try r.takeInt(u32, .big); 1749 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1750 } 1751 const data_len = try r.takeInt(u32, .big); 1752 // catches both data_len > remaining (would otherwise be a bounds-check 1753 // panic on the slice) and trailing junk after the declared payload. 1754 if (data_len != r.buffered().len) return error.InvalidChannelData; 1755 return r.buffered(); 1756 } 1757 1758 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1759 if (packet.len < 1) return error.EmptyPacket; 1760 var r = std.Io.Reader.fixed(packet[1..]); 1761 const recipient_channel = try r.takeInt(u32, .big); 1762 if (recipient_channel != expected_channel) return error.UnknownChannel; 1763 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1764 } 1765 1766 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1767 /// of the initial value. Used both for the pre-session discard path and by 1768 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1769 fn maybeRefillRecvWindow( 1770 io: std.Io, 1771 allocator: std.mem.Allocator, 1772 sc_cipher: *Cipher, 1773 writer: *std.Io.Writer, 1774 ch: *Channel, 1775 ) !void { 1776 if (ch.local_window >= initial_recv_window / 2) return; 1777 const add = initial_recv_window - ch.local_window; 1778 ch.local_window += add; 1779 var adj: std.ArrayList(u8) = .empty; 1780 defer adj.deinit(allocator); 1781 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1782 try writeU32(&adj, allocator, ch.remote_id); 1783 try writeU32(&adj, allocator, add); 1784 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1785 } 1786 1787 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1788 var bytes: [4]u8 = undefined; 1789 std.mem.writeInt(u32, &bytes, value, .big); 1790 try buf.appendSlice(allocator, &bytes); 1791 } 1792