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