╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1054 var produced: usize = first_copy; 1055 while (produced < out.len) { 1056 var hasher = Sha256.init(.{}); 1057 hasher.update(prefix); 1058 hasher.update(chained.items); 1059 const block = hasher.finalResult(); 1060 const copy_len = @min(out.len - produced, block.len); 1061 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 1062 produced += copy_len; 1063 try chained.appendSlice(allocator, block[0..]); 1064 } 1065 } 1066 1067 // --------------------------------------------------------------------------- 1068 // chacha20-poly1305@openssh.com packet codec 1069 // --------------------------------------------------------------------------- 1070 // 1071 // per openssh's PROTOCOL.chacha20poly1305: 1072 // K_2 = first 32 bytes of key material — encrypts the packet body 1073 // K_1 = next 32 bytes — encrypts the 4-byte length field 1074 // nonce = 64-bit big-endian sequence number 1075 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1076 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1077 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1078 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1079 // 1080 // padding is computed on the body alone (padding_length byte + payload + 1081 // padding) — the 4-byte length field is excluded from alignment. body must 1082 // be a multiple of 8 bytes; minimum padding 4 bytes. 1083 1084 pub const Cipher = struct { 1085 main_key: [32]u8, // K_2 1086 header_key: [32]u8, // K_1 1087 seq: u64, 1088 1089 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1090 return .{ 1091 .main_key = key_material[0..32].*, 1092 .header_key = key_material[32..64].*, 1093 .seq = initial_seq, 1094 }; 1095 } 1096 1097 fn makeNonce(seq: u64) [8]u8 { 1098 var nonce: [8]u8 = undefined; 1099 std.mem.writeInt(u64, &nonce, seq, .big); 1100 return nonce; 1101 } 1102 1103 pub fn writePacket( 1104 self: *Cipher, 1105 io: std.Io, 1106 allocator: std.mem.Allocator, 1107 writer: *std.Io.Writer, 1108 payload: []const u8, 1109 ) !void { 1110 const block: usize = 8; 1111 const initial_pad = block - ((1 + payload.len) % block); 1112 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1113 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1114 1115 const nonce = makeNonce(self.seq); 1116 1117 // plaintext body = padding_length || payload || random padding 1118 const body = try allocator.alloc(u8, body_len); 1119 defer allocator.free(body); 1120 body[0] = padding_len; 1121 @memcpy(body[1 .. 1 + payload.len], payload); 1122 io.random(body[1 + payload.len ..]); 1123 1124 // encrypt body in place with counter=1 1125 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1126 1127 // encrypt length field with header key, counter=0 1128 var enc_length: [4]u8 = undefined; 1129 var length_plain: [4]u8 = undefined; 1130 std.mem.writeInt(u32, &length_plain, body_len, .big); 1131 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1132 1133 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1134 var poly_key: [Poly1305.key_length]u8 = undefined; 1135 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1136 1137 // mac over encrypted_length || encrypted_body 1138 const mac_input = try allocator.alloc(u8, 4 + body_len); 1139 defer allocator.free(mac_input); 1140 @memcpy(mac_input[0..4], &enc_length); 1141 @memcpy(mac_input[4..], body); 1142 var tag: [Poly1305.mac_length]u8 = undefined; 1143 Poly1305.create(&tag, mac_input, &poly_key); 1144 1145 try writer.writeAll(&enc_length); 1146 try writer.writeAll(body); 1147 try writer.writeAll(&tag); 1148 try writer.flush(); 1149 1150 self.seq += 1; 1151 } 1152 1153 pub fn readPacket( 1154 self: *Cipher, 1155 allocator: std.mem.Allocator, 1156 reader: *std.Io.Reader, 1157 ) ![]u8 { 1158 const nonce = makeNonce(self.seq); 1159 1160 var enc_length: [4]u8 = undefined; 1161 try reader.readSliceAll(&enc_length); 1162 1163 var length_plain: [4]u8 = undefined; 1164 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1165 const body_len = std.mem.readInt(u32, &length_plain, .big); 1166 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1167 1168 const enc_body = try allocator.alloc(u8, body_len); 1169 defer allocator.free(enc_body); 1170 try reader.readSliceAll(enc_body); 1171 1172 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1173 try reader.readSliceAll(&tag_recv); 1174 1175 var poly_key: [Poly1305.key_length]u8 = undefined; 1176 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1177 1178 const mac_input = try allocator.alloc(u8, 4 + body_len); 1179 defer allocator.free(mac_input); 1180 @memcpy(mac_input[0..4], &enc_length); 1181 @memcpy(mac_input[4..], enc_body); 1182 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1183 Poly1305.create(&tag_computed, mac_input, &poly_key); 1184 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1185 return error.MacVerificationFailed; 1186 } 1187 1188 // decrypt body in place into a separate buffer (caller owns) 1189 const body = try allocator.alloc(u8, body_len); 1190 errdefer allocator.free(body); 1191 ChaCha20.xor(body, enc_body, 1, self.main_key, nonce); 1192 1193 const padding_len = body[0]; 1194 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1195 const payload_len = body_len - 1 - @as(u32, padding_len); 1196 1197 const payload = try allocator.dupe(u8, body[1 .. 1 + payload_len]); 1198 allocator.free(body); 1199 1200 self.seq += 1; 1201 return payload; 1202 } 1203 }; 1204 1205 // --------------------------------------------------------------------------- 1206 // post-KEX: service request + user authentication (RFC 4252) 1207 // --------------------------------------------------------------------------- 1208 1209 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1210 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1211 /// `Offering public key: … SHA256:…`. 1212 pub const fingerprint_len = 50; 1213 1214 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1215 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1216 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1217 var digest: [Sha256.digest_length]u8 = undefined; 1218 Sha256.hash(pubkey_blob, &digest, .{}); 1219 1220 var out: [fingerprint_len]u8 = undefined; 1221 @memcpy(out[0..7], "SHA256:"); 1222 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1223 std.debug.assert(encoded.len == fingerprint_len - 7); 1224 return out; 1225 } 1226 1227 fn runAuth( 1228 io: std.Io, 1229 allocator: std.mem.Allocator, 1230 reader: *std.Io.Reader, 1231 writer: *std.Io.Writer, 1232 cs_cipher: *Cipher, 1233 sc_cipher: *Cipher, 1234 session_id: *const [Sha256.digest_length]u8, 1235 ) ![fingerprint_len]u8 { 1236 // step 1: service request for ssh-userauth → service accept 1237 { 1238 const req = try cs_cipher.readPacket(allocator, reader); 1239 defer allocator.free(req); 1240 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1241 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1242 return error.RekeyUnsupported; 1243 } 1244 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1245 1246 var req_reader = std.Io.Reader.fixed(req[1..]); 1247 const service = try takeStringField(allocator, &req_reader, 64); 1248 defer allocator.free(service); 1249 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1250 1251 var accept: std.ArrayList(u8) = .empty; 1252 defer accept.deinit(allocator); 1253 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1254 try writeStringField(&accept, allocator, "ssh-userauth"); 1255 try sc_cipher.writePacket(io, allocator, writer, accept.items); 1256 } 1257 1258 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1259 // signature verifies against the offered pubkey. 1260 var auth_attempts: u32 = 0; 1261 while (true) { 1262 const req = try cs_cipher.readPacket(allocator, reader); 1263 defer allocator.free(req); 1264 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1265 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1266 return error.RekeyUnsupported; 1267 } 1268 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1269 1270 var req_reader = std.Io.Reader.fixed(req[1..]); 1271 const user_name = try takeStringField(allocator, &req_reader, 256); 1272 defer allocator.free(user_name); 1273 const service_name = try takeStringField(allocator, &req_reader, 64); 1274 defer allocator.free(service_name); 1275 const method = try takeStringField(allocator, &req_reader, 64); 1276 defer allocator.free(method); 1277 1278 if (!std.mem.eql(u8, method, "publickey")) { 1279 auth_attempts += 1; 1280 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1281 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1282 continue; 1283 } 1284 1285 const has_signature = (try req_reader.takeByte()) != 0; 1286 const algo = try takeStringField(allocator, &req_reader, 64); 1287 defer allocator.free(algo); 1288 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1289 defer allocator.free(pubkey_blob); 1290 1291 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1292 auth_attempts += 1; 1293 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1294 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1295 continue; 1296 } 1297 1298 if (!has_signature) { 1299 // probe — tell the client this key is acceptable so it'll send 1300 // the signed version next. 1301 var pk_ok: std.ArrayList(u8) = .empty; 1302 defer pk_ok.deinit(allocator); 1303 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1304 try writeStringField(&pk_ok, allocator, algo); 1305 try writeStringField(&pk_ok, allocator, pubkey_blob); 1306 try sc_cipher.writePacket(io, allocator, writer, pk_ok.items); 1307 continue; 1308 } 1309 1310 // has signature — verify it 1311 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1312 defer allocator.free(signature_blob); 1313 1314 const ok = verifyUserauthSignature( 1315 allocator, 1316 session_id, 1317 user_name, 1318 service_name, 1319 algo, 1320 pubkey_blob, 1321 signature_blob, 1322 ) catch false; 1323 1324 if (!ok) { 1325 auth_attempts += 1; 1326 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1327 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1328 continue; 1329 } 1330 1331 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1332 return formatFingerprint(pubkey_blob); 1333 } 1334 } 1335 1336 fn sendUserauthFailure( 1337 io: std.Io, 1338 allocator: std.mem.Allocator, 1339 sc_cipher: *Cipher, 1340 writer: *std.Io.Writer, 1341 ) !void { 1342 var buf: std.ArrayList(u8) = .empty; 1343 defer buf.deinit(allocator); 1344 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1345 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1346 try buf.append(allocator, 0); // partial_success = false 1347 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1348 } 1349 1350 fn sendDisconnect( 1351 io: std.Io, 1352 allocator: std.mem.Allocator, 1353 sc_cipher: *Cipher, 1354 writer: *std.Io.Writer, 1355 description: []const u8, 1356 ) !void { 1357 var buf: std.ArrayList(u8) = .empty; 1358 defer buf.deinit(allocator); 1359 try buf.append(allocator, SSH_MSG_DISCONNECT); 1360 try writeU32(&buf, allocator, SSH_DISCONNECT_PROTOCOL_ERROR); 1361 try writeStringField(&buf, allocator, description); 1362 try writeStringField(&buf, allocator, ""); 1363 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1364 } 1365 1366 /// Append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1367 /// Used by the server to recompute the signed input for verification 1368 pub fn appendPublickeySignedData( 1369 buf: *std.ArrayList(u8), 1370 allocator: std.mem.Allocator, 1371 session_id: []const u8, 1372 user_name: []const u8, 1373 service_name: []const u8, 1374 algo: []const u8, 1375 pubkey_blob: []const u8, 1376 ) !void { 1377 try writeStringField(buf, allocator, session_id); 1378 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1379 try writeStringField(buf, allocator, user_name); 1380 try writeStringField(buf, allocator, service_name); 1381 try writeStringField(buf, allocator, "publickey"); 1382 try buf.append(allocator, 1); 1383 try writeStringField(buf, allocator, algo); 1384 try writeStringField(buf, allocator, pubkey_blob); 1385 } 1386 1387 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1388 // verify the supplied signature against them. 1389 fn verifyUserauthSignature( 1390 allocator: std.mem.Allocator, 1391 session_id: *const [Sha256.digest_length]u8, 1392 user_name: []const u8, 1393 service_name: []const u8, 1394 algo: []const u8, 1395 pubkey_blob: []const u8, 1396 signature_blob: []const u8, 1397 ) !bool { 1398 var signed: std.ArrayList(u8) = .empty; 1399 defer signed.deinit(allocator); 1400 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1401 1402 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1403 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1404 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1405 defer allocator.free(pk_algo); 1406 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1407 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1408 defer allocator.free(raw_pubkey); 1409 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1410 1411 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1412 var sig_reader = std.Io.Reader.fixed(signature_blob); 1413 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1414 defer allocator.free(sig_algo); 1415 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1416 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1417 defer allocator.free(raw_sig); 1418 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1419 1420 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1421 @memcpy(&pubkey_bytes, raw_pubkey); 1422 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1423 @memcpy(&sig_bytes, raw_sig); 1424 1425 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1426 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1427 sig.verify(signed.items, pk) catch return false; 1428 return true; 1429 } 1430 1431 // --------------------------------------------------------------------------- 1432 // connection layer (RFC 4254): channels, requests, data, flow control 1433 // --------------------------------------------------------------------------- 1434 1435 const Channel = struct { 1436 local_id: u32, 1437 remote_id: u32, 1438 local_window: u32, // bytes peer may still send us before we adjust 1439 remote_window: u32, // bytes we may still send to peer before they adjust 1440 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1441 eof_received: bool = false, 1442 pty: ?PtySize = null, 1443 }; 1444 1445 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1446 1447 fn runChannelLayer( 1448 io: std.Io, 1449 allocator: std.mem.Allocator, 1450 reader: *std.Io.Reader, 1451 writer: *std.Io.Writer, 1452 cs_cipher: *Cipher, 1453 sc_cipher: *Cipher, 1454 fingerprint: *const [fingerprint_len]u8, 1455 handler: anytype, 1456 ) !void { 1457 var channel: ?Channel = null; 1458 var pending_exec: ?[]u8 = null; 1459 defer if (pending_exec) |s| allocator.free(s); 1460 1461 while (true) { 1462 const packet = try cs_cipher.readPacket(allocator, reader); 1463 defer allocator.free(packet); 1464 if (packet.len < 1) return error.EmptyPacket; 1465 const msg_type = packet[0]; 1466 1467 switch (msg_type) { 1468 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1469 1470 SSH_MSG_KEXINIT => { 1471 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1472 return error.RekeyUnsupported; 1473 }, 1474 1475 SSH_MSG_CHANNEL_OPEN => { 1476 if (channel != null) { 1477 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1478 continue; 1479 } 1480 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1481 }, 1482 1483 SSH_MSG_CHANNEL_REQUEST => { 1484 const ch = if (channel) |*c| c else continue; 1485 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1486 if (start_request) |req_kind| { 1487 const request: Request = switch (req_kind) { 1488 .shell => .{ .shell = ch.pty }, 1489 .exec => .{ .exec = pending_exec.? }, 1490 }; 1491 var sess = SessionCtx{ 1492 .io = io, 1493 .allocator = allocator, 1494 .reader = reader, 1495 .writer = writer, 1496 .cs_cipher = cs_cipher, 1497 .sc_cipher = sc_cipher, 1498 .channel = ch, 1499 .fingerprint = fingerprint.*, 1500 }; 1501 defer sess.deinit(); 1502 handler.handleSession(&sess, request) catch |session_err| { 1503 // try to send a non-zero exit status before closing 1504 sess.exit(1) catch {}; 1505 return session_err; 1506 }; 1507 if (!sess.closed) try sess.exit(0); 1508 return; 1509 } 1510 }, 1511 1512 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1513 const ch = if (channel) |*c| c else continue; 1514 try handleWindowAdjust(ch, packet); 1515 }, 1516 1517 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1518 const ch = if (channel) |*c| c else continue; 1519 // before shell/exec the client shouldn't be sending data, but 1520 // some clients are chatty; discard and refill window. 1521 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1522 }, 1523 1524 SSH_MSG_CHANNEL_EOF => { 1525 if (channel) |*c| { 1526 try parseChannelId(packet, c.local_id); 1527 c.eof_received = true; 1528 } 1529 }, 1530 1531 SSH_MSG_CHANNEL_CLOSE => { 1532 if (channel) |*c| try parseChannelId(packet, c.local_id); 1533 return; 1534 }, 1535 1536 else => {}, // ignore unknown messages 1537 } 1538 } 1539 } 1540 1541 fn handleGlobalRequest( 1542 io: std.Io, 1543 allocator: std.mem.Allocator, 1544 sc_cipher: *Cipher, 1545 writer: *std.Io.Writer, 1546 packet: []const u8, 1547 ) !void { 1548 // byte SSH_MSG_GLOBAL_REQUEST 1549 // string request_name 1550 // boolean want_reply 1551 // …request-specific data we ignore 1552 var r = std.Io.Reader.fixed(packet[1..]); 1553 const name = try takeStringField(allocator, &r, 256); 1554 defer allocator.free(name); 1555 const want_reply = (try r.takeByte()) != 0; 1556 if (want_reply) { 1557 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1558 } 1559 } 1560 1561 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1562 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1563 /// return null. 1564 fn handleChannelOpen( 1565 io: std.Io, 1566 allocator: std.mem.Allocator, 1567 sc_cipher: *Cipher, 1568 writer: *std.Io.Writer, 1569 packet: []const u8, 1570 ) !?Channel { 1571 // byte SSH_MSG_CHANNEL_OPEN 1572 // string channel_type 1573 // uint32 sender_channel (peer's id) 1574 // uint32 initial_window 1575 // uint32 max_packet 1576 var r = std.Io.Reader.fixed(packet[1..]); 1577 const ch_type = try takeStringField(allocator, &r, 64); 1578 defer allocator.free(ch_type); 1579 const remote_id = try r.takeInt(u32, .big); 1580 const initial_window = try r.takeInt(u32, .big); 1581 const max_packet = try r.takeInt(u32, .big); 1582 1583 if (!std.mem.eql(u8, ch_type, "session")) { 1584 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1585 return null; 1586 } 1587 1588 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1589 var reply: std.ArrayList(u8) = .empty; 1590 defer reply.deinit(allocator); 1591 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1592 try writeU32(&reply, allocator, remote_id); 1593 try writeU32(&reply, allocator, local_id); 1594 try writeU32(&reply, allocator, initial_recv_window); 1595 try writeU32(&reply, allocator, max_packet_size); 1596 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1597 1598 return .{ 1599 .local_id = local_id, 1600 .remote_id = remote_id, 1601 .local_window = initial_recv_window, 1602 .remote_window = initial_window, 1603 .max_packet = max_packet, 1604 }; 1605 } 1606 1607 fn sendChannelOpenFailure( 1608 io: std.Io, 1609 allocator: std.mem.Allocator, 1610 sc_cipher: *Cipher, 1611 writer: *std.Io.Writer, 1612 open_packet: []const u8, 1613 reason: u32, 1614 description: []const u8, 1615 ) !void { 1616 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1617 // address the failure to the correct id 1618 var r = std.Io.Reader.fixed(open_packet[1..]); 1619 const ch_type_len = try r.takeInt(u32, .big); 1620 try r.discardAll(ch_type_len); 1621 const remote_id = try r.takeInt(u32, .big); 1622 1623 var reply: std.ArrayList(u8) = .empty; 1624 defer reply.deinit(allocator); 1625 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1626 try writeU32(&reply, allocator, remote_id); 1627 try writeU32(&reply, allocator, reason); 1628 try writeStringField(&reply, allocator, description); 1629 try writeStringField(&reply, allocator, ""); // language tag 1630 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1631 } 1632 1633 const RequestKind = enum { shell, exec }; 1634 1635 /// Returns the kind of session request if this triggered one, else null. 1636 fn handleChannelRequest( 1637 io: std.Io, 1638 allocator: std.mem.Allocator, 1639 sc_cipher: *Cipher, 1640 writer: *std.Io.Writer, 1641 ch: *Channel, 1642 packet: []const u8, 1643 pending_exec: *?[]u8, 1644 ) !?RequestKind { 1645 // byte SSH_MSG_CHANNEL_REQUEST 1646 // uint32 recipient_channel (== our local_id) 1647 // string request_type 1648 // boolean want_reply 1649 // …request-specific data 1650 var r = std.Io.Reader.fixed(packet[1..]); 1651 const recipient_channel = try r.takeInt(u32, .big); 1652 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1653 const req_type = try takeStringField(allocator, &r, 64); 1654 defer allocator.free(req_type); 1655 const want_reply = (try r.takeByte()) != 0; 1656 1657 if (std.mem.eql(u8, req_type, "pty-req")) { 1658 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1659 // uint32 height px, string modes 1660 const term = try takeStringField(allocator, &r, 64); 1661 defer allocator.free(term); 1662 const width = try r.takeInt(u32, .big); 1663 const height = try r.takeInt(u32, .big); 1664 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1665 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1666 return null; 1667 } 1668 1669 if (std.mem.eql(u8, req_type, "env")) { 1670 // ignore environment variables silently (we don't pass them anywhere) 1671 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1672 return null; 1673 } 1674 1675 if (std.mem.eql(u8, req_type, "window-change")) { 1676 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1677 const width = try r.takeInt(u32, .big); 1678 const height = try r.takeInt(u32, .big); 1679 if (ch.pty != null) { 1680 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1681 } 1682 // spec: window-change MUST NOT request a reply, but accept either 1683 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1684 return null; 1685 } 1686 1687 if (std.mem.eql(u8, req_type, "shell")) { 1688 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1689 return .shell; 1690 } 1691 1692 if (std.mem.eql(u8, req_type, "exec")) { 1693 // capture the command string for the handler to inspect 1694 const cmd = try takeStringField(allocator, &r, 4096); 1695 if (pending_exec.*) |old| allocator.free(old); 1696 pending_exec.* = cmd; 1697 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1698 return .exec; 1699 } 1700 1701 // unknown request kind — fail it 1702 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1703 return null; 1704 } 1705 1706 fn replyChannelRequest( 1707 io: std.Io, 1708 allocator: std.mem.Allocator, 1709 sc_cipher: *Cipher, 1710 writer: *std.Io.Writer, 1711 ch: *Channel, 1712 want_reply: bool, 1713 success: bool, 1714 ) !void { 1715 if (!want_reply) return; 1716 var reply: std.ArrayList(u8) = .empty; 1717 defer reply.deinit(allocator); 1718 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1719 try writeU32(&reply, allocator, ch.remote_id); 1720 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1721 } 1722 1723 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1724 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1725 // uint32 recipient_channel 1726 // uint32 bytes_to_add 1727 var r = std.Io.Reader.fixed(packet[1..]); 1728 const recipient_channel = try r.takeInt(u32, .big); 1729 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1730 const add = try r.takeInt(u32, .big); 1731 ch.remote_window +|= add; 1732 } 1733 1734 fn discardChannelData( 1735 io: std.Io, 1736 allocator: std.mem.Allocator, 1737 sc_cipher: *Cipher, 1738 writer: *std.Io.Writer, 1739 ch: *Channel, 1740 packet: []const u8, 1741 extended: bool, 1742 ) !void { 1743 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1744 // uint32 recipient_channel 1745 // [if extended: uint32 type_code] 1746 // string data 1747 const payload = try parseChannelData(packet, extended, ch.local_id); 1748 const data_len: u32 = @intCast(payload.len); 1749 1750 if (data_len > ch.local_window) return error.WindowExceeded; 1751 ch.local_window -= data_len; 1752 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1753 } 1754 1755 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1756 if (packet.len < 1) return error.EmptyPacket; 1757 var r = std.Io.Reader.fixed(packet[1..]); 1758 const recipient_channel = try r.takeInt(u32, .big); 1759 if (recipient_channel != expected_channel) return error.UnknownChannel; 1760 if (extended) { 1761 const data_type = try r.takeInt(u32, .big); 1762 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1763 } 1764 const data_len = try r.takeInt(u32, .big); 1765 // catches both data_len > remaining (would otherwise be a bounds-check 1766 // panic on the slice) and trailing junk after the declared payload. 1767 if (data_len != r.buffered().len) return error.InvalidChannelData; 1768 return r.buffered(); 1769 } 1770 1771 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1772 if (packet.len < 1) return error.EmptyPacket; 1773 var r = std.Io.Reader.fixed(packet[1..]); 1774 const recipient_channel = try r.takeInt(u32, .big); 1775 if (recipient_channel != expected_channel) return error.UnknownChannel; 1776 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1777 } 1778 1779 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1780 /// of the initial value. Used both for the pre-session discard path and by 1781 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1782 fn maybeRefillRecvWindow( 1783 io: std.Io, 1784 allocator: std.mem.Allocator, 1785 sc_cipher: *Cipher, 1786 writer: *std.Io.Writer, 1787 ch: *Channel, 1788 ) !void { 1789 if (ch.local_window >= initial_recv_window / 2) return; 1790 const add = initial_recv_window - ch.local_window; 1791 ch.local_window += add; 1792 var adj: std.ArrayList(u8) = .empty; 1793 defer adj.deinit(allocator); 1794 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1795 try writeU32(&adj, allocator, ch.remote_id); 1796 try writeU32(&adj, allocator, add); 1797 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1798 } 1799 1800 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1801 var bytes: [4]u8 = undefined; 1802 std.mem.writeInt(u32, &bytes, value, .big); 1803 try buf.appendSlice(allocator, &bytes); 1804 } 1805