From 9b0da5ccef50bf5018142dd38deaeaf91fa16429 Mon Sep 17 00:00:00 2001 From: melonedo <44501064+melonedo@users.noreply.github.com> Date: Mon, 15 Jan 2024 22:31:15 +0800 Subject: [PATCH] Fix TLS record overflow by limiting inner record length to 2^14 Per last paragraph of RFC 8446, Section 5.2, the length of the inner content of an encrypted record must not exceed 2^14 + 1, while that of the whole encrypted record must not exceed 2^14 + 256. --- lib/std/crypto/tls.zig | 3 ++- lib/std/crypto/tls/Client.zig | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/std/crypto/tls.zig b/lib/std/crypto/tls.zig index 0713562738..7fff68471c 100644 --- a/lib/std/crypto/tls.zig +++ b/lib/std/crypto/tls.zig @@ -40,7 +40,8 @@ const assert = std.debug.assert; pub const Client = @import("tls/Client.zig"); pub const record_header_len = 5; -pub const max_ciphertext_len = (1 << 14) + 256; +pub const max_cipertext_inner_record_len = 1 << 14; +pub const max_ciphertext_len = max_cipertext_inner_record_len + 256; pub const max_ciphertext_record_len = max_ciphertext_len + record_header_len; pub const hello_retry_request_sequence = [32]u8{ 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, diff --git a/lib/std/crypto/tls/Client.zig b/lib/std/crypto/tls/Client.zig index 214cb3d1a3..abae597ae7 100644 --- a/lib/std/crypto/tls/Client.zig +++ b/lib/std/crypto/tls/Client.zig @@ -805,9 +805,9 @@ fn prepareCiphertextRecord( const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; while (true) { const encrypted_content_len: u16 = @intCast(@min( - @min(bytes.len - bytes_i, max_ciphertext_len - 1), - ciphertext_buf.len - close_notify_alert_reserved - - overhead_len - ciphertext_end, + @min(bytes.len - bytes_i, tls.max_cipertext_inner_record_len), + ciphertext_buf.len -| + (close_notify_alert_reserved + overhead_len + ciphertext_end), )); if (encrypted_content_len == 0) return .{ .iovec_end = iovec_end,