public inbox for git-commits@fedoraproject.org
help / color / mirror / Atom feed
From: Peter Lemenkov <lemenkov@gmail.com>
To: git-commits@fedoraproject.org
Subject: [rpms/erlang] f44: Backported fixes for CVE-2026-59696, CVE-2026-94200, CVE-2026-105236
Date: Mon, 02 Nov 2026 18:03:47 GMT [thread overview]
Message-ID: <179364262701.1.11300976777711995473.rpms-erlang-a0c0eccb1e2a@fedoraproject.org> (raw)
A new commit has been pushed.
Repo : rpms/erlang
Branch : f44
Commit : a0c0eccb1e2a53bcef6bfcff656059f47251c128
Author : Peter Lemenkov <lemenkov@gmail.com>
Date : 2026-11-02T19:02:44+01:00
Stats : +2586/-0 in 5 file(s)
URL : https://src.fedoraproject.org/rpms/erlang/c/a0c0eccb1e2a53bcef6bfcff656059f47251c128?branch=f44
Log:
Backported fixes for CVE-2026-59696, CVE-2026-94200, CVE-2026-105236
- CVE-2026-59696: bound integer parsing in uri_string, httpc, eldap, snmp
- CVE-2026-94200: check message type when decoding TLS extensions
- CVE-2026-105236: check SNI on TLS 1.2 session resumption
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
---
diff --git a/erlang.spec b/erlang.spec
index a89a705..aea4085 100644
--- a/erlang.spec
+++ b/erlang.spec
@@ -124,6 +124,10 @@ Patch22: otp-0022-ssh-Limit-size-of-channel-cache-entries.patch
Patch23: otp-0023-ssl-Reject-unsolicited-TLS-1.3-pre_shared_key-in-cli.patch
Patch24: otp-0024-Avoid-signed-int-overflows.patch
Patch25: otp-0025-inets-Canonicalize-request-path-before-mod_auth-dire.patch
+Patch26: otp-0026-ssl-Check-message-type-for-extension-decoding.patch
+Patch27: otp-0027-inets-stdlib-eldap-Bound-integer-parsing-to-mitigate.patch
+Patch28: otp-0028-snmp-Bound-integer-parsing-in-the-BER-decoder.patch
+Patch29: otp-0029-ssl-Check-SNI-in-TLS-1.2-session-reuse.patch
# end of autogenerated patch tag list
BuildRequires: gcc
diff --git a/otp-0026-ssl-Check-message-type-for-extension-decoding.patch b/otp-0026-ssl-Check-message-type-for-extension-decoding.patch
new file mode 100644
index 0000000..5d50ee6
--- /dev/null
+++ b/otp-0026-ssl-Check-message-type-for-extension-decoding.patch
@@ -0,0 +1,460 @@
+From: Ingela Anderton Andin <ingela@erlang.org>
+Date: Thu, 24 Sep 2026 13:09:42 +0200
+Subject: [PATCH] ssl: Check message type for extension decoding
+
+This is especially importante for new_session_ticket message
+to avoid ticket poisning from malicus server.
+
+Fixes CVE-2026-94200.
+
+(cherry picked from commit cd0334854bf3ef56dc16f9fb728efe88fb05c4ac)
+
+[Backport to OTP 26: kept OTP 26's TLS 1.3-only supported_versions
+selected-version clause and added the message-type guard to it; dropped
+the unrelated log-level change in tls_server_connection_1_3.erl; kept
+OTP 26's test includes and test list, adding only the new test case.]
+
+Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
+Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
+
+diff --git a/lib/ssl/src/ssl_handshake.erl b/lib/ssl/src/ssl_handshake.erl
+index 7e18803aa3..65f47eb963 100644
+--- a/lib/ssl/src/ssl_handshake.erl
++++ b/lib/ssl/src/ssl_handshake.erl
+@@ -2846,17 +2846,22 @@ decode_extensions(<<>>, _Version, _MessageType, Acc) ->
+ Acc;
+ decode_extensions(<<?UINT16(?ALPN_EXT), ?UINT16(ExtLen), ?UINT16(Len),
+ ExtensionData:Len/binary, Rest/binary>>, Version, MessageType, Acc)
+- when Len + 2 =:= ExtLen ->
++ when Len + 2 =:= ExtLen,
++ (MessageType == client_hello orelse
++ MessageType == server_hello orelse
++ MessageType == encrypted_extensions) ->
+ ALPN = #alpn{extension_data = ExtensionData},
+ assert_unique_extension(alpn, Acc),
+ decode_extensions(Rest, Version, MessageType, Acc#{alpn => ALPN});
+ decode_extensions(<<?UINT16(?NEXTPROTONEG_EXT), ?UINT16(Len),
+- ExtensionData:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
++ ExtensionData:Len/binary, Rest/binary>>, Version, MessageType, Acc)
++ when MessageType == client_hello; MessageType == server_hello ->
+ NextP = #next_protocol_negotiation{extension_data = ExtensionData},
+ assert_unique_extension(next_protocol_negotiation, Acc),
+ decode_extensions(Rest, Version, MessageType, Acc#{next_protocol_negotiation => NextP});
+ decode_extensions(<<?UINT16(?RENEGOTIATION_EXT), ?UINT16(Len),
+- Info:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
++ Info:Len/binary, Rest/binary>>, Version, MessageType, Acc)
++ when MessageType == client_hello; MessageType == server_hello ->
+ RenegotiateInfo = case Len of
+ 1 -> % Initial handshake
+ Info; % should be <<0>> will be matched in handle_renegotiation_info
+@@ -2873,13 +2878,15 @@ decode_extensions(<<?UINT16(?RENEGOTIATION_EXT), ?UINT16(Len),
+
+ decode_extensions(<<?UINT16(?SRP_EXT), ?UINT16(Len), ?BYTE(SRPLen),
+ SRP:SRPLen/binary, Rest/binary>>, Version, MessageType, Acc)
+- when Len == SRPLen + 1 ->
++ when Len == SRPLen + 1, MessageType == client_hello ->
+ assert_unique_extension(srp, Acc),
+ decode_extensions(Rest, Version, MessageType, Acc#{srp => #srp{username = SRP}});
+
+ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc)
+- when ?TLS_LT(Version, ?TLS_1_2) ->
++ ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc)
++ when ?TLS_LT(Version, ?TLS_1_2),
++ (MessageType == client_hello orelse
++ MessageType == certificate_request) ->
+ SignAlgoListLen = Len - 2,
+ <<?UINT16(SignAlgoListLen), SignAlgoList/binary>> = ExtData,
+ HashSignAlgos = [{ssl_cipher:hash_algorithm(Hash), ssl_cipher:sign_algorithm(Sign)} ||
+@@ -2890,7 +2897,8 @@ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_EXT), ?UINT16(Len),
+ #hash_sign_algos{hash_sign_algos =
+ HashSignAlgos}});
+ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, ?TLS_1_2=Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>, ?TLS_1_2 = Version, MessageType, Acc) when
++ MessageType == client_hello; MessageType == certificate_request->
+ SignSchemeListLen = Len - 2,
+ <<?UINT16(SignSchemeListLen), SignSchemeList/binary>> = ExtData,
+ HashSigns = decode_sign_alg(Version, SignSchemeList),
+@@ -2900,7 +2908,8 @@ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_EXT), ?UINT16(Len),
+ #hash_sign_algos{
+ hash_sign_algos = HashSigns}});
+ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, ?TLS_1_3=Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>, ?TLS_1_3 = Version, MessageType, Acc) when
++ MessageType == client_hello; MessageType == certificate_request ->
+ SignSchemeListLen = Len - 2,
+ <<?UINT16(SignSchemeListLen), SignSchemeList/binary>> = ExtData,
+ SignSchemes = decode_sign_alg(Version, SignSchemeList),
+@@ -2931,7 +2940,8 @@ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_EXT), ?UINT16(Len),
+ signature_scheme_list = SignSchemes}});
+
+ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_CERT_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) when
++ MessageType == client_hello; MessageType == certificate_request ->
+ SignSchemeListLen = Len - 2,
+ <<?UINT16(SignSchemeListLen), SignSchemeList/binary>> = ExtData,
+ %% Ignore unknown signature algorithms
+@@ -2950,21 +2960,24 @@ decode_extensions(<<?UINT16(?SIGNATURE_ALGORITHMS_CERT_EXT), ?UINT16(Len),
+ Acc#{signature_algs_cert =>
+ #signature_algorithms_cert{
+ signature_scheme_list = SignSchemes}});
+-
+ decode_extensions(<<?UINT16(?USE_SRTP_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
+- <<?UINT16(ProfilesLen), ProfilesBin:ProfilesLen/binary, ?BYTE(MKILen), MKI:MKILen/binary>> = ExtData,
++ ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) when
++ MessageType == client_hello; MessageType == server_hello;
++ MessageType == encrypted_extensions->
++ <<?UINT16(ProfilesLen), ProfilesBin:ProfilesLen/binary,
++ ?BYTE(MKILen), MKI:MKILen/binary>> = ExtData,
+ Profiles = [P || <<P:2/binary>> <= ProfilesBin],
+ assert_unique_extension(use_srtp, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{use_srtp =>
+- #use_srtp{
+- protection_profiles = Profiles,
+- mki = MKI}});
+-
++ #use_srtp{
++ protection_profiles = Profiles,
++ mki = MKI}});
+ decode_extensions(<<?UINT16(?ELLIPTIC_CURVES_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc)
+- when ?TLS_LT(Version, ?TLS_1_3) ->
++ ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc)
++ when ?TLS_LT(Version, ?TLS_1_3),
++ (MessageType == client_hello orelse
++ MessageType == server_hello) ->
+ <<?UINT16(_), EllipticCurveList/binary>> = ExtData,
+ %% Ignore unknown curves
+ Pick = fun(Enum) ->
+@@ -2981,9 +2994,10 @@ decode_extensions(<<?UINT16(?ELLIPTIC_CURVES_EXT), ?UINT16(Len),
+ Acc#{elliptic_curves =>
+ #elliptic_curves{elliptic_curve_list =
+ EllipticCurves}});
+-
+ decode_extensions(<<?UINT16(?ELLIPTIC_CURVES_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, ?TLS_1_3=Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>, ?TLS_1_3 = Version, MessageType, Acc) when
++ MessageType == client_hello;
++ MessageType == encrypted_extensions->
+ <<?UINT16(_), GroupList/binary>> = ExtData,
+ %% Ignore unknown curves
+ Pick = fun(Enum) ->
+@@ -3000,9 +3014,9 @@ decode_extensions(<<?UINT16(?ELLIPTIC_CURVES_EXT), ?UINT16(Len),
+ Acc#{elliptic_curves =>
+ #supported_groups{supported_groups =
+ SupportedGroups}});
+-
+ decode_extensions(<<?UINT16(?EC_POINT_FORMATS_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) when
++ MessageType == client_hello; MessageType == server_hello ->
+ <<?BYTE(_), ECPointFormatList/binary>> = ExtData,
+ ECPointFormats = binary_to_list(ECPointFormatList),
+ assert_unique_extension(ec_point_formats, Acc),
+@@ -3010,27 +3024,39 @@ decode_extensions(<<?UINT16(?EC_POINT_FORMATS_EXT), ?UINT16(Len),
+ Acc#{ec_point_formats =>
+ #ec_point_formats{ec_point_format_list =
+ ECPointFormats}});
+-
+ decode_extensions(<<?UINT16(?SNI_EXT), ?UINT16(Len),
+- Rest/binary>>, Version, MessageType, Acc) when Len == 0 ->
++ Rest/binary>>, Version, MessageType, Acc) when
++ Len == 0,
++ (MessageType == server_hello orelse
++ MessageType == encrypted_extensions) ->
+ assert_unique_extension(sni, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{sni => #sni{hostname = ""}}); %% Server may send an empty SNI
+
+ decode_extensions(<<?UINT16(?SNI_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) when
++ MessageType == client_hello;
++ MessageType == server_hello;
++ MessageType == encrypted_extensions ->
+ <<?UINT16(_), NameList/binary>> = ExtData,
+ assert_unique_extension(sni, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{sni => dec_sni(NameList)});
+
+-decode_extensions(<<?UINT16(?MAX_FRAGMENT_LENGTH_EXT), ?UINT16(1), ?BYTE(MaxFragEnum), Rest/binary>>,
+- Version, MessageType, Acc) ->
++decode_extensions(<<?UINT16(?MAX_FRAGMENT_LENGTH_EXT), ?UINT16(1),
++ ?BYTE(MaxFragEnum), Rest/binary>>,
++ Version, MessageType, Acc) when MessageType == client_hello;
++ MessageType == server_hello;
++ MessageType == encrypted_extensions ->
+ %% RFC 6066 Section 4
+ assert_unique_extension(max_frag_enum, Acc),
+ decode_extensions(Rest, Version, MessageType, Acc#{max_frag_enum => #max_frag_enum{enum = MaxFragEnum}});
+ decode_extensions(<<?UINT16(?SUPPORTED_VERSIONS_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) when Len > 2 ->
++ ExtData:Len/binary, Rest/binary>>, Version,
++ MessageType, Acc) when Len > 2,
++ (MessageType == client_hello orelse
++ MessageType == server_hello orelse
++ MessageType == hello_retry_request) ->
+ <<?BYTE(_),Versions/binary>> = ExtData,
+ assert_unique_extension(client_hello_versions, Acc),
+ decode_extensions(Rest, Version, MessageType,
+@@ -3039,15 +3065,18 @@ decode_extensions(<<?UINT16(?SUPPORTED_VERSIONS_EXT), ?UINT16(Len),
+ versions = decode_versions(Versions)}});
+
+ decode_extensions(<<?UINT16(?SUPPORTED_VERSIONS_EXT), ?UINT16(Len),
+- ?UINT16(SelectedVersion), Rest/binary>>, Version, MessageType, Acc)
+- when Len =:= 2, SelectedVersion =:= 16#0304 ->
++ ?UINT16(SelectedVersion), Rest/binary>>, Version, MessageType, Acc)
++ when Len =:= 2, SelectedVersion =:= 16#0304,
++ (MessageType == client_hello orelse
++ MessageType == server_hello orelse
++ MessageType == hello_retry_request) ->
+ assert_unique_extension(server_hello_selected_version, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{server_hello_selected_version =>
+ #server_hello_selected_version{selected_version = ?TLS_1_3}});
+
+ decode_extensions(<<?UINT16(?KEY_SHARE_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>,
++ ExtData:Len/binary, Rest/binary>>,
+ Version, MessageType = client_hello, Acc) ->
+ <<?UINT16(_),ClientShares/binary>> = ExtData,
+ assert_unique_extension(key_share, Acc),
+@@ -3079,7 +3108,8 @@ decode_extensions(<<?UINT16(?KEY_SHARE_EXT), ?UINT16(Len),
+ selected_group = tls_v1:enum_to_group(Group)}});
+
+ decode_extensions(<<?UINT16(?PSK_KEY_EXCHANGE_MODES_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>, Version, MessageType, Acc) ->
++ ExtData:Len/binary, Rest/binary>>,
++ Version, MessageType, Acc) when MessageType == client_hello ->
+ <<?BYTE(PLen),KEModes:PLen/binary>> = ExtData,
+ assert_unique_extension(psk_key_exchange_modes, Acc),
+ decode_extensions(Rest, Version, MessageType,
+@@ -3088,7 +3118,7 @@ decode_extensions(<<?UINT16(?PSK_KEY_EXCHANGE_MODES_EXT), ?UINT16(Len),
+ ke_modes = decode_psk_key_exchange_modes(KEModes)}});
+
+ decode_extensions(<<?UINT16(?PRE_SHARED_KEY_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>,
++ ExtData:Len/binary, Rest/binary>>,
+ Version, MessageType = client_hello, Acc) ->
+ <<?UINT16(IdLen),Identities:IdLen/binary,?UINT16(BLen),Binders:BLen/binary>> = ExtData,
+ assert_unique_extension(pre_shared_key, Acc),
+@@ -3101,7 +3131,7 @@ decode_extensions(<<?UINT16(?PRE_SHARED_KEY_EXT), ?UINT16(Len),
+ binder_length = BLen + 2}}
+ );
+ decode_extensions(<<?UINT16(?PRE_SHARED_KEY_EXT), ?UINT16(Len),
+- ExtData:Len/binary, Rest/binary>>,
++ ExtData:Len/binary, Rest/binary>>,
+ Version, MessageType = server_hello, Acc) ->
+ <<?UINT16(Identity)>> = ExtData,
+ assert_unique_extension(pre_shared_key, Acc),
+@@ -3113,7 +3143,9 @@ decode_extensions(<<?UINT16(?PRE_SHARED_KEY_EXT), ?UINT16(Len),
+ decode_extensions(<<?UINT16(?COOKIE_EXT), ?UINT16(Len), ?UINT16(CookieLen),
+ Cookie:CookieLen/binary, Rest/binary>>,
+ Version, MessageType, Acc)
+- when Len == CookieLen + 2 ->
++ when Len == CookieLen + 2,
++ (MessageType == client_hello orelse
++ MessageType == hello_retry_request) ->
+ assert_unique_extension(cookie, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{cookie => #cookie{cookie = Cookie}});
+@@ -3123,8 +3155,12 @@ decode_extensions(<<?UINT16(?COOKIE_EXT), ?UINT16(Len), ?UINT16(CookieLen),
+ %% with empty "extension_data" in the extended server hello.
+ decode_extensions(<<?UINT16(?STATUS_REQUEST), ?UINT16(Len),
+ _ExtensionData:Len/binary, Rest/binary>>, Version,
+- MessageType = server_hello, Acc)
+- when Len =:= 0 ->
++ MessageType, Acc)
++ when Len =:= 0,
++ (MessageType == client_hello orelse
++ MessageType == server_hello orelse
++ MessageType == certificate_request orelse
++ MessageType == certificate) ->
+ assert_unique_extension(status_request, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{status_request => undefined});
+@@ -3133,34 +3169,36 @@ decode_extensions(<<?UINT16(?STATUS_REQUEST), ?UINT16(Len),
+ %% RFC6066.
+ decode_extensions(<<?UINT16(?STATUS_REQUEST), ?UINT16(Len),
+ CertStatus:Len/binary, Rest/binary>>, Version,
+- MessageType, Acc) ->
++ MessageType, Acc) ->
+ case CertStatus of
+ <<?BYTE(?CERTIFICATE_STATUS_TYPE_OCSP),
+ ?UINT24(OCSPLen),
+ ASN1OCSPResponse:OCSPLen/binary>> ->
+ assert_unique_extension(status_request, Acc),
+ decode_extensions(Rest, Version, MessageType,
+- Acc#{status_request => #certificate_status{response = ASN1OCSPResponse}});
++ Acc#{status_request => #certificate_status{response = ASN1OCSPResponse}});
+ _Other ->
+ decode_extensions(Rest, Version, MessageType, Acc)
+ end;
+
+ decode_extensions(<<?UINT16(?EARLY_DATA_EXT), ?UINT16(0), Rest/binary>>,
+- Version, MessageType, Acc) ->
++ Version, MessageType, Acc) when MessageType == client_hello;
++ MessageType == encrypted_extensions ->
+ assert_unique_extension(early_data, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{early_data => #early_data_indication{}});
+
+ decode_extensions(<<?UINT16(?EARLY_DATA_EXT), ?UINT16(4), ?UINT32(MaxSize),
+ Rest/binary>>,
+- Version, MessageType, Acc) ->
++ Version, new_session_ticket = MessageType, Acc) ->
+ assert_unique_extension(early_data, Acc),
+ decode_extensions(Rest, Version, MessageType,
+ Acc#{early_data =>
+ #early_data_indication_nst{indication = MaxSize}});
+ decode_extensions(<<?UINT16(?CERTIFICATE_AUTHORITIES_EXT), ?UINT16(Len),
+ CertAutsExt:Len/binary, Rest/binary>>,
+- Version, MessageType, Acc) ->
++ Version, MessageType, Acc) when MessageType == client_hello;
++ MessageType == certificate_request ->
+ CertAutsLen = Len - 2,
+ <<?UINT16(CertAutsLen), EncCertAuts/binary>> = CertAutsExt,
+ assert_unique_extension(certificate_authorities, Acc),
+diff --git a/lib/ssl/src/tls_handshake_1_3.erl b/lib/ssl/src/tls_handshake_1_3.erl
+index 58adef4161..0182a43ee6 100644
+--- a/lib/ssl/src/tls_handshake_1_3.erl
++++ b/lib/ssl/src/tls_handshake_1_3.erl
+@@ -648,7 +648,7 @@ decode_handshake(?NEW_SESSION_TICKET, <<?UINT32(LifeTime), ?UINT32(Age),
+ ?BYTE(NonceSize), Nonce:NonceSize/binary,
+ ?UINT16(TicketSize), Ticket:TicketSize/binary,
+ ?UINT16(BinExtSize), BinExts:BinExtSize/binary>>) ->
+- Exts = decode_extensions(BinExts, encrypted_extensions),
++ Exts = decode_extensions(BinExts, new_session_ticket),
+ #new_session_ticket{ticket_lifetime = LifeTime,
+ ticket_age_add = Age,
+ ticket_nonce = Nonce,
+diff --git a/lib/ssl/test/property_test/ssl_eqc_handshake.erl b/lib/ssl/test/property_test/ssl_eqc_handshake.erl
+index dface49f82..818798f5d9 100644
+--- a/lib/ssl/test/property_test/ssl_eqc_handshake.erl
++++ b/lib/ssl/test/property_test/ssl_eqc_handshake.erl
+@@ -484,7 +484,24 @@ extensions(?TLS_1_3 = Version, encrypted_extensions) ->
+ server_name() ->
+ ?LET(ServerName, sni(),
+ ServerName).
+- %% sni().
++
++max_fragment_length() ->
++ ?LET(Enum, elements([1,2,3,4]), #max_frag_enum{enum = Enum}).
++
++status_request(client_hello) ->
++ undefined; %% Should extend this as part of OCSP enhancement
++status_request(server_hello) ->
++ "".
++
++early_data_indication() ->
++ %% In ClientHello and EncryptedExtensions the early_data extension is
++ %% empty (RFC 8446/9846 4.2.10). The max_early_data_size form
++ %% (#early_data_indication_nst{}) is only valid in NewSessionTicket.
++ #early_data_indication{}.
++
++cookie() ->
++ %% Can be bigger, but value is not important here.
++ #cookie{cookie = rand:bytes(20)}.
+
+ signature_algs_cert() ->
+ ?LET(List, sig_scheme_list(),
+diff --git a/lib/ssl/test/ssl_handshake_SUITE.erl b/lib/ssl/test/ssl_handshake_SUITE.erl
+index 48acb6f5ea..cf44268ae0 100644
+--- a/lib/ssl/test/ssl_handshake_SUITE.erl
++++ b/lib/ssl/test/ssl_handshake_SUITE.erl
+@@ -30,6 +30,7 @@
+ -include("ssl_internal.hrl").
+ -include("ssl_record.hrl").
+ -include("tls_handshake.hrl").
++-include("tls_handshake_1_3.hrl").
+ -include_lib("public_key/include/public_key.hrl").
+
+ %% Common test
+@@ -53,7 +54,8 @@
+ select_proper_tls_1_2_rsa_default_hashsign/1,
+ ignore_hassign_extension_pre_tls_1_2/1,
+ signature_algorithms/1,
+- drop_unassigned_signature_algorithms/1]).
++ drop_unassigned_signature_algorithms/1,
++ decode_early_data_extension_by_message_type/1]).
+
+ %%--------------------------------------------------------------------
+ %% Common Test interface functions -----------------------------------
+@@ -68,7 +70,8 @@ all() -> [decode_hello_handshake,
+ select_proper_tls_1_2_rsa_default_hashsign,
+ ignore_hassign_extension_pre_tls_1_2,
+ signature_algorithms,
+- drop_unassigned_signature_algorithms].
++ drop_unassigned_signature_algorithms,
++ decode_early_data_extension_by_message_type].
+
+ %%--------------------------------------------------------------------
+ init_per_suite(Config) ->
+@@ -138,7 +141,7 @@ decode_hello_handshake(_Config) ->
+
+ decode_single_hello_extension_correctly(_Config) ->
+ Renegotiation = <<?UINT16(?RENEGOTIATION_EXT), ?UINT16(1), 0>>,
+- Extensions = ssl_handshake:decode_extensions(Renegotiation, ?TLS_1_2, undefined),
++ Extensions = ssl_handshake:decode_extensions(Renegotiation, ?TLS_1_2, client_hello),
+ #{renegotiation_info := #renegotiation_info{renegotiated_connection = <<0>>}} = Extensions.
+
+ decode_supported_elliptic_curves_hello_extension_correctly(_Config) ->
+@@ -180,6 +183,54 @@ decode_empty_server_sni_correctly(_Config) ->
+ #{sni := #sni{hostname = ""}} = Decoded.
+
+
++decode_early_data_extension_by_message_type(_Config) ->
++ %% RFC 9846 §4.2: the early_data extension has two wire forms and the
++ %% form permitted depends on the handshake message it rides in:
++ %% - empty (0-length) in ClientHello / EncryptedExtensions
++ %% -> #early_data_indication{}
++ %% - 4-byte max_early_data_size in NewSessionTicket
++ %% -> #early_data_indication_nst{}
++ %% The decoder must enforce this per message type. Regression test for the
++ %% NST early_data DoS: a malicious server's NewSessionTicket carrying a
++ %% 0-length early_data was previously decoded to #early_data_indication{}
++ %% and stored in the node-global tls_client_ticket_store; a later
++ %% auto-resume then crashed the store with a case_clause in
++ %% get_max_early_data/1 (only undefined/#early_data_indication_nst{} are
++ %% handled there). The fix guards the 0-length form to CH/EE only, so a
++ %% 0-length early_data in an NST is ignored (never stored, never crashes).
++
++ EmptyEarlyData = <<?UINT16(?EARLY_DATA_EXT), ?UINT16(0)>>,
++ NstEarlyData = <<?UINT16(?EARLY_DATA_EXT), ?UINT16(4), ?UINT32(16384)>>,
++
++ %% Legitimate empty form in ClientHello / EncryptedExtensions is accepted.
++ #{early_data := #early_data_indication{}} =
++ ssl_handshake:decode_extensions(EmptyEarlyData, ?TLS_1_3, client_hello),
++ #{early_data := #early_data_indication{}} =
++ ssl_handshake:decode_extensions(EmptyEarlyData, ?TLS_1_3, encrypted_extensions),
++
++ %% Legitimate 4-byte form in NewSessionTicket is accepted.
++ #{early_data := #early_data_indication_nst{indication = 16384}} =
++ ssl_handshake:decode_extensions(NstEarlyData, ?TLS_1_3, new_session_ticket),
++
++ %% DoS closure: a 0-length early_data in a NewSessionTicket is NOT a valid
++ %% NST form, so it is ignored (no early_data key) rather than stored as
++ %% #early_data_indication{}. Before the fix this returned
++ %% #{early_data => #early_data_indication{}} and poisoned the ticket store.
++ NoEarlyDataNst = ssl_handshake:decode_extensions(EmptyEarlyData, ?TLS_1_3,
++ new_session_ticket),
++ false = maps:is_key(early_data, NoEarlyDataNst),
++
++ %% Symmetric guard: the 4-byte NST form is not valid in ClientHello /
++ %% EncryptedExtensions and is likewise ignored.
++ NoEarlyDataCh = ssl_handshake:decode_extensions(NstEarlyData, ?TLS_1_3,
++ client_hello),
++ false = maps:is_key(early_data, NoEarlyDataCh),
++ NoEarlyDataEe = ssl_handshake:decode_extensions(NstEarlyData, ?TLS_1_3,
++ encrypted_extensions),
++ false = maps:is_key(early_data, NoEarlyDataEe),
++ ok.
++
++
+ select_proper_tls_1_2_rsa_default_hashsign(_Config) ->
+ % RFC 5246 section 7.4.1.4.1 tells to use {sha1,rsa} as default signature_algorithm for RSA key exchanges
+ {sha, rsa} = ssl_handshake:select_hashsign_algs(undefined, ?rsaEncryption, ?TLS_1_2),
diff --git a/otp-0027-inets-stdlib-eldap-Bound-integer-parsing-to-mitigate.patch b/otp-0027-inets-stdlib-eldap-Bound-integer-parsing-to-mitigate.patch
new file mode 100644
index 0000000..5dbc5db
--- /dev/null
+++ b/otp-0027-inets-stdlib-eldap-Bound-integer-parsing-to-mitigate.patch
@@ -0,0 +1,749 @@
+From: Konrad Pietrzak <konrad@erlang.org>
+Date: Thu, 25 Jun 2026 13:51:22 +0200
+Subject: [PATCH] inets,stdlib,eldap: Bound integer parsing to mitigate DoS
+
+inets (httpc):
+- Add per-request max_header_size and max_body_size options
+- Enforce cumulative header byte count during parsing; reject with
+ {error, {header_too_long, {max, MaxSize}}} when exceeded
+- Default max_header_size is 10240 (same as httpd)
+- Validate Content-Length contains only digits before storing,
+ preventing badarg crashes on malformed responses
+- Update limits from new request options on connection reuse
+- Catch validation throws in handler, return clean errors to caller
+- Document new options in request/4,5 docstring
+
+stdlib (uri_string):
+- Bound port component digit count in uri_string:parse/1
+
+eldap:
+- Bound port digit count in referral URL parsing
+
+snmp:
+- Bound INTEGER value to max 32-bit value as in SMI-MIB
+- Bound Counter32/Gauge32/TimeTicks to 5 bytes (32-bit + sign)
+- Bound Counter64 to 9 bytes (64-bit + sign)
+
+Mitigates GHSA-8qw4-2chm-mvj2.
+
+Fixes CVE-2026-59696.
+
+(cherry picked from commit aba0fe8c2d700bf4ac94607cf7f00e53bbe4042d)
+
+[Backport to OTP 26: dropped the -doc attribute for httpc:request/5
+(OTP 26 has XML docs). The headers_conflict_chunked_with_length test
+conflict was adapted to OTP 26 call syntax: the new throw handler in
+httpc_handler now reports {headers_conflict, _} instead of
+{could_not_parse_as_http, _}, as upstream.]
+
+Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
+Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
+
+diff --git a/lib/eldap/src/eldap.erl b/lib/eldap/src/eldap.erl
+index 7edd012263..eea66896f8 100644
+--- a/lib/eldap/src/eldap.erl
++++ b/lib/eldap/src/eldap.erl
+@@ -1422,10 +1422,12 @@ parse_hostport(Str) ->
+ parse_port(Rest,Sport)}}
+ end.
+
+-parse_port(Rest,Sport) ->
++parse_port(Rest,Sport) when length(Sport) =< 5 ->
+ try list_to_integer(Sport)
+ catch _:_ -> parse_error(parsing_port,Rest)
+- end.
++ end;
++parse_port(Rest, _) ->
++ parse_error(parsing_port, Rest).
+
+ parse_host(Rest,Shost) ->
+ case catch validate_host(Shost) of
+diff --git a/lib/inets/src/http_client/httpc.erl b/lib/inets/src/http_client/httpc.erl
+index 953f19bc5a..23ca981431 100644
+--- a/lib/inets/src/http_client/httpc.erl
++++ b/lib/inets/src/http_client/httpc.erl
+@@ -156,7 +156,9 @@ request(Url, Profile) ->
+ | {headers_as_is, boolean()}
+ | {socket_opts, [SocketOpt]}
+ | {receiver, Receiver}
+- | {ipv6_host_with_brackets, boolean()},
++ | {ipv6_host_with_brackets, boolean()}
++ | {max_header_size, MaxSize}
++ | {max_body_size, MaxSize},
+ StreamTo :: none | self | {self, once} | file:name_all(),
+ SocketOpt :: term(),
+ BodyFormat :: string | binary,
+@@ -165,6 +167,7 @@ request(Url, Profile) ->
+ | { ReceiverModule::atom()
+ , ReceiverFunction::atom()
+ , ReceiverArgs::list()},
++ MaxSize :: non_neg_integer() | nolimit,
+ Result :: { StatusLine , [HttpHeader], HttpBodyResult}
+ | { StatusCode, HttpBodyResult}
+ | RequestId
+@@ -218,7 +221,9 @@ request(Method, Request, HttpOptions, Options) ->
+ | {headers_as_is, boolean()}
+ | {socket_opts, [SocketOpt]}
+ | {receiver, Receiver}
+- | {ipv6_host_with_brackets, boolean()},
++ | {ipv6_host_with_brackets, boolean()}
++ | {max_header_size, MaxSize}
++ | {max_body_size, MaxSize},
+ StreamTo :: none | self | {self, once} | file:name_all(),
+ BodyFormat :: string | binary,
+ SocketOpt :: term(),
+@@ -227,6 +232,7 @@ request(Method, Request, HttpOptions, Options) ->
+ | { ReceiverModule::atom()
+ , ReceiverFunction::atom()
+ , ReceiverArgs::list()},
++ MaxSize :: non_neg_integer() | nolimit,
+ Profile :: atom() | pid(),
+ HttpVersion :: string(),
+ Result :: {StatusLine
+@@ -927,7 +933,9 @@ maybe_format_body(BinBody, Options) ->
+ | {headers_as_is, boolean()}
+ | {socket_opts, [SocketOpt]}
+ | {receiver, Receiver}
+- | {ipv6_host_with_brackets, boolean()},
++ | {ipv6_host_with_brackets, boolean()}
++ | {max_header_size, MaxSize}
++ | {max_body_size, MaxSize},
+ BodyFormat :: string | binary,
+ StreamTo :: none | self | {self, once} | file:name_all(),
+ SocketOpt :: term(),
+@@ -935,7 +943,8 @@ maybe_format_body(BinBody, Options) ->
+ | fun((term()) -> term())
+ | { ReceiverModule::atom()
+ , ReceiverFunction::atom()
+- , ReceiverArgs::list()}.
++ , ReceiverArgs::list()},
++ MaxSize :: non_neg_integer() | nolimit.
+ %% This options is a workaround for http servers that do not follow the
+ %% http standard and have case sensitive header parsing. Should only be
+ %% used if there is no other way to communicate with the server or for
+@@ -1120,16 +1129,26 @@ request_options_defaults() ->
+
+ VerifyBrackets = VerifyBoolean,
+
++ VerifyIntegerNoLimit =
++ fun(nolimit) ->
++ ok;
++ (Value) when
++ is_integer(Value), Value > 0 ->
++ ok
++ end,
++
+ [
+- {sync, true, VerifySync},
+- {stream, none, VerifyStream},
+- {body_format, string, VerifyBodyFormat},
+- {full_result, true, VerifyFullResult},
+- {headers_as_is, false, VerifyHeaderAsIs},
+- {receiver, alias(), VerifyReceiver},
+- {socket_opts, undefined, VerifySocketOpts},
+- {ipv6_host_with_brackets, false, VerifyBrackets}
+- ].
++ {sync, true, VerifySync},
++ {stream, none, VerifyStream},
++ {body_format, string, VerifyBodyFormat},
++ {full_result, true, VerifyFullResult},
++ {headers_as_is, false, VerifyHeaderAsIs},
++ {receiver, alias(), VerifyReceiver},
++ {socket_opts, undefined, VerifySocketOpts},
++ {ipv6_host_with_brackets, false, VerifyBrackets},
++ {max_header_size, ?HTTP_MAX_HEADER_SIZE, VerifyIntegerNoLimit},
++ {max_body_size, ?HTTP_MAX_BODY_SIZE, VerifyIntegerNoLimit}
++ ].
+
+ request_options(Options) ->
+ Defaults = request_options_defaults(),
+@@ -1175,7 +1194,9 @@ request_options([{Key, DefaultVal, Verify} | Defaults], Options, Acc) ->
+ | {headers_as_is, boolean()}
+ | {socket_opts, [SocketOpt]}
+ | {receiver, Receiver}
+- | {ipv6_host_with_brackets, boolean()},
++ | {ipv6_host_with_brackets, boolean()}
++ | {max_header_size, MaxSize}
++ | {max_body_size, MaxSize},
+ StreamTo :: none | self | {self, once} | file:name_all(),
+ BodyFormat :: string | binary,
+ SocketOpt :: term(),
+@@ -1184,7 +1205,8 @@ request_options([{Key, DefaultVal, Verify} | Defaults], Options, Acc) ->
+ | fun((term()) -> term())
+ | { ReceiverModule::atom()
+ , ReceiverFunction::atom()
+- , ReceiverArgs::list()}.
++ , ReceiverArgs::list()},
++ MaxSize :: non_neg_integer() | nolimit.
+ request_options_sanity_check(Opts) ->
+ case proplists:get_value(sync, Opts) of
+ Sync when (Sync =:= true) ->
+diff --git a/lib/inets/src/http_client/httpc_handler.erl b/lib/inets/src/http_client/httpc_handler.erl
+index 1d91fe1479..a10d3bd565 100644
+--- a/lib/inets/src/http_client/httpc_handler.erl
++++ b/lib/inets/src/http_client/httpc_handler.erl
+@@ -224,17 +224,23 @@ init([Parent, Request, Options, ProfileName]) ->
+ handle_verbose(Options#options.verbose),
+ ProxyOptions = handle_proxy_options(Request#request.scheme, Options),
+ Address = handle_proxy(Request#request.address, ProxyOptions),
++ MaxHeaderSize = proplists:get_value(max_header_size, Request#request.request_options),
++ MaxBodySize = proplists:get_value(max_body_size, Request#request.request_options),
+ {ok, State} =
+ %% #state.once should initially be 'inactive' because we
+ %% activate the socket at first regardless of the state.
+ case {Address /= Request#request.address, Request#request.scheme} of
+ {true, https} ->
+ connect_and_send_upgrade_request(Address, Request,
+- #state{options = Options,
++ #state{max_header_size = MaxHeaderSize,
++ max_body_size = MaxBodySize,
++ options = Options,
+ profile_name = ProfileName});
+ {_, _} ->
+ connect_and_send_first_request(Address, Request,
+- #state{options = Options,
++ #state{max_header_size = MaxHeaderSize,
++ max_body_size = MaxBodySize,
++ options = Options,
+ profile_name = ProfileName})
+ end,
+ gen_server:enter_loop(?MODULE, [], State).
+@@ -248,6 +254,20 @@ init([Parent, Request, Options, ProfileName]) ->
+ %% {stop, Reason, State} (terminate/2 is called)
+ %% Description: Handling call messages
+ %%--------------------------------------------------------------------
++handle_call(Request, From, State0) when
++ is_record(Request, request) ->
++ MaxHeaderSize = proplists:get_value(max_header_size, Request#request.request_options),
++ MaxBodySize = proplists:get_value(max_body_size, Request#request.request_options),
++ State = State0#state{max_header_size = MaxHeaderSize,
++ max_body_size = MaxBodySize},
++ try do_handle_call(Request, From, State) of
++ Result ->
++ Result
++ catch
++ Class:Reason:ST ->
++ {stop, {shutdown, {{Class, Reason}, ST}}, State}
++ end;
++
+ handle_call(Request, From, State) ->
+ try do_handle_call(Request, From, State) of
+ Result ->
+@@ -538,6 +558,10 @@ do_handle_info({Proto, _Socket, Data},
+ activate_once(Session),
+ {noreply, State#state{mfa = NewMFA}}
+ catch
++ throw:{error, Err}:_ ->
++ ClientErrMsg = httpc_response:error(Request, Err),
++ NewState = answer_request(Request, ClientErrMsg, State),
++ {stop, normal, NewState};
+ Class:Reason:ST ->
+ ClientReason = {could_not_parse_as_http, Data},
+ ClientErrMsg = httpc_response:error(Request, ClientReason),
+diff --git a/lib/inets/src/http_client/httpc_response.erl b/lib/inets/src/http_client/httpc_response.erl
+index 603cd64ea8..246ab88d55 100644
+--- a/lib/inets/src/http_client/httpc_response.erl
++++ b/lib/inets/src/http_client/httpc_response.erl
+@@ -56,9 +56,9 @@ parse_reason_phrase([Bin, Rest, Phrase, MaxHeaderSize, Result, Relaxed]) ->
+ parse_reason_phrase(<<Rest/binary, Bin/binary>>, Phrase,
+ MaxHeaderSize, Result, Relaxed).
+
+-parse_headers([Bin, Rest,Header, Headers, MaxHeaderSize, Result, Relaxed]) ->
++parse_headers([Bin, Rest,Header, Headers, MaxHeaderSize, CurrentSize, Result, Relaxed]) ->
+ parse_headers(<<Rest/binary, Bin/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed).
++ MaxHeaderSize, CurrentSize, Result, Relaxed).
+
+ whole_body(Body, Length) when is_binary(Body)->
+ case byte_size(Body) of
+@@ -195,7 +195,7 @@ parse_status_code(<<?LF>>, StatusCodeStr,
+
+ parse_status_code(<<?CR, ?LF, Rest/binary>>, StatusCodeStr,
+ MaxHeaderSize, Result, true) ->
+- parse_headers(Rest, [], [], MaxHeaderSize,
++ parse_headers(Rest, [], [], MaxHeaderSize, 0,
+ [" ", list_to_integer(lists:reverse(
+ string:trim(StatusCodeStr)))
+ | Result], true);
+@@ -245,7 +245,7 @@ parse_reason_phrase(<<?LF, Rest/binary>>, Phrase,
+ MaxHeaderSize, Result, Relaxed);
+ parse_reason_phrase(<<?CR, ?LF, Rest/binary>>, Phrase,
+ MaxHeaderSize, Result, Relaxed) ->
+- parse_headers(Rest, [], [], MaxHeaderSize,
++ parse_headers(Rest, [], [], MaxHeaderSize, 0,
+ [lists:reverse(Phrase) | Result], Relaxed);
+ parse_reason_phrase(<<?LF>>, Phrase, MaxHeaderSize, Result, Relaxed) ->
+ %% If ?CR is is missing RFC2616 section-19.3
+@@ -259,100 +259,96 @@ parse_reason_phrase(<<Octet, Rest/binary>>, Phrase, MaxHeaderSize, Result,
+ parse_reason_phrase(Rest, [Octet | Phrase], MaxHeaderSize,
+ Result, Relaxed).
+
+-parse_headers(<<>>, Header, Headers, MaxHeaderSize, Result, Relaxed) ->
+- {?MODULE, parse_headers, [<<>>, Header, Headers, MaxHeaderSize, Result,
++parse_headers(<<>>, Header, Headers, MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ {?MODULE, parse_headers, [<<>>, Header, Headers, MaxHeaderSize, CurrentSize, Result,
+ Relaxed]};
+
+ parse_headers(<<?CR,?LF,?LF,Body/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- %% If ?CR is is missing RFC2616 section-19.3
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ %% If ?CR is is missing RFC2616 section-19.3
+ parse_headers(<<?CR,?LF,?CR,?LF,Body/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed);
++ MaxHeaderSize, CurrentSize, Result, Relaxed);
+
+ parse_headers(<<?LF,?LF,Body/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- %% If ?CR is is missing RFC2616 section-19.3
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ %% If ?CR is is missing RFC2616 section-19.3
+ parse_headers(<<?CR,?LF,?CR,?LF,Body/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed);
++ MaxHeaderSize, CurrentSize, Result, Relaxed);
+
+ parse_headers(<<?CR,?LF,?CR,?LF,Body/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
++ _MaxHeaderSize, _CurrentSize, Result, Relaxed) ->
+ HTTPHeaders = [lists:reverse(Header) | Headers],
+- Length = lists:foldl(fun(H, Acc) -> length(H) + Acc end,
+- 0, HTTPHeaders),
+- case ((Length =< MaxHeaderSize) or (MaxHeaderSize == nolimit)) of
+- true ->
+- ResponseHeaderRcord =
+- http_response:headers(HTTPHeaders, #http_response_h{}),
+-
+- %% RFC7230, Section 3.3.3
+- %% If a message is received with both a Transfer-Encoding and a
+- %% Content-Length header field, the Transfer-Encoding overrides the
+- %% Content-Length. Such a message might indicate an attempt to
+- %% perform request smuggling (Section 9.5) or response splitting
+- %% (Section 9.4) and ought to be handled as an error. A sender MUST
+- %% remove the received Content-Length field prior to forwarding such
+- %% a message downstream.
+- case ResponseHeaderRcord#http_response_h.'transfer-encoding' of
+- undefined ->
++ ResponseHeaderRcord =
++ http_response:headers(HTTPHeaders, #http_response_h{}),
++
++ %% RFC7230, Section 3.3.3
++ %% If a message is received with both a Transfer-Encoding and a
++ %% Content-Length header field, the Transfer-Encoding overrides the
++ %% Content-Length. Such a message might indicate an attempt to
++ %% perform request smuggling (Section 9.5) or response splitting
++ %% (Section 9.4) and ought to be handled as an error. A sender MUST
++ %% remove the received Content-Length field prior to forwarding such
++ %% a message downstream.
++ case ResponseHeaderRcord#http_response_h.'transfer-encoding' of
++ undefined ->
++ {ok, list_to_tuple(
++ lists:reverse([Body, ResponseHeaderRcord | Result]))};
++ Value ->
++ TransferEncoding = string:lowercase(Value),
++ ContentLength = ResponseHeaderRcord#http_response_h.'content-length',
++ if
++ %% Respond without error but remove Content-Length field in relaxed mode
++ (Relaxed =:= true)
++ andalso (TransferEncoding =:= "chunked")
++ andalso (ContentLength =/= "-1") ->
++ ResponseHeaderRcordFixed =
++ ResponseHeaderRcord#http_response_h{'content-length' = "-1"},
++ {ok, list_to_tuple(
++ lists:reverse([Body, ResponseHeaderRcordFixed | Result]))};
++ %% Respond with error in default (not relaxed) mode
++ (Relaxed =:= false)
++ andalso (TransferEncoding =:= "chunked")
++ andalso (ContentLength =/= "-1") ->
++ throw({error, {headers_conflict, {'content-length',
++ 'transfer-encoding'}}});
++ true ->
+ {ok, list_to_tuple(
+- lists:reverse([Body, ResponseHeaderRcord | Result]))};
+- Value ->
+- TransferEncoding = string:lowercase(Value),
+- ContentLength = ResponseHeaderRcord#http_response_h.'content-length',
+- if
+- %% Respond without error but remove Content-Length field in relaxed mode
+- (Relaxed =:= true)
+- andalso (TransferEncoding =:= "chunked")
+- andalso (ContentLength =/= "-1") ->
+- ResponseHeaderRcordFixed =
+- ResponseHeaderRcord#http_response_h{'content-length' = "-1"},
+- {ok, list_to_tuple(
+- lists:reverse([Body, ResponseHeaderRcordFixed | Result]))};
+- %% Respond with error in default (not relaxed) mode
+- (Relaxed =:= false)
+- andalso (TransferEncoding =:= "chunked")
+- andalso (ContentLength =/= "-1") ->
+- throw({error, {headers_conflict, {'content-length',
+- 'transfer-encoding'}}});
+- true ->
+- {ok, list_to_tuple(
+- lists:reverse([Body, ResponseHeaderRcord | Result]))}
+- end
+- end;
+- false ->
+- throw({error, {header_too_long, MaxHeaderSize,
+- MaxHeaderSize-Length}})
++ lists:reverse([Body, ResponseHeaderRcord | Result]))}
++ end
+ end;
+-parse_headers(<<?CR,?LF,?CR>> = Data, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- {?MODULE, parse_headers, [Data, Header, Headers,
+- MaxHeaderSize, Result, Relaxed]};
+-parse_headers(<<?CR,?LF>> = Data, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- {?MODULE, parse_headers, [Data, Header, Headers, MaxHeaderSize,
+- Result, Relaxed]};
++parse_headers(<<?CR,?LF,?CR>> = Data, Header, Headers,
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ {?MODULE, parse_headers, [Data, Header, Headers,
++ MaxHeaderSize, CurrentSize, Result, Relaxed]};
++parse_headers(<<?CR,?LF>> = Data, Header, Headers,
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ {?MODULE, parse_headers, [Data, Header, Headers, MaxHeaderSize, CurrentSize,
++ Result, Relaxed]};
+ parse_headers(<<?CR,?LF, Octet, Rest/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- parse_headers(Rest, [Octet],
+- [lists:reverse(Header) | Headers], MaxHeaderSize,
+- Result, Relaxed);
+-parse_headers(<<?CR>> = Data, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- {?MODULE, parse_headers, [Data, Header, Headers, MaxHeaderSize,
+- Result, Relaxed]};
+-
+-parse_headers(<<?LF>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- %% If ?CR is is missing RFC2616 section-19.3
+- parse_headers(<<?CR, ?LF>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed);
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ parse_headers(Rest, [Octet],
++ [lists:reverse(Header) | Headers], MaxHeaderSize, CurrentSize + 3,
++ Result, Relaxed);
++parse_headers(<<?CR>> = Data, Header, Headers,
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ {?MODULE, parse_headers, [Data, Header, Headers, MaxHeaderSize, CurrentSize,
++ Result, Relaxed]};
++
++parse_headers(<<?LF>>, Header, Headers,
++ MaxHeaderSize, CurrentSize, Result, Relaxed) ->
++ %% If ?CR is is missing RFC2616 section-19.3
++ parse_headers(<<?CR, ?LF>>, Header, Headers,
++ MaxHeaderSize, CurrentSize, Result, Relaxed);
+
+ parse_headers(<<Octet, Rest/binary>>, Header, Headers,
+- MaxHeaderSize, Result, Relaxed) ->
+- parse_headers(Rest, [Octet | Header], Headers, MaxHeaderSize,
+- Result, Relaxed).
+-
++ MaxHeaderSize, CurrentSize, Result, Relaxed)
++ when (is_integer(MaxHeaderSize) andalso CurrentSize < MaxHeaderSize);
++ MaxHeaderSize =:= nolimit ->
++ parse_headers(Rest, [Octet | Header], Headers, MaxHeaderSize,
++ CurrentSize + 1, Result, Relaxed);
++parse_headers(<<_Octet, _Rest/binary>>, _UnfinalizedHeader, _Headers,
++ MaxHeaderSize, _CurrentSize, _Result, _Relaxed) ->
++ throw({error, {header_too_long, {max, MaxHeaderSize}}}).
+
+ %% RFC2616, Section 10.1.1
+ %% Note:
+diff --git a/lib/inets/src/http_lib/http_response.erl b/lib/inets/src/http_lib/http_response.erl
+index cbdea82523..2d616dddc9 100644
+--- a/lib/inets/src/http_lib/http_response.erl
++++ b/lib/inets/src/http_lib/http_response.erl
+@@ -125,7 +125,10 @@ headers("content-encoding", Value, Headers) ->
+ headers("content-language", Value, Headers) ->
+ Headers#http_response_h{'content-language' = Value};
+ headers("content-length", Value, Headers) ->
+- Headers#http_response_h{'content-length' = Value};
++ case is_valid_content_length(Value) of
++ true -> Headers#http_response_h{'content-length' = Value};
++ false -> throw({error, {invalid_content_length, Value}})
++ end;
+ headers("content-location", Value, Headers) ->
+ Headers#http_response_h{'content-location' = Value};
+ headers("content-md5", Value, Headers) ->
+@@ -221,3 +224,8 @@ key_value_tuple(_, undefined) ->
+ undefined;
+ key_value_tuple(Key, Value) ->
+ {Key, Value}.
++
++is_valid_content_length("") ->
++ false;
++is_valid_content_length(Value) ->
++ lists:all(fun(C) -> C >= $0 andalso C =< $9 end, Value).
+diff --git a/lib/inets/test/httpc_SUITE.erl b/lib/inets/test/httpc_SUITE.erl
+index b31f5d9eec..9de9eccda6 100644
+--- a/lib/inets/test/httpc_SUITE.erl
++++ b/lib/inets/test/httpc_SUITE.erl
+@@ -157,7 +157,7 @@ real_requests_esi() ->
+
+ simulated_unix_socket() ->
+ [unix_domain_socket,
+- invalid_ipfamily_unix_socket].
++ invalid_ipfamily_unix_socket].
+
+ only_simulated() ->
+ [
+@@ -209,7 +209,10 @@ only_simulated() ->
+ get_space,
+ delete_no_body,
+ post_with_content_type,
+- stream_fun_server_close
++ stream_fun_server_close,
++ abnormal_header_size,
++ invalid_content_length,
++ abnormal_trailer_size
+ ].
+
+ server_closing_connection() ->
+@@ -1361,7 +1364,7 @@ headers_conflict_chunked_with_length(doc) ->
+ headers_conflict_chunked_with_length(Config) when is_list(Config) ->
+ Request = {url(group_name(Config), "/headers_conflict_chunked_with_length.html", Config), []},
+ RequestOpts = proplists:get_value(request_opts, Config, []),
+- {error, {could_not_parse_as_http, _}} = httpc:request(get, Request, [{relaxed, false}, ?SSL_NO_VERIFY], RequestOpts),
++ {error, {headers_conflict, _}} = httpc:request(get, Request, [{relaxed, false}, ?SSL_NO_VERIFY], RequestOpts),
+ {ok,{{_,200,_},_,_}} = httpc:request(get, Request, [{relaxed, true}, ?SSL_NO_VERIFY], RequestOpts),
+ ok.
+
+@@ -2080,6 +2083,104 @@ def_ssl_opt(_Config) ->
+ ok.
+
+ %%-------------------------------------------------------------------------
++abnormal_header_size() ->
++ [{doc, "httpc has two options to protect against unreasonable amounts of"
++ "data to be parsed; namely max_header_size and max_body_size which"
++ "default to 10240 and nolimit"}].
++abnormal_header_size(Config) ->
++ RequestNormal = {url(group_name(Config), "/normal_header_size_restricted.html", Config), []},
++ RequestAbnormal = {url(group_name(Config), "/abnormal_header_size.html", Config), []},
++ RequestBoundary = {url(group_name(Config), "/boundary_header_size.html", Config), []},
++ RequestNormalBigBody = {url(group_name(Config), "/nomal_header_size_big_body.html", Config), []},
++ Profile = ?profile(Config),
++
++ %% Normal response passes with explicit max_header_size
++ {ok, {{_, 200, _}, _Headers, _Body}} =
++ httpc:request(get, RequestNormal,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, 4096}],
++ Profile),
++ %% Rejected when max_header_size is artificially low
++ {error, {header_too_long, {max, 16}}} =
++ httpc:request(get, RequestNormal,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, 16}],
++ Profile),
++ %% Abnormal response (>10240 total header bytes) rejected with default limit
++ {error, {header_too_long, {max, ?HTTP_MAX_HEADER_SIZE}}} =
++ httpc:request(get, RequestAbnormal,
++ [?SSL_NO_VERIFY],
++ [],
++ Profile),
++ %% Boundary: one byte under limit fails, exactly at limit passes
++ {error, {header_too_long, _}} =
++ httpc:request(get, RequestBoundary,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, 135}],
++ Profile),
++ {ok, {{_, 200, _}, _, _}} =
++ httpc:request(get, RequestBoundary,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, 136}],
++ Profile),
++
++ %% max_body_size rejects oversized body
++ {error, body_too_big} =
++ httpc:request(get, RequestNormalBigBody,
++ [?SSL_NO_VERIFY],
++ [{max_body_size, 1000}],
++ Profile),
++
++%% nolimit bypasses the check (backward compatibility)
++ {ok, {{_, 200, _}, _, _}} =
++ httpc:request(get, RequestAbnormal,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, nolimit},
++ {body_format, binary}],
++ Profile),
++ ok.
++
++%%-------------------------------------------------------------------------
++invalid_content_length() ->
++ [{doc, "Malformed Content-Length value is rejected during header parsing"}].
++invalid_content_length(Config) ->
++ Request = {url(group_name(Config), "/invalid_content_length.html", Config),
++ [{"connection", "close"}]},
++ Profile = ?profile(Config),
++ {error, {invalid_content_length, _}} =
++ httpc:request(get, Request, [?SSL_NO_VERIFY], [], Profile),
++ ok.
++
++%%-------------------------------------------------------------------------
++abnormal_trailer_size() ->
++ [{doc, "Chunked trailers are bounded by the same max_header_size option"}].
++abnormal_trailer_size(Config) ->
++ RequestNormal = {url(group_name(Config), "/chunked_trailer_normal.html", Config), []},
++ RequestAbnormal = {url(group_name(Config), "/chunked_trailer_abnormal.html", Config), []},
++ Profile = ?profile(Config),
++
++ %% Normal chunked response with small trailers passes
++ {ok, {{_, 200, _}, _Headers, _Body}} =
++ httpc:request(get, RequestNormal,
++ [?SSL_NO_VERIFY],
++ [],
++ Profile),
++
++ %% Chunked response with oversized trailers rejected
++ {error, {header_too_long, {max, _}}} =
++ httpc:request(get, RequestAbnormal,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, 64}],
++ Profile),
++
++ %% Same oversized trailers pass with nolimit
++ {ok, {{_, 200, _}, _, _}} =
++ httpc:request(get, RequestAbnormal,
++ [?SSL_NO_VERIFY],
++ [{max_header_size, nolimit}],
++ Profile),
++ ok.
++
+ remote_socket_close_parallel() ->
+ [{doc,
+ "Verify remote socket closure (related tickets: OTP-18509, OTP-18545,"
+@@ -3166,6 +3267,62 @@ handle_uri(_,"/delete_no_body.html", _,Headers,_, DefaultResponse) ->
+ not_found ->
+ DefaultResponse
+ end;
++handle_uri(_, "/normal_header_size_restricted.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Content-Length:150\r\n" ++
++ "Connection:close\r\n" ++
++ "\r\n" ++
++ lists:flatten(["OK " || _ <- lists:seq(1,50)]);
++
++handle_uri(_, "/boundary_header_size.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Content-Length:2\r\n" ++
++ "Connection:close\r\n" ++
++ "X-Pad:" ++ lists:duplicate(94, $A) ++ "\r\n" ++
++ "\r\n" ++
++ "OK";
++
++handle_uri(_, "/abnormal_header_size.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Content-Length:23\r\n" ++
++ "X-Pad:" ++ lists:duplicate(10241, $0) ++ "\r\n" ++
++ "Connection: close\r\n" ++
++ "\r\n" ++
++ "This should not be read";
++handle_uri(_, "/nomal_header_size_big_body.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Content-Length:20000\r\n" ++
++ "Connection:close\r\n" ++
++ "\r\n" ++
++ lists:duplicate(20000, $A);
++
++handle_uri(_, "/invalid_content_length.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Content-Length:abc\r\n" ++
++ "Connection:close\r\n" ++
++ "\r\n" ++
++ "body";
++
++handle_uri(_, "/chunked_trailer_normal.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Transfer-Encoding: chunked\r\n" ++
++ "Connection:close\r\n" ++
++ "\r\n" ++
++ "5\r\nhello\r\n" ++
++ "0\r\n" ++
++ "X-Checksum: abc123\r\n" ++
++ "\r\n";
++
++handle_uri(_, "/chunked_trailer_abnormal.html", _, _, _, _) ->
++ "HTTP/1.1 200 OK\r\n" ++
++ "Transfer-Encoding: chunked\r\n" ++
++ "Connection:close\r\n" ++
++ "\r\n" ++
++ "5\r\nhello\r\n" ++
++ "0\r\n" ++
++ "X-Huge:" ++ lists:duplicate(200, $B) ++ "\r\n" ++
++ "\r\n";
++
+ handle_uri(_,_,_,_,_,DefaultResponse) ->
+ DefaultResponse.
+
+diff --git a/lib/snmp/src/misc/snmp_pdus.erl b/lib/snmp/src/misc/snmp_pdus.erl
+index 1967c7078d..3f8c352974 100644
+--- a/lib/snmp/src/misc/snmp_pdus.erl
++++ b/lib/snmp/src/misc/snmp_pdus.erl
+@@ -265,7 +265,7 @@ dec_value([5,0 | T]) ->
+
+ %% INTEGER
+ dec_value([2 | Bytes]) ->
+- {Value, Rest} = dec_integer_notag(Bytes),
++ {Value, Rest} = dec_integer_notag(Bytes, 4), %% SMI INTEGER is 32-bit
+ {{'INTEGER', Value}, Rest};
+
+ %% OCTET STRING
+@@ -282,7 +282,7 @@ dec_value([64 | Bytes]) ->
+ dec_value([65 | Bytes]) ->
+ %% Counter32 is an unsigned 32 but is actually encoded as
+ %% a signed integer 32 (INTEGER).
+- {Value, Rest} = dec_integer_notag(Bytes),
++ {Value, Rest} = dec_integer_notag(Bytes, 5),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+@@ -298,7 +298,7 @@ dec_value([65 | Bytes]) ->
+
+ %% Unsigned32
+ dec_value([66 | Bytes]) ->
+- {Value, Rest} = dec_integer_notag(Bytes),
++ {Value, Rest} = dec_integer_notag(Bytes, 5),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+@@ -312,7 +312,7 @@ dec_value([66 | Bytes]) ->
+
+ %% TimeTicks
+ dec_value([67 | Bytes]) ->
+- {Value, Rest} = dec_integer_notag(Bytes),
++ {Value, Rest} = dec_integer_notag(Bytes, 5),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+@@ -333,7 +333,7 @@ dec_value([68 | Bytes]) ->
+ dec_value([70 | Bytes]) ->
+ %% Counter64 is an unsigned 64 but is actually encoded as
+ %% a signed integer 64.
+- {Value, Rest} = dec_integer_notag(Bytes),
++ {Value, Rest} = dec_integer_notag(Bytes, 9),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value < 16#8000000000000000) ->
+diff --git a/lib/stdlib/src/uri_string.erl b/lib/stdlib/src/uri_string.erl
+index 7d24a0dba9..c88ad981fc 100644
+--- a/lib/stdlib/src/uri_string.erl
++++ b/lib/stdlib/src/uri_string.erl
+@@ -1364,12 +1364,14 @@ calculate_parsed_query_fragment(Input, Unparsed) ->
+
+ get_port(<<>>) ->
+ undefined;
+-get_port(B) ->
++get_port(B) when byte_size(B) =< 5 ->
+ try binary_to_integer(B)
+ catch
+ error:badarg ->
+ throw({error, invalid_uri, B})
+- end.
++ end;
++get_port(B) ->
++ throw({error, invalid_uri, B}).
+
+
+ %% Strip last char if it is in list
diff --git a/otp-0028-snmp-Bound-integer-parsing-in-the-BER-decoder.patch b/otp-0028-snmp-Bound-integer-parsing-in-the-BER-decoder.patch
new file mode 100644
index 0000000..73688e0
--- /dev/null
+++ b/otp-0028-snmp-Bound-integer-parsing-in-the-BER-decoder.patch
@@ -0,0 +1,672 @@
+From: Konrad Pietrzak <konrad@erlang.org>
+Date: Wed, 30 Sep 2026 15:06:20 +0200
+Subject: [PATCH] snmp: Bound integer parsing in the BER decoder
+
+Bounding the varbind value types was only half the job. Every
+dec_int_tag/1 call site was still unbounded, so the v3 header fields, the
+USM security parameters and all PDU integer fields accepted an arbitrary
+number of BER content octets and built a bignum from them.
+msgAuthoritativeEngineBoots and msgAuthoritativeEngineTime are parsed
+before the message is authenticated, so that input is reachable pre-auth.
+
+Give every integer field the content octet limit its type implies, named
+after the type rather than spelled as a literal: four octets for the
+INTEGER (0..2147483647) and Integer32 fields, five for the unsigned 32-bit
+types, nine for Counter64. Remove the unlimited dec_int_tag/1 and
+dec_integer_notag/1 wrappers so no call site can silently omit a limit,
+and with them the infinity clause of dec_integer_notag/2, which is
+unreachable once every caller passes a limit.
+
+Signal a violation with exit rather than throw. All callers wrap decoding
+in (catch ...) and match {'EXIT', Reason}; a thrown term is returned bare
+and matched neither clause, so an over-long integer produced a case_clause
+in snmpa_mpd instead of a discarded packet and an snmpInASNParseErrs
+increment. Fields that re-tag the failure keep the {Size, Limit} pair and
+use a distinct _bytesize suffix, so a length violation cannot be confused
+with the value rejections from chk_msg_id/1 and friends.
+
+dec_Counter64/2 had a second, separate signalling bug: it reported an
+over-long Counter64 as throw({exit, {bad_counter64_length, BadSize}}), a
+term no caller can match on either count. It now exits with the same
+{bad_integer, {Size, Limit}} reason as every other integer field.
+
+The chk_msg_id/1, chk_msg_max_size/1 and chk_msg_sec_model/1 range checks
+are kept alongside the new limits. An octet cap is not a range check: four
+legal octets still encode a negative msgID, and one octet still encodes a
+msgMaxSize below the RFC 3412 floor of 484.
+
+Related: GHSA-8qw4-2chm-mvj2
+Aux Id: OTP-20346
+
+Part of the fix for CVE-2026-59696.
+
+(cherry picked from commit 2cf26f2238c904f5e7a621b971442e2c7b77db1a)
+
+[Backport to OTP 26: OTP 26 has no dec_Counter64/snmp_pdus_basic codec
+and decodes Counter64 inline, so the dec_Counter64/2 change is replaced
+by using ?UINT64_MAX_OCTETS for the inline Counter64 limit added by the
+previous commit. All other hunks ported as-is.]
+
+Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
+Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
+
+diff --git a/lib/snmp/src/misc/snmp_pdus.erl b/lib/snmp/src/misc/snmp_pdus.erl
+index 3f8c352974..2d12e1c31b 100644
+--- a/lib/snmp/src/misc/snmp_pdus.erl
++++ b/lib/snmp/src/misc/snmp_pdus.erl
+@@ -26,6 +26,16 @@
+ -define(VMODULE,"PDUS").
+ -include("snmp_verbosity.hrl").
+
++%% Maximum number of content octets accepted for a BER-encoded integer.
++%% Each value is the minimal BER length of the largest legal value of the
++%% type. Unsigned types need one octet more than their width, for the
++%% leading zero that keeps the value positive.
++-define(INT32_MAX_OCTETS, 4). %% ASN.1 INTEGER / Integer32 and every
++ %% INTEGER (0..2147483647) field
++-define(UINT32_MAX_OCTETS, 5). %% Counter32, Gauge32/Unsigned32, TimeTicks
++-define(UINT64_MAX_OCTETS, 9). %% Counter64
++-define(VERSION_MAX_OCTETS, 10). %% msgVersion -- deliberately generous
++
+ %% See RFC1155, RFC1157, RFC1901, RFC1902, RFC1905, RFC2272
+
+
+@@ -67,11 +77,11 @@ dec_message_only([48 | Bytes]) ->
+ end.
+
+ dec_snmp_version(Bytes) ->
+- case (catch dec_int_tag(Bytes, 10)) of
+- {error, {bad_integer, BadInt}} ->
+- exit({bad_version, BadInt});
++ case (catch dec_int_tag(Bytes, ?VERSION_MAX_OCTETS)) of
+ {SNMPversion, Rest} when is_integer(SNMPversion) andalso is_list(Rest) ->
+ {dec_snmp_ver(SNMPversion), Rest};
++ {'EXIT', {error, {bad_integer, BadInt}}} ->
++ exit({bad_version, BadInt});
+ {'EXIT', Reason} ->
+ exit(Reason)
+ end.
+@@ -99,12 +109,18 @@ dec_rest_v3_msg_only([48 | Bytes]) -> % starts with header data sequence
+ {Size, Tail} = dec_len(Bytes),
+ {HBytes, Bytes1} = split_at(Tail, Size, []),
+ %% Decode HeaderData
+- {MsgID, HBytes1} = dec_int_tag(HBytes),
++ {MsgID, HBytes1} = try dec_int_tag(HBytes, ?INT32_MAX_OCTETS)
++ catch exit:{error, {bad_integer, BadSizeMsgId}} -> exit({bad_msg_id_bytesize, BadSizeMsgId})
++ end,
+ chk_msg_id(MsgID),
+- {MsgMaxSize, HBytes2} = dec_int_tag(HBytes1),
++ {MsgMaxSize, HBytes2} = try dec_int_tag(HBytes1, ?INT32_MAX_OCTETS)
++ catch exit:{error, {bad_integer, BadSizeMaxSize}} -> exit({bad_msg_max_size_bytesize, BadSizeMaxSize})
++ end,
+ chk_msg_max_size(MsgMaxSize),
+ {MsgFlags, HBytes3} = dec_oct_str_tag(HBytes2),
+- {MsgSecurityModel, []} = dec_int_tag(HBytes3),
++ {MsgSecurityModel, []} = try dec_int_tag(HBytes3, ?INT32_MAX_OCTETS)
++ catch exit:{error, {bad_integer, BadSizeSecModel}} -> exit({bad_sec_model_bytesize, BadSizeSecModel})
++ end,
+ chk_msg_sec_model(MsgSecurityModel),
+ %% Continue with Message
+ % {MsgSecurityParameters, Bytes2} = dec_oct_str_tag(Bytes1),
+@@ -176,8 +192,8 @@ dec_pdu([164 | Bytes]) -> % It's a trap
+ Bytes2 = get_data_bytes(Bytes),
+ {Enterprise, Rest1} = dec_oid_tag(Bytes2),
+ {{'IpAddress', [_, _, _, _] = AgentAddr}, Rest2} = dec_value(Rest1),
+- {GenericTrap, Rest3} = dec_int_tag(Rest2),
+- {SpecificTrap, Rest4} = dec_int_tag(Rest3),
++ {GenericTrap, Rest3} = dec_int_tag(Rest2, ?INT32_MAX_OCTETS),
++ {SpecificTrap, Rest4} = dec_int_tag(Rest3, ?INT32_MAX_OCTETS),
+ {{'TimeTicks', TimeStamp}, VBBytes} = dec_value(Rest4),
+ VBs = dec_VBs(VBBytes),
+ #trappdu{enterprise = Enterprise, agent_addr = AgentAddr,
+@@ -186,9 +202,9 @@ dec_pdu([164 | Bytes]) -> % It's a trap
+
+ dec_pdu([165 | Bytes]) -> % Bulk
+ Bytes2 = get_data_bytes(Bytes),
+- {RequestID, Rest1} = dec_int_tag(Bytes2),
+- {NonRepeaters, Rest2} = dec_int_tag(Rest1),
+- {MaxRepetitions,VBbytes} = dec_int_tag(Rest2),
++ {RequestID, Rest1} = dec_int_tag(Bytes2, ?INT32_MAX_OCTETS),
++ {NonRepeaters, Rest2} = dec_int_tag(Rest1, ?INT32_MAX_OCTETS),
++ {MaxRepetitions,VBbytes} = dec_int_tag(Rest2, ?INT32_MAX_OCTETS),
+ VBs = dec_VBs(VBbytes),
+ #pdu{type = 'get-bulk-request', request_id = RequestID,
+ error_status = NonRepeaters, error_index = MaxRepetitions,
+@@ -197,15 +213,15 @@ dec_pdu([165 | Bytes]) -> % Bulk
+ dec_pdu([PduTag | Bytes]) ->
+ Type = dec_pdu_tag(PduTag),
+ Bytes2 = get_data_bytes(Bytes),
+- {RequestID, Rest1} = dec_int_tag(Bytes2),
+- {ErrStat, Rest2} = dec_int_tag(Rest1),
++ {RequestID, Rest1} = dec_int_tag(Bytes2, ?INT32_MAX_OCTETS),
++ {ErrStat, Rest2} = dec_int_tag(Rest1, ?INT32_MAX_OCTETS),
+ ErrStatus = case lists:keysearch(ErrStat, 2, errMsgs()) of
+ {value, {ErrStatName, _ErrStat}} ->
+ ErrStatName;
+ false ->
+ ErrStat
+ end,
+- {ErrIndex, VarbindsBytes} = dec_int_tag(Rest2),
++ {ErrIndex, VarbindsBytes} = dec_int_tag(Rest2, ?INT32_MAX_OCTETS),
+ VBs = dec_VBs(VarbindsBytes),
+ #pdu{type = Type, request_id = RequestID, error_status = ErrStatus,
+ error_index = ErrIndex, varbinds = VBs}.
+@@ -231,8 +247,14 @@ dec_individual_VBs([48 | Bytes], OrgIndex, AccVBs) ->
+ dec_usm_security_parameters([48 | Bytes1]) ->
+ {_Len, Bytes2} = dec_len(Bytes1),
+ {MsgAuthEngineID, Bytes3} = dec_oct_str_tag(Bytes2),
+- {MsgAuthEngineBoots, Bytes4} = dec_int_tag(Bytes3),
+- {MsgAuthEngineTime, Bytes5} = dec_int_tag(Bytes4),
++ {MsgAuthEngineBoots, Bytes4} = try dec_int_tag(Bytes3, ?INT32_MAX_OCTETS)
++ catch
++ exit:{error, {bad_integer, SizeBoots}} -> exit({bad_engine_boots_bytesize, SizeBoots})
++ end,
++ {MsgAuthEngineTime, Bytes5} = try dec_int_tag(Bytes4, ?INT32_MAX_OCTETS)
++ catch
++ exit:{error, {bad_integer, SizeTime}} -> exit({bad_engine_time_bytesize, SizeTime})
++ end,
+ {MsgUserName, Bytes6} = dec_oct_str_tag(Bytes5),
+ {MsgAuthParams, Bytes7} = dec_oct_str_tag(Bytes6),
+ {MsgPrivParams, []} = dec_oct_str_tag(Bytes7),
+@@ -265,7 +287,7 @@ dec_value([5,0 | T]) ->
+
+ %% INTEGER
+ dec_value([2 | Bytes]) ->
+- {Value, Rest} = dec_integer_notag(Bytes, 4), %% SMI INTEGER is 32-bit
++ {Value, Rest} = dec_integer_notag(Bytes, ?INT32_MAX_OCTETS), %% SMI INTEGER is 32-bit
+ {{'INTEGER', Value}, Rest};
+
+ %% OCTET STRING
+@@ -282,7 +304,7 @@ dec_value([64 | Bytes]) ->
+ dec_value([65 | Bytes]) ->
+ %% Counter32 is an unsigned 32 but is actually encoded as
+ %% a signed integer 32 (INTEGER).
+- {Value, Rest} = dec_integer_notag(Bytes, 5),
++ {Value, Rest} = dec_integer_notag(Bytes, ?UINT32_MAX_OCTETS),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+@@ -298,7 +320,7 @@ dec_value([65 | Bytes]) ->
+
+ %% Unsigned32
+ dec_value([66 | Bytes]) ->
+- {Value, Rest} = dec_integer_notag(Bytes, 5),
++ {Value, Rest} = dec_integer_notag(Bytes, ?UINT32_MAX_OCTETS),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+@@ -312,7 +334,7 @@ dec_value([66 | Bytes]) ->
+
+ %% TimeTicks
+ dec_value([67 | Bytes]) ->
+- {Value, Rest} = dec_integer_notag(Bytes, 5),
++ {Value, Rest} = dec_integer_notag(Bytes, ?UINT32_MAX_OCTETS),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value =< 16#ffffffff) ->
+@@ -333,7 +355,7 @@ dec_value([68 | Bytes]) ->
+ dec_value([70 | Bytes]) ->
+ %% Counter64 is an unsigned 64 but is actually encoded as
+ %% a signed integer 64.
+- {Value, Rest} = dec_integer_notag(Bytes, 9),
++ {Value, Rest} = dec_integer_notag(Bytes, ?UINT64_MAX_OCTETS),
+ Value2 =
+ if
+ (Value >= 0) andalso (Value < 16#8000000000000000) ->
+@@ -375,22 +397,16 @@ split_at([H|T], N, Acc) ->
+ %% All decoding routines return: {Data, RestBytes}
+ %%----------------------------------------------------------------------
+
+-dec_int_tag([2 | Bytes]) ->
+- dec_integer_notag(Bytes).
+ dec_int_tag([2 | Bytes], SizeLimit) ->
+ dec_integer_notag(Bytes, SizeLimit).
+
+-dec_integer_notag(Ints) ->
+- dec_integer_notag(Ints, infinity).
+ dec_integer_notag(Ints, SizeLimit) ->
+ case dec_len(Ints) of
+- {Size, Ints2} when SizeLimit =:= infinity ->
+- do_dec_integer_notag(Size, Ints2);
+ {Size, Ints2} when (is_integer(SizeLimit) andalso
+ (Size =< SizeLimit)) ->
+ do_dec_integer_notag(Size, Ints2);
+ {BadSize, _BadInts2} ->
+- throw({error, {bad_integer, {BadSize, SizeLimit}}})
++ exit({error, {bad_integer, {BadSize, SizeLimit}}})
+ end.
+
+ do_dec_integer_notag(Size, Ints) ->
+diff --git a/lib/snmp/test/snmp_pdus_SUITE.erl b/lib/snmp/test/snmp_pdus_SUITE.erl
+index d70e7aebd0..37b2f73f5e 100644
+--- a/lib/snmp/test/snmp_pdus_SUITE.erl
++++ b/lib/snmp/test/snmp_pdus_SUITE.erl
+@@ -29,6 +29,7 @@
+ %%----------------------------------------------------------------------
+ -include_lib("common_test/include/ct.hrl").
+ -include("snmp_test_lib.hrl").
++-define(SNMP_USE_V3, true).
+ -include_lib("snmp/include/snmp_types.hrl").
+
+
+@@ -45,7 +46,13 @@
+ otp7575/1,
+ otp8563/1,
+ otp9022/1,
+- otp10132/1
++ otp10132/1,
++
++ dec_value_int_size_limits/1,
++ dec_pdu_int_size_limits/1,
++ dec_v3_hdr_int_size_limits/1,
++ dec_v3_hdr_value_checks/1,
++ dec_usm_sec_params_int_size_limits/1
+ ]).
+
+
+@@ -57,10 +64,12 @@ suite() ->
+ [{ct_hooks, [ts_install_cth]}].
+
+ all() ->
+- [{group, tickets}].
++ [{group, tickets},
++ {group, ber_limits}].
+
+ groups() ->
+- [{tickets, [], tickets_cases()}].
++ [{tickets, [], tickets_cases()},
++ {ber_limits, [], ber_limits_cases()}].
+
+ tickets_cases() ->
+ [
+@@ -70,6 +79,15 @@ tickets_cases() ->
+ otp10132
+ ].
+
++ber_limits_cases() ->
++ [
++ dec_value_int_size_limits,
++ dec_pdu_int_size_limits,
++ dec_v3_hdr_int_size_limits,
++ dec_v3_hdr_value_checks,
++ dec_usm_sec_params_int_size_limits
++ ].
++
+
+ %%
+ %% -----
+@@ -387,6 +405,287 @@ otp10132(Config) when is_list(Config) ->
+ ok.
+
+
++%%======================================================================
++%% BER integer content octet limits
++%%======================================================================
++
++%% snmp_pdus caps the number of BER content octets accepted for every
++%% integer-valued field (?INT32_MAX_OCTETS and friends). The cases below
++%% pin, for each field, the largest accepted encoding and the rejection of
++%% one octet more.
++%%
++%% They also pin that the rejection is an *exit*. It used to be a throw,
++%% which slipped through the (catch ...) wrappers in snmpa_mpd -- e.g.
++%% around dec_scoped_pdu/1 in v3_proc/6 -- and produced a case_clause
++%% instead of a discarded packet. dec_class/1 reports the exception class,
++%% so a regression back to throw fails the case instead of passing
++%% silently.
++
++dec_value_int_size_limits(suite) -> [];
++dec_value_int_size_limits(doc) ->
++ ["Content octet limits for the integer types decoded by dec_value/1"];
++dec_value_int_size_limits(Config) when is_list(Config) ->
++ %% {Type, BER tag, max content octets}. The unsigned types allow one
++ %% octet more than their width, for the leading zero that keeps the
++ %% value positive.
++ Types = [{'INTEGER', 2, 4},
++ {'Counter32', 65, 5},
++ {'Unsigned32', 66, 5},
++ {'TimeTicks', 67, 5},
++ {'Counter64', 70, 9}],
++ lists:foreach(
++ fun({Type, Tag, Max}) ->
++ ?IPRINT("~w: ~w content octets is accepted", [Type, Max]),
++ case snmp_pdus:dec_value(padded_value(Tag, Max)) of
++ {{Type, 1}, []} ->
++ ok;
++ UnexpectedOk ->
++ exit({unexpected_decode_result, Type, Max, UnexpectedOk})
++ end,
++
++ ?IPRINT("~w: ~w content octets is rejected", [Type, Max + 1]),
++ case dec_class(fun() ->
++ snmp_pdus:dec_value(
++ padded_value(Tag, Max + 1))
++ end) of
++ {exit, {error, {bad_integer, {Bad, Max}}}} when Bad =:= Max + 1 ->
++ ok;
++ Unexpected ->
++ exit({unexpected_decode_result, Type, Max + 1, Unexpected})
++ end
++ end, Types),
++ ?IPRINT("done"),
++ ok.
++
++
++dec_pdu_int_size_limits(suite) -> [];
++dec_pdu_int_size_limits(doc) ->
++ ["Content octet limits for the integer fields of PDU, BulkPDU and TrapPDU"];
++dec_pdu_int_size_limits(Config) when is_list(Config) ->
++ %% RFC 3416: request-id is INTEGER (-2147483648..2147483647) and
++ %% error-index, non-repeaters and max-repetitions are
++ %% INTEGER (0..max-bindings) with max-bindings = 2147483647 -- so four
++ %% content octets each.
++ ?IPRINT("get-request: a well formed PDU decodes"),
++ #pdu{type = 'get-request',
++ request_id = 1,
++ error_status = noError,
++ error_index = 0,
++ varbinds = []} =
++ snmp_pdus:dec_pdu(pdu(160, [int_tlv(1, 4),
++ int_tlv(0, 1),
++ int_tlv(0, 1)])),
++
++ ?IPRINT("get-request: request-id with 5 content octets is rejected"),
++ expect_bad_integer(request_id, {5, 4},
++ fun() ->
++ snmp_pdus:dec_pdu(pdu(160, [int_tlv(1, 5),
++ int_tlv(0, 1),
++ int_tlv(0, 1)]))
++ end),
++
++ %% error-status is an enumerated INTEGER (noError(0)..inconsistentName(18)),
++ %% so one content octet carries every legal value. The exact cap is not
++ %% pinned here -- only that a grossly oversized encoding is rejected --
++ %% because unrecognised values are deliberately passed through by
++ %% dec_pdu/1 and the cap may be tightened without changing behaviour.
++ ?IPRINT("get-request: error-status with 8 content octets is rejected"),
++ case dec_class(fun() ->
++ snmp_pdus:dec_pdu(pdu(160, [int_tlv(1, 1),
++ int_tlv(0, 8),
++ int_tlv(0, 1)]))
++ end) of
++ {exit, {error, {bad_integer, {8, _}}}} ->
++ ok;
++ UnexpectedErrStatus ->
++ exit({unexpected_decode_result, error_status, UnexpectedErrStatus})
++ end,
++
++ ?IPRINT("get-request: error-index with 5 content octets is rejected"),
++ expect_bad_integer(error_index, {5, 4},
++ fun() ->
++ snmp_pdus:dec_pdu(pdu(160, [int_tlv(1, 1),
++ int_tlv(0, 1),
++ int_tlv(0, 5)]))
++ end),
++
++ ?IPRINT("get-bulk-request: a well formed PDU decodes"),
++ #pdu{type = 'get-bulk-request',
++ request_id = 1,
++ error_status = 0,
++ error_index = 10,
++ varbinds = []} =
++ snmp_pdus:dec_pdu(pdu(165, [int_tlv(1, 4),
++ int_tlv(0, 1),
++ int_tlv(10, 1)])),
++
++ ?IPRINT("get-bulk-request: non-repeaters with 5 content octets is rejected"),
++ expect_bad_integer(non_repeaters, {5, 4},
++ fun() ->
++ snmp_pdus:dec_pdu(pdu(165, [int_tlv(1, 1),
++ int_tlv(0, 5),
++ int_tlv(0, 1)]))
++ end),
++
++ ?IPRINT("get-bulk-request: max-repetitions with 5 content octets is rejected"),
++ expect_bad_integer(max_repetitions, {5, 4},
++ fun() ->
++ snmp_pdus:dec_pdu(pdu(165, [int_tlv(1, 1),
++ int_tlv(0, 1),
++ int_tlv(0, 5)]))
++ end),
++
++ ?IPRINT("trap: a well formed TrapPDU decodes"),
++ #trappdu{generic_trap = 6,
++ specific_trap = 1,
++ time_stamp = 0,
++ varbinds = []} =
++ snmp_pdus:dec_pdu(trap_pdu(int_tlv(6, 1), int_tlv(1, 4))),
++
++ ?IPRINT("trap: generic-trap with 5 content octets is rejected"),
++ expect_bad_integer(generic_trap, {5, 4},
++ fun() ->
++ snmp_pdus:dec_pdu(
++ trap_pdu(int_tlv(6, 5), int_tlv(1, 1)))
++ end),
++
++ ?IPRINT("trap: specific-trap with 5 content octets is rejected"),
++ expect_bad_integer(specific_trap, {5, 4},
++ fun() ->
++ snmp_pdus:dec_pdu(
++ trap_pdu(int_tlv(6, 1), int_tlv(1, 5)))
++ end),
++
++ ?IPRINT("done"),
++ ok.
++
++
++dec_v3_hdr_int_size_limits(suite) -> [];
++dec_v3_hdr_int_size_limits(doc) ->
++ ["Content octet limits for the v3 header data integer fields"];
++dec_v3_hdr_int_size_limits(Config) when is_list(Config) ->
++ %% RFC 3412: msgID and msgMaxSize are INTEGER (0..2147483647) and
++ %% msgSecurityModel is INTEGER (1..2147483647) -- four content octets.
++ ?IPRINT("the largest legal msgID is accepted"),
++ #message{version = 'version-3',
++ vsn_hdr = #v3_hdr{msgID = 2147483647,
++ msgMaxSize = 484,
++ msgSecurityModel = 3}} =
++ snmp_pdus:dec_message_only(v3_msg([raw_int_tlv([127, 255, 255, 255]),
++ v3_msg_max_size_tlv(),
++ v3_msg_flags_tlv(),
++ v3_sec_model_tlv()])),
++
++ ?IPRINT("msgID with 5 content octets is rejected"),
++ expect_exit(msg_id, {bad_msg_id_bytesize, {5, 4}},
++ fun() ->
++ snmp_pdus:dec_message_only(
++ v3_msg([int_tlv(1, 5),
++ v3_msg_max_size_tlv(),
++ v3_msg_flags_tlv(),
++ v3_sec_model_tlv()]))
++ end),
++
++ ?IPRINT("msgMaxSize with 5 content octets is rejected"),
++ expect_exit(msg_max_size, {bad_msg_max_size_bytesize, {5, 4}},
++ fun() ->
++ snmp_pdus:dec_message_only(
++ v3_msg([int_tlv(1, 1),
++ int_tlv(1, 5),
++ v3_msg_flags_tlv(),
++ v3_sec_model_tlv()]))
++ end),
++
++ ?IPRINT("msgSecurityModel with 5 content octets is rejected"),
++ expect_exit(msg_sec_model, {bad_sec_model_bytesize, {5, 4}},
++ fun() ->
++ snmp_pdus:dec_message_only(
++ v3_msg([int_tlv(1, 1),
++ v3_msg_max_size_tlv(),
++ v3_msg_flags_tlv(),
++ int_tlv(1, 5)]))
++ end),
++
++ ?IPRINT("done"),
++ ok.
++
++
++dec_v3_hdr_value_checks(suite) -> [];
++dec_v3_hdr_value_checks(doc) ->
++ ["Range checks on the v3 header data integer fields are applied in "
++ "addition to the content octet limits"];
++dec_v3_hdr_value_checks(Config) when is_list(Config) ->
++ %% A content octet limit is not a range check: four octets still encode
++ %% 16#80000000, and one octet still encodes a msgMaxSize below the
++ %% RFC 3412 floor of 484. chk_msg_id/1, chk_msg_max_size/1 and
++ %% chk_msg_sec_model/1 must keep rejecting those.
++ ?IPRINT("a negative msgID is rejected"),
++ expect_exit(msg_id, {bad_msg_id, -2147483648},
++ fun() ->
++ snmp_pdus:dec_message_only(
++ v3_msg([raw_int_tlv([128, 0, 0, 0]),
++ v3_msg_max_size_tlv(),
++ v3_msg_flags_tlv(),
++ v3_sec_model_tlv()]))
++ end),
++
++ ?IPRINT("a msgMaxSize below 484 is rejected"),
++ expect_exit(msg_max_size, {bad_msg_max_size, 100},
++ fun() ->
++ snmp_pdus:dec_message_only(
++ v3_msg([int_tlv(1, 1),
++ int_tlv(100, 1),
++ v3_msg_flags_tlv(),
++ v3_sec_model_tlv()]))
++ end),
++
++ ?IPRINT("a negative msgSecurityModel is rejected"),
++ expect_exit(msg_sec_model, {bad_msg_sec_model, -1},
++ fun() ->
++ snmp_pdus:dec_message_only(
++ v3_msg([int_tlv(1, 1),
++ v3_msg_max_size_tlv(),
++ v3_msg_flags_tlv(),
++ raw_int_tlv([255])]))
++ end),
++
++ ?IPRINT("done"),
++ ok.
++
++
++dec_usm_sec_params_int_size_limits(suite) -> [];
++dec_usm_sec_params_int_size_limits(doc) ->
++ ["Content octet limits for msgAuthoritativeEngineBoots and "
++ "msgAuthoritativeEngineTime"];
++dec_usm_sec_params_int_size_limits(Config) when is_list(Config) ->
++ %% RFC 3414: both fields are INTEGER (0..2147483647) -- four content
++ %% octets. They are parsed before the message is authenticated, so an
++ %% unbounded encoding here is reachable pre-auth.
++ ?IPRINT("well formed security parameters decode"),
++ #usmSecurityParameters{msgAuthoritativeEngineID = "",
++ msgAuthoritativeEngineBoots = 1,
++ msgAuthoritativeEngineTime = 2} =
++ snmp_pdus:dec_usm_security_parameters(usm_params(int_tlv(1, 4),
++ int_tlv(2, 4))),
++
++ ?IPRINT("msgAuthoritativeEngineBoots with 5 content octets is rejected"),
++ expect_exit(engine_boots, {bad_engine_boots_bytesize, {5, 4}},
++ fun() ->
++ snmp_pdus:dec_usm_security_parameters(
++ usm_params(int_tlv(1, 5), int_tlv(2, 1)))
++ end),
++
++ ?IPRINT("msgAuthoritativeEngineTime with 5 content octets is rejected"),
++ expect_exit(engine_time, {bad_engine_time_bytesize, {5, 4}},
++ fun() ->
++ snmp_pdus:dec_usm_security_parameters(
++ usm_params(int_tlv(1, 1), int_tlv(2, 5)))
++ end),
++
++ ?IPRINT("done"),
++ ok.
++
++
+ %%======================================================================
+ %% Internal functions
+ %%======================================================================
+@@ -394,3 +693,86 @@ otp10132(Config) when is_list(Config) ->
+ dec_message(B) when is_binary(B) ->
+ L = binary_to_list(B),
+ snmp_pdus:dec_message(L).
++
++
++%% -----
++%% Exception helpers
++%%
++%% dec_class/1 reports the exception class alongside the reason, so that a
++%% throw cannot pass for an exit.
++
++dec_class(Fun) ->
++ try Fun() of
++ Result ->
++ {ok, Result}
++ catch
++ Class:Reason ->
++ {Class, Reason}
++ end.
++
++expect_exit(Field, Reason, Fun) ->
++ case dec_class(Fun) of
++ {exit, Reason} ->
++ ok;
++ Unexpected ->
++ exit({unexpected_decode_result, Field, Reason, Unexpected})
++ end.
++
++expect_bad_integer(Field, SizeAndLimit, Fun) ->
++ expect_exit(Field, {error, {bad_integer, SizeAndLimit}}, Fun).
++
++
++%% -----
++%% BER encoding helpers
++%%
++%% All lengths stay below 128, so a single octet length is always enough.
++
++%% INTEGER TLV carrying Value in exactly Size content octets, zero padded.
++%% Padding is what the content octet limits exist to bound, so these
++%% encodings are intentionally non-minimal.
++int_tlv(Value, Size) when is_integer(Value), Value >= 0, Value < 128,
++ is_integer(Size), Size >= 1 ->
++ raw_int_tlv(lists:duplicate(Size - 1, 0) ++ [Value]).
++
++raw_int_tlv(Octets) ->
++ [2, length(Octets) | Octets].
++
++%% TLV for one of the integer valued application types: Size content
++%% octets encoding the value 1.
++padded_value(Tag, Size) when is_integer(Size), Size >= 1 ->
++ [Tag, Size | lists:duplicate(Size - 1, 0) ++ [1]].
++
++%% Minimal v3 message for dec_message_only/1: version, a header data
++%% sequence built from the supplied TLVs, and empty msgSecurityParameters.
++v3_msg(HdrDataTLVs) ->
++ HdrData = lists:append(HdrDataTLVs),
++ HdrSeq = [48, length(HdrData) | HdrData],
++ Content = raw_int_tlv([3]) ++ HdrSeq ++ [4, 0],
++ [48, length(Content) | Content].
++
++v3_msg_max_size_tlv() ->
++ raw_int_tlv([1, 228]). % 484, the RFC 3412 minimum
++
++v3_msg_flags_tlv() ->
++ [4, 1, 4]. % reportable, noAuthNoPriv
++
++v3_sec_model_tlv() ->
++ raw_int_tlv([3]). % USM
++
++%% USM security parameters with an empty engine ID, user name, and
++%% authentication and privacy parameters.
++usm_params(BootsTLV, TimeTLV) ->
++ Content = [4, 0] ++ BootsTLV ++ TimeTLV ++ [4, 0] ++ [4, 0] ++ [4, 0],
++ [48, length(Content) | Content].
++
++%% PDU with the three supplied integer TLVs and an empty varbind list.
++pdu(Tag, IntTLVs) ->
++ Content = lists:append(IntTLVs) ++ [48, 0],
++ [Tag, length(Content) | Content].
++
++%% TrapPDU with enterprise 1.3, agent-addr 127.0.0.1, time-stamp 0 and an
++%% empty varbind list.
++trap_pdu(GenericTLV, SpecificTLV) ->
++ Content = [6, 1, 43] ++ [64, 4, 127, 0, 0, 1] ++
++ GenericTLV ++ SpecificTLV ++ [67, 1, 0] ++ [48, 0],
++ [164, length(Content) | Content].
diff --git a/otp-0029-ssl-Check-SNI-in-TLS-1.2-session-reuse.patch b/otp-0029-ssl-Check-SNI-in-TLS-1.2-session-reuse.patch
new file mode 100644
index 0000000..fd4b68d
--- /dev/null
+++ b/otp-0029-ssl-Check-SNI-in-TLS-1.2-session-reuse.patch
@@ -0,0 +1,701 @@
+From: Ingela Anderton Andin <ingela@erlang.org>
+Date: Wed, 7 Oct 2026 15:28:54 +0200
+Subject: [PATCH] ssl: Check SNI in TLS-1.2 session reuse
+
+Fixes CVE-2026-105236.
+
+(cherry picked from commit 10ee925d0fee8413f1170cc21bfcf123c8d22454)
+
+[Backport to OTP 26: OTP 26 has no tls_dtls_server_connection.erl; the
+server-side session registration lives in tls_dtls_connection.erl, so
+the SNI hostname is recorded there instead (the private
+handle_session/6 is renamed maybe_register_session/7, as upstream, to
+avoid clashing with the exported handle_session/7). select_session/9
+becomes select_session/10 since OTP 26 still passes Compressions.
+Dropped the unrelated DTLS ClientHello version-decoding change in
+dtls_handshake:decode_handshake/3 and the session_server_restart test
+case, which does not exist in OTP 26. Without that DTLS change OTP 26
+cannot negotiate rsa_pss_rsae-only signature algorithms over DTLS 1.2,
+so openssl_sni_SUITE keeps forcing them for TLS only and runs the new
+sni_cross_ca_no_session_reuse case in the tlsv1.2 group only (upstream
+ssl_session_SUITE likewise skips it for DTLS).]
+
+Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
+Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
+
+diff --git a/lib/ssl/src/dtls_handshake.erl b/lib/ssl/src/dtls_handshake.erl
+index a93adb5287..710dde572d 100644
+--- a/lib/ssl/src/dtls_handshake.erl
++++ b/lib/ssl/src/dtls_handshake.erl
+@@ -198,7 +198,7 @@ handle_client_hello(Version,
+ {Type, #session{cipher_suite = CipherSuite,
+ own_certificates = [OwnCert |_]} = Session1}
+ = ssl_handshake:select_session(SugesstedId, CipherSuites,
+- AvailableHashSigns, Compressions,
++ AvailableHashSigns, Compressions, HelloExt,
+ SessIdTracker, Session0#session{ecc = ECCCurve}, TLSVersion,
+ SslOpts, CertKeyPairs),
+ case CipherSuite of
+diff --git a/lib/ssl/src/ssl_handshake.erl b/lib/ssl/src/ssl_handshake.erl
+index 65f47eb963..59611e50c4 100644
+--- a/lib/ssl/src/ssl_handshake.erl
++++ b/lib/ssl/src/ssl_handshake.erl
+@@ -70,7 +70,7 @@
+
+ %% Cipher suites handling
+ -export([available_suites/2, available_signature_algs/2, available_signature_algs/3,
+- cipher_suites/3, select_session/9,
++ cipher_suites/3, select_session/10,
+ premaster_secret/2, premaster_secret/3, premaster_secret/4]).
+
+ %% Extensions handling
+@@ -1067,10 +1067,12 @@ cipher_suites(Suites, false) ->
+ cipher_suites(Suites, true) ->
+ Suites.
+
+-select_session(SuggestedSessionId, CipherSuites, HashSigns, Compressions, SessIdTracker, Session0, Version, SslOpts, CertKeyAlts) ->
++select_session(SuggestedSessionId, CipherSuites, HashSigns, Compressions, HelloExt,
++ SessIdTracker, Session0, Version, SslOpts, CertKeyAlts) ->
+ CertKeyPairs = ssl_certificate:available_cert_key_pairs(CertKeyAlts, Version),
+- {SessionId, Resumed} = ssl_session:server_select_session(Version, SessIdTracker, SuggestedSessionId,
+- SslOpts, CertKeyPairs),
++ {SessionId, Resumed} =
++ ssl_session:server_select_session(Version, SessIdTracker, SuggestedSessionId,
++ HelloExt, SslOpts, CertKeyPairs),
+ case Resumed of
+ undefined ->
+ %% Select Cert
+diff --git a/lib/ssl/src/ssl_handshake.hrl b/lib/ssl/src/ssl_handshake.hrl
+index ada0c774d5..857c3b3443 100644
+--- a/lib/ssl/src/ssl_handshake.hrl
++++ b/lib/ssl/src/ssl_handshake.hrl
+@@ -51,7 +51,8 @@
+ time_stamp,
+ ecc, %% TLS 1.3 Group
+ sign_alg, %% TLS 1.3 Signature Algorithm
+- dh_public_value %% TLS 1.3 DH Public Value from peer
++ dh_public_value, %% TLS 1.3 DH Public Value from peer
++ sni %% SNI hostname
+ }).
+
+ -define(EMPTY_ID, <<>>).
+diff --git a/lib/ssl/src/ssl_session.erl b/lib/ssl/src/ssl_session.erl
+index 721a9ef4d5..078a4537de 100644
+--- a/lib/ssl/src/ssl_session.erl
++++ b/lib/ssl/src/ssl_session.erl
+@@ -33,7 +33,7 @@
+ %% Internal application API
+ -export([is_new/2,
+ client_select_session/5,
+- server_select_session/5,
++ server_select_session/6,
+ valid_session/2,
+ legacy_session_id/1]).
+
+@@ -107,16 +107,16 @@ client_select_session({_, _, #{versions := Versions,
+ end.
+
+ %%--------------------------------------------------------------------
+--spec server_select_session(ssl_record:ssl_version(), pid(), ssl:session_id(), map(),
++-spec server_select_session(ssl_record:ssl_version(), pid(), ssl:session_id(), map(), map(),
+ list()) -> {binary(), #session{} | undefined}.
+ %%
+ %% Description: Should be called by the server side to get an id
+ %% for the client hello message.
+ %%--------------------------------------------------------------------
+-server_select_session(_, SessIdTracker, ?EMPTY_ID, _SslOpts, _CertKeyPairs) ->
++server_select_session(_, SessIdTracker, ?EMPTY_ID, _HelloExt, _SslOpts, _CertKeyPairs) ->
+ {ssl_server_session_cache:new_session_id(SessIdTracker), undefined};
+-server_select_session(_, SessIdTracker, SuggestedId, Options, CertKeyPairs) ->
+- case is_resumable(SuggestedId, SessIdTracker, Options, CertKeyPairs)
++server_select_session(_, SessIdTracker, SuggestedId, HelloExt, Options, CertKeyPairs) ->
++ case is_resumable(SuggestedId, SessIdTracker, Options, HelloExt, CertKeyPairs)
+ of
+ {true, Resumed} ->
+ {SuggestedId, Resumed};
+@@ -193,10 +193,10 @@ select_session(Sessions, #{ciphers := Ciphers}, CertKeyPairs) ->
+ [Session | _] -> Session
+ end.
+
+-is_resumable(_, _, #{reuse_sessions := false}, _) ->
++is_resumable(_, _, #{reuse_sessions := false}, _, _) ->
+ {false, undefined};
+ is_resumable(SuggestedSessionId, SessIdTracker,
+- #{reuse_session := ReuseFun} = Options, OwnCertKeyPairs) ->
++ #{reuse_session := ReuseFun} = Options, HelloExt, OwnCertKeyPairs) ->
+ case ssl_server_session_cache:reuse_session(SessIdTracker, SuggestedSessionId) of
+ #session{cipher_suite = CipherSuite,
+ own_certificates = [SessionOwnCert | _],
+@@ -205,7 +205,7 @@ is_resumable(SuggestedSessionId, SessIdTracker,
+ peer_certificate = PeerCert} = Session ->
+ case resumable(IsResumable)
+ andalso is_owncert(SessionOwnCert, OwnCertKeyPairs)
+- andalso reusable_options(Options, Session)
++ andalso reusable_options(Options, HelloExt, Session)
+ andalso ReuseFun(SuggestedSessionId, PeerCert,
+ Compression, CipherSuite)
+ of
+@@ -229,10 +229,23 @@ resumable(IsResumable) ->
+ IsResumable.
+
+ reusable_options(#{fail_if_no_peer_cert := true,
+- verify := verify_peer}, Session) ->
+- (Session#session.peer_certificate =/= undefined);
+-reusable_options(_,_) ->
+- true.
++ verify := verify_peer}, _, #session{peer_certificate = undefined}) ->
++ %% Can not resume session without a peer cert if current negotiation requires one.
++ false;
++reusable_options(_Opts, HelloExt, #session{sni = SessionSNI}) ->
++ %% RFC 6066 3: a server that implements SNI MUST NOT resume a session
++ %% if the server_name of the resumption request differs from the one
++ %% that established the session; it must do a full handshake instead.
++ %% Comparing the established server_name (rather than the server
++ %% certificate) also covers the case where several SNI names share
++ %% one certificate but have different client-authentication trust.
++ %% A request without SNI only matches a session established without
++ %% SNI, so ordinary (non-SNI) resumption is unaffected.
++ RequestSNI = case maps:get(sni, HelloExt, undefined) of
++ #sni{hostname = Host} -> Host;
++ undefined -> undefined
++ end,
++ RequestSNI =:= SessionSNI.
+
+ record_cb(tls) ->
+ tls_record;
+diff --git a/lib/ssl/src/tls_dtls_connection.erl b/lib/ssl/src/tls_dtls_connection.erl
+index d4da62de28..e945e00f71 100644
+--- a/lib/ssl/src/tls_dtls_connection.erl
++++ b/lib/ssl/src/tls_dtls_connection.erl
+@@ -597,6 +597,7 @@ cipher(internal, #finished{verify_data = Data} = Finished,
+ port = Port,
+ trackers = Trackers},
+ handshake_env = #handshake_env{tls_handshake_history = Hist,
++ sni_hostname = SNIHostname,
+ expecting_finished = true} = HsEnv,
+ connection_env = #connection_env{negotiated_version = Version},
+ session = #session{master_secret = MasterSecret}
+@@ -608,7 +609,8 @@ cipher(internal, #finished{verify_data = Data} = Finished,
+ get_current_prf(ConnectionStates0, read),
+ MasterSecret, Hist) of
+ verified ->
+- Session = handle_session(Role, SslOpts, Host, Port, Trackers, Session0),
++ Session = maybe_register_session(Role, SslOpts, SNIHostname, Host, Port,
++ Trackers, Session0),
+ cipher_role(Role, Data, Session,
+ State#state{handshake_env = HsEnv#handshake_env{expecting_finished = false}});
+ #alert{} = Alert ->
+@@ -1578,16 +1580,17 @@ session_handle_params(#server_ecdh_params{curve = ECCurve}, Session) ->
+ session_handle_params(_, Session) ->
+ Session.
+
+-handle_session(server, #{reuse_sessions := true},
++maybe_register_session(server, #{reuse_sessions := true}, SNIHostname,
+ _Host, _Port, Trackers, #session{is_resumable = false} = Session) ->
+ Tracker = proplists:get_value(session_id_tracker, Trackers),
+- server_register_session(Tracker, Session#session{is_resumable = true});
+-handle_session(Role = client, #{verify := verify_peer,
+- reuse_sessions := Reuse} = SslOpts,
++ server_register_session(Tracker, Session#session{is_resumable = true,
++ sni = SNIHostname});
++maybe_register_session(Role = client, #{verify := verify_peer,
++ reuse_sessions := Reuse} = SslOpts, _SNIHostname,
+ Host, Port, _, #session{is_resumable = false} = Session) when Reuse =/= false ->
+ client_register_session(host_id(Role, Host, SslOpts), Port, Session#session{is_resumable = true},
+ reg_type(Reuse));
+-handle_session(_,_,_,_,_, Session) ->
++maybe_register_session(_,_,_,_,_,_, Session) ->
+ Session.
+
+ reg_type(save) ->
+diff --git a/lib/ssl/src/tls_handshake.erl b/lib/ssl/src/tls_handshake.erl
+index 2431a2ec4d..3d4503002a 100644
+--- a/lib/ssl/src/tls_handshake.erl
++++ b/lib/ssl/src/tls_handshake.erl
+@@ -347,7 +347,7 @@ handle_client_hello(Version,
+ {Type, #session{cipher_suite = CipherSuite,
+ own_certificates = [OwnCert |_]} = Session1}
+ = ssl_handshake:select_session(SugesstedId, CipherSuites,
+- AvailableHashSigns, Compressions,
++ AvailableHashSigns, Compressions, HelloExt,
+ SessIdTracker, Session0#session{ecc = ECCCurve},
+ Version, SslOpts, CertKeyPairs),
+ case CipherSuite of
+diff --git a/lib/ssl/test/openssl_sni_SUITE.erl b/lib/ssl/test/openssl_sni_SUITE.erl
+index a5ebbb35c4..7de6bf5776 100644
+--- a/lib/ssl/test/openssl_sni_SUITE.erl
++++ b/lib/ssl/test/openssl_sni_SUITE.erl
+@@ -38,7 +38,9 @@
+ sni_no_match/1,
+ sni_no_match_fun/1,
+ sni_no_header/1,
+- sni_no_header_fun/1
++ sni_no_header_fun/1,
++ sni_cross_ca_no_session_reuse/0,
++ sni_cross_ca_no_session_reuse/1
+ ]).
+
+ %% Apply exports
+@@ -75,7 +77,7 @@ groups() ->
+ case ssl_test_lib:openssl_sane_dtls() of
+ true ->
+ [{'tlsv1.3', [], sni_tests()},
+- {'tlsv1.2', [], sni_tests()},
++ {'tlsv1.2', [], sni_tests() ++ tls_1_2_tests()},
+ {'tlsv1.1', [], sni_tests()},
+ {'tlsv1', [], sni_tests()},
+ {'dtlsv1.2', [], sni_tests()},
+@@ -83,7 +85,7 @@ groups() ->
+ ];
+ false ->
+ [{'tlsv1.3', [], sni_tests()},
+- {'tlsv1.2', [], sni_tests()},
++ {'tlsv1.2', [], sni_tests() ++ tls_1_2_tests()},
+ {'tlsv1.1', [], sni_tests()},
+ {'tlsv1', [], sni_tests()}
+ ]
+@@ -97,6 +99,10 @@ sni_tests() ->
+ sni_no_header,
+ sni_no_header_fun].
+
++%% Session-id based resumption only exists pre TLS-1.3.
++tls_1_2_tests() ->
++ [sni_cross_ca_no_session_reuse].
++
+ init_per_suite(Config0) ->
+ Config1 = ssl_test_lib:init_per_suite(Config0, openssl),
+ Config2 = check_openssl_sni_support(Config1),
+@@ -188,6 +194,90 @@ sni_no_match_fun(Config) when is_list(Config) ->
+ proplists:get_value(client_local_opts, Config)], Config),
+ sni_test(ServerNode, ServerOptions, ClientOptions, Config).
+
++sni_cross_ca_no_session_reuse() ->
++ ["Two SNI names share the same server
++ certificate but trust different CAs. A client that
++ trusts the lower-trust name must NOT be able to resume
++ that TLS-1.2 session at the higher-trust name."].
++
++sni_cross_ca_no_session_reuse(Config) when is_list(Config) ->
++ {_, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
++ Version = ssl_test_lib:protocol_version(Config),
++ PrivDir = proplists:get_value(priv_dir, Config),
++ {ServerConf, ServerCACertFile, LowCACertFile, HighCACertFile,
++ LowClientCert, LowClientKey} = ssl_test_lib:make_cross_ca_pems(PrivDir),
++
++ LowSNI = "low.test",
++ HighSNI = "high.test",
++ SigAlgOpts = maybe_add_sigalgs(Version, []),
++ SniBase = SigAlgOpts ++ ServerConf,
++ SniFun =
++ fun(SNI) when SNI =:= LowSNI ->
++ [{verify, verify_peer}, {fail_if_no_peer_cert, true},
++ {reuse_sessions, true},
++ {cacertfile, LowCACertFile} | SniBase];
++ (SNI) when SNI =:= HighSNI ->
++ [{verify, verify_peer}, {fail_if_no_peer_cert, true},
++ {reuse_sessions, true},
++ {cacertfile, HighCACertFile} | SniBase];
++ (_) ->
++ unrecognized
++ end,
++
++ ServerOptions = [{verify, verify_none},
++ {versions, [Version]},
++ {sni_fun, SniFun} | SniBase],
++
++ SessFile = filename:join(PrivDir, "otp20445_low.sess"),
++ file:delete(SessFile),
++
++ %% One persistent listener for both connections so the pre-TLS-1.3
++ %% session cache (which is per listen socket) is shared.
++ Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
++ {from, self()},
++ {mfa, {?MODULE, send_and_hostname, []}},
++ {options, ServerOptions}]),
++ Port0 = ssl_test_lib:inet_port(Server),
++
++ ClientBase = maybe_add_openssl_sigalgs(Version) ++
++ [{hostname, Hostname}, {port, Port0},
++ {cacertfile, ServerCACertFile},
++ {certfile, LowClientCert}, {keyfile, LowClientKey}],
++
++ %% 1. Establish and save a session at the low-trust name. The server
++ %% reports the SNI name it served, proving the low client is
++ %% authenticated against the low CA.
++ Low = ssl_test_lib:start_client(openssl,
++ [{server_name_indication, LowSNI},
++ {versions, [Version]},
++ {session_args, ["-sess_out", SessFile]}
++ | ClientBase],
++ Config),
++ ssl_test_lib:check_result(Server, LowSNI),
++ ssl_test_lib:close_port(Low),
++
++ %% The session file must have been written for the attack to be
++ %% meaningful.
++ true = filelib:is_regular(SessFile),
++
++ %% Re-arm the same listener for the next connection.
++ Server ! {listen, {mfa, {?MODULE, send_and_hostname, []}}},
++
++ %% 2. Attempt to resume that session at the high-trust name using
++ %% the same low-trust client certificate. The verify_peer service
++ %% must force a full handshake and reject the low-trust cert with an
++ %% unknown_ca alert, instead of silently resuming (which would let
++ %% the low-trust client reach the high-trust authority).
++ High = ssl_test_lib:start_client(openssl,
++ [{server_name_indication, HighSNI},
++ {versions, [Version]},
++ {session_args, ["-sess_in", SessFile]}
++ | ClientBase],
++ Config),
++ ssl_test_lib:check_server_alert(Server, unknown_ca),
++ ssl_test_lib:close_port(High),
++ ssl_test_lib:close(Server),
++ ok.
+
+ %%--------------------------------------------------------------------
+ %% Callback functions ------------------------------------------------
+@@ -260,17 +350,21 @@ maybe_add_openssl_sigalgs(Version) when Version == 'tlsv1.3';
+ case ssl_test_lib:portable_cmd("openssl", ["version"]) of
+ "OpenSSL 1.0" ++ _ ->
+ [];
++ "OpenSSL 1.1" ++ _ ->
++ openssl_add_sigalgs("rsa_pkcs1_sha256:rsa_pss_rsae_sha256");
+ _ ->
+- HelpText = ssl_test_lib:portable_cmd("openssl", ["s_client", "--help"]),
+- case string:str(HelpText, "-sigalgs") of
+- 0 ->
+- [];
+- _ ->
+- [{sigalgs, "rsa_pss_rsae_sha512:rsa_pss_rsae_sha384:rsa_pss_rsae_sha256"}]
+- end
++ openssl_add_sigalgs("rsa_pss_rsae_sha512:rsa_pss_rsae_sha384:rsa_pss_rsae_sha256")
+ end;
+ maybe_add_openssl_sigalgs(_) ->
+ [].
++openssl_add_sigalgs(Sigalgs) ->
++ HelpText = ssl_test_lib:portable_cmd("openssl", ["s_client", "--help"]),
++ case string:str(HelpText, "-sigalgs") of
++ 0 ->
++ [];
++ _ ->
++ [{sigalgs, Sigalgs}]
++ end.
+
+ check_openssl_sni_support(Config) ->
+ HelpText = ssl_test_lib:portable_cmd("openssl", ["s_client", "--help"]),
+diff --git a/lib/ssl/test/ssl_session_SUITE.erl b/lib/ssl/test/ssl_session_SUITE.erl
+index 549939fad6..75430f34d6 100644
+--- a/lib/ssl/test/ssl_session_SUITE.erl
++++ b/lib/ssl/test/ssl_session_SUITE.erl
+@@ -61,7 +61,9 @@
+ server_max_session_table/0,
+ server_max_session_table/1,
+ session_table_stable_size_on_tcp_close/0,
+- session_table_stable_size_on_tcp_close/1
++ session_table_stable_size_on_tcp_close/1,
++ sni_cross_ca_no_session_reuse/0,
++ sni_cross_ca_no_session_reuse/1
+ ]).
+
+ -define(SLEEP, 500).
+@@ -83,7 +85,6 @@ all() ->
+ groups() ->
+ [{'dtlsv1.2', [], session_tests()},
+ {'dtlsv1', [], session_tests()},
+- {'tlsv1.3', [], session_tests() ++ tls_session_tests()},
+ {'tlsv1.2', [], session_tests() ++ tls_session_tests()},
+ {'tlsv1.1', [], session_tests() ++ tls_session_tests()},
+ {'tlsv1', [], session_tests() ++ tls_session_tests()}
+@@ -98,20 +99,20 @@ session_tests() ->
+ no_reuses_session_server_restart_new_cert,
+ no_reuses_session_server_restart_new_cert_file,
+ client_max_session_table,
+- server_max_session_table
++ server_max_session_table,
++ sni_cross_ca_no_session_reuse
+ ].
+
+ tls_session_tests() ->
+ [session_table_stable_size_on_tcp_close].
+
+ init_per_suite(Config0) ->
+- catch crypto:stop(),
+- try crypto:start() of
++ case application:ensure_started(crypto) of
+ ok ->
+ ssl_test_lib:clean_start(),
+ Config = ssl_test_lib:make_rsa_cert(Config0),
+- ssl_test_lib:make_rsa_1024_cert(Config)
+- catch _:_ ->
++ ssl_test_lib:make_rsa_1024_cert(Config);
++ {error, _} ->
+ {skip, "Crypto did not start"}
+ end.
+
+@@ -125,6 +126,30 @@ init_per_group(GroupName, Config) ->
+ end_per_group(GroupName, Config) ->
+ ssl_test_lib:end_per_group(GroupName, Config).
+
++init_per_testcase(sni_cross_ca_no_session_reuse, Config) ->
++ %% The cross-SNI session-reuse fix applies to pre-TLS-1.3 TLS and
++ %% DTLS alike (see ssl_session:reusable_options/3, threaded via
++ %% tls_handshake and dtls_handshake). This end-to-end test is however
++ %% TLS-only: over DTLS the ssl_test_lib run_server/listen re-arm does
++ %% not reliably route a second, brand-new UDP peer to the re-armed
++ %% transport_accept, so the test hangs. The DTLS code path is covered
++ %% by the generic reuse_session test. See OTP-20445 backlog note on
++ %% making the DTLS re-accept harness robust for a dedicated DTLS case.
++ case proplists:get_value(protocol, Config, tls) of
++ dtls ->
++ {skip, "cross-SNI reuse end-to-end test is TLS-only; "
++ "DTLS code path covered by reuse_session"};
++ _ ->
++ Versions = ssl_test_lib:protocol_version(Config),
++ ssl:stop(),
++ application:load(ssl),
++ ssl_test_lib:clean_env(),
++ ssl_test_lib:set_protocol_versions(Versions),
++ ssl:start(),
++ ssl_test_lib:ct_log_supported_protocol_versions(Config),
++ ct:timetrap({seconds, 5}),
++ Config
++ end;
+ init_per_testcase(TestCase, Config) when TestCase == reuse_session_expired;
+ TestCase == explicit_session_reuse_expired ->
+ Versions = ssl_test_lib:protocol_version(Config),
+@@ -348,7 +373,6 @@ explicit_session_reuse(Config) when is_list(Config) ->
+
+
+ %%--------------------------------------------------------------------
+-
+ explicit_session_reuse_expired() ->
+ [{doc,"Test to reuse a session that has expired and make sure server session table is correctly handled"}].
+ explicit_session_reuse_expired(Config) when is_list(Config) ->
+@@ -459,6 +483,91 @@ explicit_session_reuse_expired(Config) when is_list(Config) ->
+ 2 = SessionCacheCb3:size(SessionCacheDb3).
+
+
++%%--------------------------------------------------------------------
++sni_cross_ca_no_session_reuse() ->
++ ["Two SNI names share the same server
++ certificate but trust different CAs. A client that
++ trusts the lower-trust name must NOT be able to resume
++ that TLS-1.2 session at the higher-trust name."].
++
++sni_cross_ca_no_session_reuse(Config) when is_list(Config) ->
++ process_flag(trap_exit, true),
++ {ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
++ PrivDir = proplists:get_value(priv_dir, Config),
++ {ServerConf, CACertFile, LowCACertFile, HighCACertFile,
++ ClientCert, ClientKey} = ssl_test_lib:make_cross_ca_pems(PrivDir),
++
++ LowSNI = "low.test",
++ HighSNI = "high.test",
++
++ SniFun =
++ fun(SNI) when SNI =:= LowSNI ->
++ [{verify, verify_peer}, {fail_if_no_peer_cert, true},
++ {reuse_sessions, true},
++ {cacertfile, LowCACertFile} | ServerConf];
++ (SNI) when SNI =:= HighSNI ->
++ [{verify, verify_peer}, {fail_if_no_peer_cert, true},
++ {reuse_sessions, true},
++ {cacertfile, HighCACertFile} | ServerConf];
++ (_) ->
++ unrecognized
++ end,
++
++ ServerOpts = ssl_test_lib:ssl_options([{sni_fun, SniFun} | ServerConf], Config),
++ ClientOpts = ssl_test_lib:ssl_options([], Config),
++
++ Server =
++ ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
++ {from, self()},
++ {mfa, {ssl_test_lib, no_result, []}},
++ {options, [{reuse_sessions, true},
++ {sni_fun, SniFun}| ServerOpts]}]),
++ Port = ssl_test_lib:inet_port(Server),
++
++ %% 1. Establish a session at the lower-trust name and capture its
++ %% id + data so it can be explicitly re-offered later, regardless of
++ %% SNI (equivalent to openssl s_client -sess_out/-sess_in). Using the
++ %% client session cache would not work here: the client keys cached
++ %% sessions by SNI and would not offer the low.test session on a
++ %% high.test connection, so the server resumption decision would
++ %% never be exercised.
++ {Client0, Client0Sock} =
++ ssl_test_lib:start_client([{node, ClientNode},
++ {port, Port}, {host, Hostname},
++ {mfa, {ssl_test_lib, no_result, []}},
++ {from, self()},
++ {options, [{reuse_sessions, save},
++ {cacertfile, CACertFile},
++ {certfile, ClientCert},
++ {keyfile, ClientKey},
++ {server_name_indication, LowSNI} | ClientOpts]},
++ return_socket
++ ]),
++
++ {ok, [{session_id, ID}, {session_data, SessData}]} =
++ ssl:connection_information(Client0Sock, [session_id, session_data]),
++
++ ssl_test_lib:close(Client0),
++
++ Server ! listen,
++
++ %% 2. Explicitly re-offer the low.test session on a high.test
++ %% connection, presenting the same client certificate. high.test
++ %% trusts a different client CA, so the server must refuse to resume
++ %% across the SNI boundary and fall back to a full handshake, which
++ %% then rejects the client certificate with unknown_ca. Silent
++ %% resumption would let the lower-trust client reach the higher-trust
++ %% service without being validated against its CA.
++ ssl_test_lib:start_client_error([{node, ClientNode},
++ {port, Port}, {host, Hostname},
++ {mfa, {ssl_test_lib, no_result, []}},
++ {from, self()},
++ {options, [{reuse_session, {ID, SessData}},
++ {cacertfile, CACertFile},
++ {certfile, ClientCert}, {keyfile, ClientKey},
++ {server_name_indication, HighSNI}]}]),
++ ssl_test_lib:check_server_alert(Server, unknown_ca).
++
+ %%--------------------------------------------------------------------
+ no_reuses_session_server_restart_new_cert() ->
+ [{doc,"Check that a session is not reused if the server is restarted with a new cert."}].
+@@ -582,6 +691,7 @@ no_reuses_session_server_restart_new_cert_file(Config) when is_list(Config) ->
+ ssl_test_lib:close(Server1),
+ ssl_test_lib:close(Client1).
+
++%%--------------------------------------------------------------------
+
+ client_max_session_table() ->
+ [{doc, "Check that max session table limit is not exceeded, set max to 2 in init_per_testcase"}].
+@@ -597,7 +707,8 @@ client_max_session_table(Config) when is_list(Config)->
+ State = ssl_test_lib:state(Prop),
+ ClientCache = element(2, State),
+ 2 = ?CLIENT_CB:size(ClientCache).
+-
++
++%%--------------------------------------------------------------------
+ server_max_session_table() ->
+ [{doc, "Check that max session table limit exceeded, set max to 2 in init_per_testcase"}].
+
+@@ -615,6 +726,8 @@ server_max_session_table(Config) when is_list(Config)->
+ N = SessionCacheCb:size(SessionCacheDb),
+ true = N == 2.
+
++
++%%--------------------------------------------------------------------
+ session_table_stable_size_on_tcp_close() ->
+ [{doc, "Check that new sessions are cleanup when connection is closed abruptly during first handshake"}].
+
+diff --git a/lib/ssl/test/ssl_sni_SUITE.erl b/lib/ssl/test/ssl_sni_SUITE.erl
+index 6b20025636..f6c617aec4 100644
+--- a/lib/ssl/test/ssl_sni_SUITE.erl
++++ b/lib/ssl/test/ssl_sni_SUITE.erl
+@@ -91,11 +91,11 @@ groups() ->
+ ].
+
+ sni_tests() ->
+- [no_sni_ext,
+- sni_match,
++ [no_sni_ext,
++ sni_match,
+ sni_no_match,
+- no_sni_ext_fun,
+- sni_match_fun,
++ no_sni_ext_fun,
++ sni_match_fun,
+ sni_no_match_fun,
+ dns_name,
+ ip_fallback,
+@@ -144,7 +144,7 @@ init_per_testcase(_TestCase, Config) ->
+ ct:timetrap(?TIMEOUT),
+ Config.
+
+-end_per_testcase(_TestCase, Config) ->
++end_per_testcase(_TestCase, Config) ->
+ Config.
+
+ %%--------------------------------------------------------------------
+diff --git a/lib/ssl/test/ssl_test_lib.erl b/lib/ssl/test/ssl_test_lib.erl
+index f30219b18b..639c17e7f5 100644
+--- a/lib/ssl/test/ssl_test_lib.erl
++++ b/lib/ssl/test/ssl_test_lib.erl
+@@ -182,6 +182,7 @@
+ make_rsa_1024_cert/1,
+ make_rsa_pss_pem/4,
+ make_rsa_sni_configs/0,
++ make_cross_ca_pems/1,
+ pss_params/1,
+ gen_conf/4,
+ make_mix_cert/1,
+@@ -1709,6 +1710,65 @@ make_sni_conf(HostName, Sha) ->
+ peer => [{digest, Sha},
+ {key, hardcode_rsa_key(6)}]}}).
+
++%% Build PEM material for the cross-CA SNI test:
++%% - one shared server certificate presented for both SNI names
++%% - two independent client CAs (low / high)
++%% - a client certificate signed by the low CA
++%% The server certificate carries both SNI names as SANs so that the
++%% same certificate legitimately serves low.test and high.test, which
++%% is what makes the pre-TLS-1.3 session cache's is_owncert check pass.
++make_cross_ca_pems(PrivDir) ->
++ Sha = sha256,
++ SNIExt = [#'Extension'{extnID = ?'id-ce-subjectAltName',
++ extnValue = [{dNSName, "low.test"},
++ {dNSName, "high.test"}],
++ critical = false}],
++ %% Call 1: shared server + low client CA.
++ Data1 = public_key:pkix_test_data(
++ #{server_chain =>
++ #{root => [{digest, Sha}, {key, ssl_test_lib:hardcode_rsa_key(1)}],
++ intermediates => [[{digest, Sha},
++ {key, ssl_test_lib:hardcode_rsa_key(2)}]],
++ peer => [{digest, Sha}, {extensions, SNIExt},
++ {key, ssl_test_lib:hardcode_rsa_key(3)}]},
++ client_chain =>
++ #{root => [{digest, Sha}, {key, ssl_test_lib:hardcode_rsa_key(4)}],
++ intermediates => [[{digest, Sha},
++ {key, ssl_test_lib:hardcode_rsa_key(5)}]],
++ peer => [{digest, Sha},
++ {key, ssl_test_lib:hardcode_rsa_key(6)}]}}),
++ [{server_config, SharedServerConf},
++ {client_config, LowClientConf}] =
++ x509_test:gen_pem_config_files(
++ Data1,
++ filename:join(PrivDir, "otp20445_low"),
++ filename:join(PrivDir, "otp20445_shared")),
++
++ %% Call 2: throwaway server + an independent high client CA. Only
++ %% the client (high) CA file is used from this call.
++ Data2 = public_key:pkix_test_data(
++ #{server_chain =>
++ #{root => [{digest, Sha}], intermediates => [[{digest, Sha}]],
++ peer => [{digest, Sha}]},
++ client_chain =>
++ #{root => [{digest, Sha}], intermediates => [[{digest, Sha}]],
++ peer => [{digest, Sha}]}}),
++ [{server_config, _}, {client_config, HighClientConf}] =
++ x509_test:gen_pem_config_files(
++ Data2,
++ filename:join(PrivDir, "otp20445_high"),
++ filename:join(PrivDir, "otp20445_throwaway")),
++
++ ServerConf = [{certfile, proplists:get_value(certfile, SharedServerConf)},
++ {keyfile, proplists:get_value(keyfile, SharedServerConf)}],
++ ServerCACertFile = proplists:get_value(cacertfile, SharedServerConf),
++ LowCACertFile = proplists:get_value(cacertfile, LowClientConf),
++ HighCACertFile = proplists:get_value(cacertfile, HighClientConf),
++ LowClientCert = proplists:get_value(certfile, LowClientConf),
++ LowClientKey = proplists:get_value(keyfile, LowClientConf),
++ {ServerConf, ServerCACertFile, LowCACertFile, HighCACertFile,
++ LowClientCert, LowClientKey}.
++
+ gen_conf(ClientChainType, ServerChainType, UserClient, UserServer) ->
+ gen_conf(ClientChainType, ServerChainType, UserClient, UserServer, ?DEFAULT_CURVE).
+ %%
next reply other threads:[~2026-11-02 18:03 UTC|newest]
Thread overview: 2+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-02 18:03 Peter Lemenkov [this message]
2026-11-02 18:44 [rpms/erlang] f44: Backported fixes for CVE-2026-59696, CVE-2026-94200, CVE-2026-105236 Peter Lemenkov
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=179364262701.1.11300976777711995473.rpms-erlang-a0c0eccb1e2a@fedoraproject.org \
--to=lemenkov@gmail.com \
--cc=git-commits@fedoraproject.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox