╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
752 errdefer allocator.free(host_key_algos); 753 const cs_cipher = try takeStringField(allocator, &reader, max_name_list_len); 754 errdefer allocator.free(cs_cipher); 755 const sc_cipher = try takeStringField(allocator, &reader, max_name_list_len); 756 errdefer allocator.free(sc_cipher); 757 758 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 759 for (0..6) |_| { 760 const len = try reader.takeInt(u32, .big); 761 if (len > max_name_list_len) return error.FieldTooLarge; 762 try reader.discardAll(len); 763 } 764 _ = try reader.takeByte(); // first_kex_packet_follows 765 _ = try reader.takeInt(u32, .big); // reserved 766 767 return .{ 768 .kex_algos = kex_algos, 769 .host_key_algos = host_key_algos, 770 .cs_cipher = cs_cipher, 771 .sc_cipher = sc_cipher, 772 }; 773 } 774 775 // --------------------------------------------------------------------------- 776 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 777 // --------------------------------------------------------------------------- 778 779 const KexResult = struct { 780 cs_key: [64]u8, // client → server cipher key material (K_2 || K_1) 781 sc_key: [64]u8, // server → client cipher key material 782 session_id: [Sha256.digest_length]u8, 783 }; 784 785 fn runKex( 786 io: std.Io, 787 allocator: std.mem.Allocator, 788 reader: *std.Io.Reader, 789 writer: *std.Io.Writer, 790 host_key: *const HostKey, 791 client_version: []const u8, 792 ) !KexResult { 793 // exchange KEXINITs 794 const server_kex_init = try buildServerKexInit(io, allocator); 795 defer allocator.free(server_kex_init); 796 try writePlainPacket(io, writer, server_kex_init); 797 798 const client_kex_init = try readPlainPacket(allocator, reader); 799 defer allocator.free(client_kex_init); 800 801 var parsed = try parseClientKexInit(allocator, client_kex_init); 802 defer parsed.deinit(allocator); 803 804 if (!nameListContainsAny(parsed.kex_algos, &our_kex_algos)) return error.NoCommonKexAlgorithm; 805 if (!nameListContainsAny(parsed.host_key_algos, &our_host_key_algos)) return error.NoCommonHostKeyAlgorithm; 806 if (!nameListContainsAny(parsed.cs_cipher, &our_ciphers)) return error.NoCommonCipher; 807 if (!nameListContainsAny(parsed.sc_cipher, &our_ciphers)) return error.NoCommonCipher; 808 809 // receive KEX_ECDH_INIT — client's ephemeral curve25519 pubkey 810 const ecdh_init = try readPlainPacket(allocator, reader); 811 defer allocator.free(ecdh_init); 812 if (ecdh_init.len < 1 or ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 813 814 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 815 const client_ephemeral_alloc = try takeStringField(allocator, &ecdh_init_reader, X25519.public_length); 816 defer allocator.free(client_ephemeral_alloc); 817 if (client_ephemeral_alloc.len != X25519.public_length) return error.InvalidEphemeralKey; 818 var client_ephemeral: [X25519.public_length]u8 = undefined; 819 @memcpy(&client_ephemeral, client_ephemeral_alloc); 820 821 // our ephemeral keypair + shared secret 822 const server_ephemeral_kp = X25519.KeyPair.generate(io); 823 const shared_secret = try X25519.scalarmult(server_ephemeral_kp.secret_key, client_ephemeral); 824 825 // build host key blob (K_S) 826 var host_key_blob: std.ArrayList(u8) = .empty; 827 defer host_key_blob.deinit(allocator); 828 try host_key.appendPublicBlob(&host_key_blob, allocator); 829 830 // build exchange hash input and compute H 831 const exchange_hash = try computeExchangeHash( 832 allocator, 833 client_version, 834 server_version, 835 client_kex_init, 836 server_kex_init, 837 host_key_blob.items, 838 &client_ephemeral, 839 &server_ephemeral_kp.public_key, 840 &shared_secret, 841 ); 842 843 // sign H with the host key, format as ssh signature blob 844 var signature_blob: std.ArrayList(u8) = .empty; 845 defer signature_blob.deinit(allocator); 846 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 847 848 // build & send KEX_ECDH_REPLY 849 var reply: std.ArrayList(u8) = .empty; 850 defer reply.deinit(allocator); 851 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 852 try writeStringField(&reply, allocator, host_key_blob.items); 853 try writeStringField(&reply, allocator, &server_ephemeral_kp.public_key); 854 try writeStringField(&reply, allocator, signature_blob.items); 855 try writePlainPacket(io, writer, reply.items); 856 857 // NEWKEYS — both sides switch to encrypted mode after this is sent and 858 // the peer's NEWKEYS is received. 859 try writePlainPacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 860 861 const peer_newkeys = try readPlainPacket(allocator, reader); 862 defer allocator.free(peer_newkeys); 863 if (peer_newkeys.len < 1 or peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 864 865 // derive session keys per RFC 4253 §7.2. session_id == H for the first 866 // KEX. K is encoded as mpint in each derivation input. only the encrypt 867 // keys are needed for chacha20-poly1305 (no separate MAC/IV). 868 var keys: SessionKeys = undefined; 869 try deriveSessionKeys(allocator, &shared_secret, &exchange_hash, &exchange_hash, &keys); 870 871 return .{ 872 .cs_key = keys.cs_enc, 873 .sc_key = keys.sc_enc, 874 .session_id = exchange_hash, 875 }; 876 } 877 878 // --------------------------------------------------------------------------- 879 // exchange hash (RFC 4253 §8, RFC 5656 §4) 880 // --------------------------------------------------------------------------- 881 882 fn computeExchangeHash( 883 allocator: std.mem.Allocator, 884 client_version: []const u8, 885 server_version_str: []const u8, 886 client_kex_init: []const u8, 887 server_kex_init: []const u8, 888 host_key_blob: []const u8, 889 client_ephemeral: []const u8, 890 server_ephemeral: []const u8, 891 shared_secret: []const u8, 892 ) ![Sha256.digest_length]u8 { 893 var buf: std.ArrayList(u8) = .empty; 894 defer buf.deinit(allocator); 895 896 try writeStringField(&buf, allocator, client_version); 897 try writeStringField(&buf, allocator, server_version_str); 898 try writeStringField(&buf, allocator, client_kex_init); 899 try writeStringField(&buf, allocator, server_kex_init); 900 try writeStringField(&buf, allocator, host_key_blob); 901 try writeStringField(&buf, allocator, client_ephemeral); 902 try writeStringField(&buf, allocator, server_ephemeral); 903 try writeMpint(&buf, allocator, shared_secret); 904 905 var hasher = Sha256.init(.{}); 906 hasher.update(buf.items); 907 return hasher.finalResult(); 908 } 909 910 // --------------------------------------------------------------------------- 911 // key derivation (RFC 4253 §7.2) 912 // --------------------------------------------------------------------------- 913 914 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 915 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 916 // blocks chained per RFC 4253. 917 const SessionKeys = struct { 918 cs_iv: [16]u8, 919 sc_iv: [16]u8, 920 cs_enc: [64]u8, 921 sc_enc: [64]u8, 922 }; 923 924 fn deriveSessionKeys( 925 allocator: std.mem.Allocator, 926 shared_secret: []const u8, 927 exchange_hash: []const u8, 928 session_id: []const u8, 929 out: *SessionKeys, 930 ) !void { 931 // pre-build the K || H prefix once; reused for every derivation 932 var prefix: std.ArrayList(u8) = .empty; 933 defer prefix.deinit(allocator); 934 try writeMpint(&prefix, allocator, shared_secret); 935 try prefix.appendSlice(allocator, exchange_hash); 936 937 try deriveKey(allocator, prefix.items, 'A', session_id, &out.cs_iv); 938 try deriveKey(allocator, prefix.items, 'B', session_id, &out.sc_iv); 939 try deriveKey(allocator, prefix.items, 'C', session_id, &out.cs_enc); 940 try deriveKey(allocator, prefix.items, 'D', session_id, &out.sc_enc); 941 } 942 943 fn deriveKey( 944 allocator: std.mem.Allocator, 945 prefix: []const u8, // K || H, already encoded 946 letter: u8, 947 session_id: []const u8, 948 out: []u8, 949 ) !void { 950 // first block: HASH(K || H || letter || session_id) 951 var first_block: [Sha256.digest_length]u8 = undefined; 952 { 953 var hasher = Sha256.init(.{}); 954 hasher.update(prefix); 955 hasher.update(&[_]u8{letter}); 956 hasher.update(session_id); 957 first_block = hasher.finalResult(); 958 } 959 const first_copy = @min(out.len, first_block.len); 960 @memcpy(out[0..first_copy], first_block[0..first_copy]); 961 962 // chain additional blocks if requested length exceeds one hash: 963 // K_{n+1} = HASH(K || H || K_1 || K_2 || … || K_n) 964 var chained: std.ArrayList(u8) = .empty; 965 defer chained.deinit(allocator); 966 try chained.appendSlice(allocator, first_block[0..]); 967 968 var produced: usize = first_copy; 969 while (produced < out.len) { 970 var hasher = Sha256.init(.{}); 971 hasher.update(prefix); 972 hasher.update(chained.items); 973 const block = hasher.finalResult(); 974 const copy_len = @min(out.len - produced, block.len); 975 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 976 produced += copy_len; 977 try chained.appendSlice(allocator, block[0..]); 978 } 979 } 980 981 // --------------------------------------------------------------------------- 982 // chacha20-poly1305@openssh.com packet codec 983 // --------------------------------------------------------------------------- 984 // 985 // per openssh's PROTOCOL.chacha20poly1305: 986 // K_2 = first 32 bytes of key material — encrypts the packet body 987 // K_1 = next 32 bytes — encrypts the 4-byte length field 988 // nonce = 64-bit big-endian sequence number 989 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 990 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 991 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 992 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 993 // 994 // padding is computed on the body alone (padding_length byte + payload + 995 // padding) — the 4-byte length field is excluded from alignment. body must 996 // be a multiple of 8 bytes; minimum padding 4 bytes. 997 998 const Cipher = struct { 999 main_key: [32]u8, // K_2 1000 header_key: [32]u8, // K_1 1001 seq: u64, 1002 1003 fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1004 return .{ 1005 .main_key = key_material[0..32].*, 1006 .header_key = key_material[32..64].*, 1007 .seq = initial_seq, 1008 }; 1009 } 1010 1011 fn makeNonce(seq: u64) [8]u8 { 1012 var nonce: [8]u8 = undefined; 1013 std.mem.writeInt(u64, &nonce, seq, .big); 1014 return nonce; 1015 } 1016 1017 fn writePacket( 1018 self: *Cipher, 1019 io: std.Io, 1020 allocator: std.mem.Allocator, 1021 writer: *std.Io.Writer, 1022 payload: []const u8, 1023 ) !void { 1024 const block: usize = 8; 1025 const initial_pad = block - ((1 + payload.len) % block); 1026 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1027 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1028 1029 const nonce = makeNonce(self.seq); 1030 1031 // plaintext body = padding_length || payload || random padding 1032 const body = try allocator.alloc(u8, body_len); 1033 defer allocator.free(body); 1034 body[0] = padding_len; 1035 @memcpy(body[1 .. 1 + payload.len], payload); 1036 io.random(body[1 + payload.len ..]); 1037 1038 // encrypt body in place with counter=1 1039 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1040 1041 // encrypt length field with header key, counter=0 1042 var enc_length: [4]u8 = undefined; 1043 var length_plain: [4]u8 = undefined; 1044 std.mem.writeInt(u32, &length_plain, body_len, .big); 1045 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1046 1047 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1048 var poly_key: [Poly1305.key_length]u8 = undefined; 1049 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1050 1051 // mac over encrypted_length || encrypted_body 1052 const mac_input = try allocator.alloc(u8, 4 + body_len); 1053 defer allocator.free(mac_input); 1054 @memcpy(mac_input[0..4], &enc_length); 1055 @memcpy(mac_input[4..], body); 1056 var tag: [Poly1305.mac_length]u8 = undefined; 1057 Poly1305.create(&tag, mac_input, &poly_key); 1058 1059 try writer.writeAll(&enc_length); 1060 try writer.writeAll(body); 1061 try writer.writeAll(&tag); 1062 try writer.flush(); 1063 1064 self.seq += 1; 1065 } 1066 1067 fn readPacket( 1068 self: *Cipher, 1069 allocator: std.mem.Allocator, 1070 reader: *std.Io.Reader, 1071 ) ![]u8 { 1072 const nonce = makeNonce(self.seq); 1073 1074 var enc_length: [4]u8 = undefined; 1075 try reader.readSliceAll(&enc_length); 1076 1077 var length_plain: [4]u8 = undefined; 1078 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1079 const body_len = std.mem.readInt(u32, &length_plain, .big); 1080 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1081 1082 const enc_body = try allocator.alloc(u8, body_len); 1083 defer allocator.free(enc_body); 1084 try reader.readSliceAll(enc_body); 1085 1086 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1087 try reader.readSliceAll(&tag_recv); 1088 1089 var poly_key: [Poly1305.key_length]u8 = undefined; 1090 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1091 1092 const mac_input = try allocator.alloc(u8, 4 + body_len); 1093 defer allocator.free(mac_input); 1094 @memcpy(mac_input[0..4], &enc_length); 1095 @memcpy(mac_input[4..], enc_body); 1096 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1097 Poly1305.create(&tag_computed, mac_input, &poly_key); 1098 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1099 return error.MacVerificationFailed; 1100 } 1101 1102 // decrypt body in place into a separate buffer (caller owns) 1103 const body = try allocator.alloc(u8, body_len); 1104 errdefer allocator.free(body); 1105 ChaCha20.xor(body, enc_body, 1, self.main_key, nonce); 1106 1107 const padding_len = body[0]; 1108 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1109 const payload_len = body_len - 1 - @as(u32, padding_len); 1110 1111 const payload = try allocator.dupe(u8, body[1 .. 1 + payload_len]); 1112 allocator.free(body); 1113 1114 self.seq += 1; 1115 return payload; 1116 } 1117 }; 1118 1119 // --------------------------------------------------------------------------- 1120 // post-KEX: service request + user authentication (RFC 4252) 1121 // --------------------------------------------------------------------------- 1122 1123 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1124 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1125 /// `Offering public key: … SHA256:…`. 1126 pub const fingerprint_len = 50; 1127 1128 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1129 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1130 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1131 var digest: [Sha256.digest_length]u8 = undefined; 1132 Sha256.hash(pubkey_blob, &digest, .{}); 1133 1134 var out: [fingerprint_len]u8 = undefined; 1135 @memcpy(out[0..7], "SHA256:"); 1136 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1137 std.debug.assert(encoded.len == fingerprint_len - 7); 1138 return out; 1139 } 1140 1141 fn runAuth( 1142 io: std.Io, 1143 allocator: std.mem.Allocator, 1144 reader: *std.Io.Reader, 1145 writer: *std.Io.Writer, 1146 cs_cipher: *Cipher, 1147 sc_cipher: *Cipher, 1148 session_id: *const [Sha256.digest_length]u8, 1149 ) ![fingerprint_len]u8 { 1150 // step 1: service request for ssh-userauth → service accept 1151 { 1152 const req = try cs_cipher.readPacket(allocator, reader); 1153 defer allocator.free(req); 1154 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1155 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1156 return error.RekeyUnsupported; 1157 } 1158 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1159 1160 var req_reader = std.Io.Reader.fixed(req[1..]); 1161 const service = try takeStringField(allocator, &req_reader, 64); 1162 defer allocator.free(service); 1163 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1164 1165 var accept: std.ArrayList(u8) = .empty; 1166 defer accept.deinit(allocator); 1167 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1168 try writeStringField(&accept, allocator, "ssh-userauth"); 1169 try sc_cipher.writePacket(io, allocator, writer, accept.items); 1170 } 1171 1172 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1173 // signature verifies against the offered pubkey. 1174 var auth_attempts: u32 = 0; 1175 while (true) { 1176 const req = try cs_cipher.readPacket(allocator, reader); 1177 defer allocator.free(req); 1178 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1179 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1180 return error.RekeyUnsupported; 1181 } 1182 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1183 1184 var req_reader = std.Io.Reader.fixed(req[1..]); 1185 const user_name = try takeStringField(allocator, &req_reader, 256); 1186 defer allocator.free(user_name); 1187 const service_name = try takeStringField(allocator, &req_reader, 64); 1188 defer allocator.free(service_name); 1189 const method = try takeStringField(allocator, &req_reader, 64); 1190 defer allocator.free(method); 1191 1192 if (!std.mem.eql(u8, method, "publickey")) { 1193 auth_attempts += 1; 1194 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1195 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1196 continue; 1197 } 1198 1199 const has_signature = (try req_reader.takeByte()) != 0; 1200 const algo = try takeStringField(allocator, &req_reader, 64); 1201 defer allocator.free(algo); 1202 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1203 defer allocator.free(pubkey_blob); 1204 1205 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1206 auth_attempts += 1; 1207 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1208 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1209 continue; 1210 } 1211 1212 if (!has_signature) { 1213 // probe — tell the client this key is acceptable so it'll send 1214 // the signed version next. 1215 var pk_ok: std.ArrayList(u8) = .empty; 1216 defer pk_ok.deinit(allocator); 1217 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1218 try writeStringField(&pk_ok, allocator, algo); 1219 try writeStringField(&pk_ok, allocator, pubkey_blob); 1220 try sc_cipher.writePacket(io, allocator, writer, pk_ok.items); 1221 continue; 1222 } 1223 1224 // has signature — verify it 1225 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1226 defer allocator.free(signature_blob); 1227 1228 const ok = verifyUserauthSignature( 1229 allocator, 1230 session_id, 1231 user_name, 1232 service_name, 1233 algo, 1234 pubkey_blob, 1235 signature_blob, 1236 ) catch false; 1237 1238 if (!ok) { 1239 auth_attempts += 1; 1240 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1241 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1242 continue; 1243 } 1244 1245 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1246 return formatFingerprint(pubkey_blob); 1247 } 1248 } 1249 1250 fn sendUserauthFailure( 1251 io: std.Io, 1252 allocator: std.mem.Allocator, 1253 sc_cipher: *Cipher, 1254 writer: *std.Io.Writer, 1255 ) !void { 1256 var buf: std.ArrayList(u8) = .empty; 1257 defer buf.deinit(allocator); 1258 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1259 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1260 try buf.append(allocator, 0); // partial_success = false 1261 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1262 } 1263 1264 fn sendDisconnect( 1265 io: std.Io, 1266 allocator: std.mem.Allocator, 1267 sc_cipher: *Cipher, 1268 writer: *std.Io.Writer, 1269 description: []const u8, 1270 ) !void { 1271 var buf: std.ArrayList(u8) = .empty; 1272 defer buf.deinit(allocator); 1273 try buf.append(allocator, SSH_MSG_DISCONNECT); 1274 try writeU32(&buf, allocator, SSH_DISCONNECT_PROTOCOL_ERROR); 1275 try writeStringField(&buf, allocator, description); 1276 try writeStringField(&buf, allocator, ""); 1277 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1278 } 1279 1280 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1281 // verify the supplied signature against them. 1282 fn verifyUserauthSignature( 1283 allocator: std.mem.Allocator, 1284 session_id: *const [Sha256.digest_length]u8, 1285 user_name: []const u8, 1286 service_name: []const u8, 1287 algo: []const u8, 1288 pubkey_blob: []const u8, 1289 signature_blob: []const u8, 1290 ) !bool { 1291 // signed data: 1292 // string session_id 1293 // byte SSH_MSG_USERAUTH_REQUEST 1294 // string user_name 1295 // string service_name 1296 // string "publickey" 1297 // bool TRUE 1298 // string algo 1299 // string pubkey 1300 var signed: std.ArrayList(u8) = .empty; 1301 defer signed.deinit(allocator); 1302 try writeStringField(&signed, allocator, session_id); 1303 try signed.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1304 try writeStringField(&signed, allocator, user_name); 1305 try writeStringField(&signed, allocator, service_name); 1306 try writeStringField(&signed, allocator, "publickey"); 1307 try signed.append(allocator, 1); 1308 try writeStringField(&signed, allocator, algo); 1309 try writeStringField(&signed, allocator, pubkey_blob); 1310 1311 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1312 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1313 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1314 defer allocator.free(pk_algo); 1315 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1316 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1317 defer allocator.free(raw_pubkey); 1318 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1319 1320 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1321 var sig_reader = std.Io.Reader.fixed(signature_blob); 1322 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1323 defer allocator.free(sig_algo); 1324 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1325 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1326 defer allocator.free(raw_sig); 1327 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1328 1329 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1330 @memcpy(&pubkey_bytes, raw_pubkey); 1331 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1332 @memcpy(&sig_bytes, raw_sig); 1333 1334 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1335 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1336 sig.verify(signed.items, pk) catch return false; 1337 return true; 1338 } 1339 1340 // --------------------------------------------------------------------------- 1341 // connection layer (RFC 4254): channels, requests, data, flow control 1342 // --------------------------------------------------------------------------- 1343 1344 const Channel = struct { 1345 local_id: u32, 1346 remote_id: u32, 1347 local_window: u32, // bytes peer may still send us before we adjust 1348 remote_window: u32, // bytes we may still send to peer before they adjust 1349 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1350 eof_received: bool = false, 1351 pty: ?PtySize = null, 1352 }; 1353 1354 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1355 1356 fn runChannelLayer( 1357 io: std.Io, 1358 allocator: std.mem.Allocator, 1359 reader: *std.Io.Reader, 1360 writer: *std.Io.Writer, 1361 cs_cipher: *Cipher, 1362 sc_cipher: *Cipher, 1363 fingerprint: *const [fingerprint_len]u8, 1364 handler: anytype, 1365 ) !void { 1366 var channel: ?Channel = null; 1367 var pending_exec: ?[]u8 = null; 1368 defer if (pending_exec) |s| allocator.free(s); 1369 1370 while (true) { 1371 const packet = try cs_cipher.readPacket(allocator, reader); 1372 defer allocator.free(packet); 1373 if (packet.len < 1) return error.EmptyPacket; 1374 const msg_type = packet[0]; 1375 1376 switch (msg_type) { 1377 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1378 1379 SSH_MSG_KEXINIT => { 1380 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1381 return error.RekeyUnsupported; 1382 }, 1383 1384 SSH_MSG_CHANNEL_OPEN => { 1385 if (channel != null) { 1386 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1387 continue; 1388 } 1389 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1390 }, 1391 1392 SSH_MSG_CHANNEL_REQUEST => { 1393 const ch = if (channel) |*c| c else continue; 1394 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1395 if (start_request) |req_kind| { 1396 const request: Request = switch (req_kind) { 1397 .shell => .{ .shell = ch.pty }, 1398 .exec => .{ .exec = pending_exec.? }, 1399 }; 1400 var sess = SessionCtx{ 1401 .io = io, 1402 .allocator = allocator, 1403 .reader = reader, 1404 .writer = writer, 1405 .cs_cipher = cs_cipher, 1406 .sc_cipher = sc_cipher, 1407 .channel = ch, 1408 .fingerprint = fingerprint.*, 1409 }; 1410 defer sess.deinit(); 1411 handler.handleSession(&sess, request) catch |session_err| { 1412 // try to send a non-zero exit status before closing 1413 sess.exit(1) catch {}; 1414 return session_err; 1415 }; 1416 if (!sess.closed) try sess.exit(0); 1417 return; 1418 } 1419 }, 1420 1421 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1422 const ch = if (channel) |*c| c else continue; 1423 try handleWindowAdjust(ch, packet); 1424 }, 1425 1426 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1427 const ch = if (channel) |*c| c else continue; 1428 // before shell/exec the client shouldn't be sending data, but 1429 // some clients are chatty; discard and refill window. 1430 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1431 }, 1432 1433 SSH_MSG_CHANNEL_EOF => { 1434 if (channel) |*c| { 1435 try parseChannelId(packet, c.local_id); 1436 c.eof_received = true; 1437 } 1438 }, 1439 1440 SSH_MSG_CHANNEL_CLOSE => { 1441 if (channel) |*c| try parseChannelId(packet, c.local_id); 1442 return; 1443 }, 1444 1445 else => {}, // ignore unknown messages 1446 } 1447 } 1448 } 1449 1450 fn handleGlobalRequest( 1451 io: std.Io, 1452 allocator: std.mem.Allocator, 1453 sc_cipher: *Cipher, 1454 writer: *std.Io.Writer, 1455 packet: []const u8, 1456 ) !void { 1457 // byte SSH_MSG_GLOBAL_REQUEST 1458 // string request_name 1459 // boolean want_reply 1460 // …request-specific data we ignore 1461 var r = std.Io.Reader.fixed(packet[1..]); 1462 const name = try takeStringField(allocator, &r, 256); 1463 defer allocator.free(name); 1464 const want_reply = (try r.takeByte()) != 0; 1465 if (want_reply) { 1466 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1467 } 1468 } 1469 1470 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1471 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1472 /// return null. 1473 fn handleChannelOpen( 1474 io: std.Io, 1475 allocator: std.mem.Allocator, 1476 sc_cipher: *Cipher, 1477 writer: *std.Io.Writer, 1478 packet: []const u8, 1479 ) !?Channel { 1480 // byte SSH_MSG_CHANNEL_OPEN 1481 // string channel_type 1482 // uint32 sender_channel (peer's id) 1483 // uint32 initial_window 1484 // uint32 max_packet 1485 var r = std.Io.Reader.fixed(packet[1..]); 1486 const ch_type = try takeStringField(allocator, &r, 64); 1487 defer allocator.free(ch_type); 1488 const remote_id = try r.takeInt(u32, .big); 1489 const initial_window = try r.takeInt(u32, .big); 1490 const max_packet = try r.takeInt(u32, .big); 1491 1492 if (!std.mem.eql(u8, ch_type, "session")) { 1493 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1494 return null; 1495 } 1496 1497 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1498 var reply: std.ArrayList(u8) = .empty; 1499 defer reply.deinit(allocator); 1500 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1501 try writeU32(&reply, allocator, remote_id); 1502 try writeU32(&reply, allocator, local_id); 1503 try writeU32(&reply, allocator, initial_recv_window); 1504 try writeU32(&reply, allocator, max_packet_size); 1505 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1506 1507 return .{ 1508 .local_id = local_id, 1509 .remote_id = remote_id, 1510 .local_window = initial_recv_window, 1511 .remote_window = initial_window, 1512 .max_packet = max_packet, 1513 }; 1514 } 1515 1516 fn sendChannelOpenFailure( 1517 io: std.Io, 1518 allocator: std.mem.Allocator, 1519 sc_cipher: *Cipher, 1520 writer: *std.Io.Writer, 1521 open_packet: []const u8, 1522 reason: u32, 1523 description: []const u8, 1524 ) !void { 1525 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1526 // address the failure to the correct id 1527 var r = std.Io.Reader.fixed(open_packet[1..]); 1528 const ch_type_len = try r.takeInt(u32, .big); 1529 try r.discardAll(ch_type_len); 1530 const remote_id = try r.takeInt(u32, .big); 1531 1532 var reply: std.ArrayList(u8) = .empty; 1533 defer reply.deinit(allocator); 1534 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1535 try writeU32(&reply, allocator, remote_id); 1536 try writeU32(&reply, allocator, reason); 1537 try writeStringField(&reply, allocator, description); 1538 try writeStringField(&reply, allocator, ""); // language tag 1539 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1540 } 1541 1542 const RequestKind = enum { shell, exec }; 1543 1544 /// Returns the kind of session request if this triggered one, else null. 1545 fn handleChannelRequest( 1546 io: std.Io, 1547 allocator: std.mem.Allocator, 1548 sc_cipher: *Cipher, 1549 writer: *std.Io.Writer, 1550 ch: *Channel, 1551 packet: []const u8, 1552 pending_exec: *?[]u8, 1553 ) !?RequestKind { 1554 // byte SSH_MSG_CHANNEL_REQUEST 1555 // uint32 recipient_channel (== our local_id) 1556 // string request_type 1557 // boolean want_reply 1558 // …request-specific data 1559 var r = std.Io.Reader.fixed(packet[1..]); 1560 const recipient_channel = try r.takeInt(u32, .big); 1561 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1562 const req_type = try takeStringField(allocator, &r, 64); 1563 defer allocator.free(req_type); 1564 const want_reply = (try r.takeByte()) != 0; 1565 1566 if (std.mem.eql(u8, req_type, "pty-req")) { 1567 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1568 // uint32 height px, string modes 1569 const term = try takeStringField(allocator, &r, 64); 1570 defer allocator.free(term); 1571 const width = try r.takeInt(u32, .big); 1572 const height = try r.takeInt(u32, .big); 1573 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1574 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1575 return null; 1576 } 1577 1578 if (std.mem.eql(u8, req_type, "env")) { 1579 // ignore environment variables silently (we don't pass them anywhere) 1580 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1581 return null; 1582 } 1583 1584 if (std.mem.eql(u8, req_type, "window-change")) { 1585 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1586 const width = try r.takeInt(u32, .big); 1587 const height = try r.takeInt(u32, .big); 1588 if (ch.pty != null) { 1589 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1590 } 1591 // spec: window-change MUST NOT request a reply, but accept either 1592 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1593 return null; 1594 } 1595 1596 if (std.mem.eql(u8, req_type, "shell")) { 1597 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1598 return .shell; 1599 } 1600 1601 if (std.mem.eql(u8, req_type, "exec")) { 1602 // capture the command string for the handler to inspect 1603 const cmd = try takeStringField(allocator, &r, 4096); 1604 if (pending_exec.*) |old| allocator.free(old); 1605 pending_exec.* = cmd; 1606 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1607 return .exec; 1608 } 1609 1610 // unknown request kind — fail it 1611 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1612 return null; 1613 } 1614 1615 fn replyChannelRequest( 1616 io: std.Io, 1617 allocator: std.mem.Allocator, 1618 sc_cipher: *Cipher, 1619 writer: *std.Io.Writer, 1620 ch: *Channel, 1621 want_reply: bool, 1622 success: bool, 1623 ) !void { 1624 if (!want_reply) return; 1625 var reply: std.ArrayList(u8) = .empty; 1626 defer reply.deinit(allocator); 1627 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1628 try writeU32(&reply, allocator, ch.remote_id); 1629 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1630 } 1631 1632 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1633 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1634 // uint32 recipient_channel 1635 // uint32 bytes_to_add 1636 var r = std.Io.Reader.fixed(packet[1..]); 1637 const recipient_channel = try r.takeInt(u32, .big); 1638 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1639 const add = try r.takeInt(u32, .big); 1640 ch.remote_window +|= add; 1641 } 1642 1643 fn discardChannelData( 1644 io: std.Io, 1645 allocator: std.mem.Allocator, 1646 sc_cipher: *Cipher, 1647 writer: *std.Io.Writer, 1648 ch: *Channel, 1649 packet: []const u8, 1650 extended: bool, 1651 ) !void { 1652 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1653 // uint32 recipient_channel 1654 // [if extended: uint32 type_code] 1655 // string data 1656 const payload = try parseChannelData(packet, extended, ch.local_id); 1657 const data_len: u32 = @intCast(payload.len); 1658 1659 if (data_len > ch.local_window) return error.WindowExceeded; 1660 ch.local_window -= data_len; 1661 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1662 } 1663 1664 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1665 if (packet.len < 1) return error.EmptyPacket; 1666 var r = std.Io.Reader.fixed(packet[1..]); 1667 const recipient_channel = try r.takeInt(u32, .big); 1668 if (recipient_channel != expected_channel) return error.UnknownChannel; 1669 if (extended) { 1670 const data_type = try r.takeInt(u32, .big); 1671 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1672 } 1673 const data_len = try r.takeInt(u32, .big); 1674 // catches both data_len > remaining (would otherwise be a bounds-check 1675 // panic on the slice) and trailing junk after the declared payload. 1676 if (data_len != r.buffered().len) return error.InvalidChannelData; 1677 return r.buffered(); 1678 } 1679 1680 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1681 if (packet.len < 1) return error.EmptyPacket; 1682 var r = std.Io.Reader.fixed(packet[1..]); 1683 const recipient_channel = try r.takeInt(u32, .big); 1684 if (recipient_channel != expected_channel) return error.UnknownChannel; 1685 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1686 } 1687 1688 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1689 /// of the initial value. Used both for the pre-session discard path and by 1690 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1691 fn maybeRefillRecvWindow( 1692 io: std.Io, 1693 allocator: std.mem.Allocator, 1694 sc_cipher: *Cipher, 1695 writer: *std.Io.Writer, 1696 ch: *Channel, 1697 ) !void { 1698 if (ch.local_window >= initial_recv_window / 2) return; 1699 const add = initial_recv_window - ch.local_window; 1700 ch.local_window += add; 1701 var adj: std.ArrayList(u8) = .empty; 1702 defer adj.deinit(allocator); 1703 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1704 try writeU32(&adj, allocator, ch.remote_id); 1705 try writeU32(&adj, allocator, add); 1706 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1707 } 1708 1709 fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1710 var bytes: [4]u8 = undefined; 1711 std.mem.writeInt(u32, &bytes, value, .big); 1712 try buf.appendSlice(allocator, &bytes); 1713 } 1714