Copilot commented on code in PR #13809:
URL: https://github.com/apache/trafficserver/pull/13809#discussion_r4476592000


##########
src/iocore/net/SSLUtils.cc:
##########
@@ -595,6 +595,24 @@ ssl_client_hello_callback(const SSL_CLIENT_HELLO 
*client_hello)
   return CLIENT_HELLO_SUCCESS;
 }
 
+#if HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
+// OpenSSL's ClientHello API drops extensions it doesn't recognize, including
+// GREASE. Record the extension types from the raw ClientHello message, which
+// this callback receives before ssl_client_hello_callback runs.
+static void
+ssl_msg_callback(int write_p, int /* version ATS_UNUSED */, int content_type, 
const void *buf, size_t len, SSL *ssl,
+                 void * /* arg ATS_UNUSED */)
+{
+  auto const *msg = static_cast<const uint8_t *>(buf);
+  if (write_p || content_type != SSL3_RT_HANDSHAKE || len == 0 || msg[0] != 
SSL3_MT_CLIENT_HELLO) {
+    return;
+  }
+  if (TLSSNISupport *snis = TLSSNISupport::getInstance(ssl); snis != nullptr) {
+    snis->on_client_hello_message(msg, len);
+  }

Review Comment:
   on_client_hello_message() documents and requires the *full* handshake 
message (including the 4-byte header), but ssl_msg_callback forwards the msg 
callback buffer directly. If OpenSSL ever invokes the msg callback with 
record-level handshake fragments (or otherwise not the complete ClientHello), 
this will systematically fail parsing, increment the failure metric, and negate 
the intended fix for fragmented ClientHellos. Consider adding explicit 
reassembly keyed off the handshake length field (buffer until 4+body_len), or 
ensure via API guarantees that this callback always receives complete handshake 
messages before calling on_client_hello_message().



##########
src/iocore/net/TLSSNISupport.cc:
##########
@@ -138,6 +141,111 @@ TLSSNISupport::on_client_hello(ClientHello &client_hello)
   }
 }
 
+void
+TLSSNISupport::on_client_hello_message(const uint8_t *msg, size_t len)
+{
+  _reset_raw_extension_types();
+
+  auto const count =
+    parse_client_hello_extension_types(msg, len, 
_fast_raw_extension_storage.data(), _fast_raw_extension_storage.size());
+  if (!count) {
+    Metrics::Counter::increment(ssl_rsb.client_hello_raw_parse_failure);
+    Dbg(dbg_ctl_ssl_sni, "Could not parse the extensions of the raw 
ClientHello");
+    return;
+  }
+  if (*count <= _fast_raw_extension_storage.size()) {
+    _raw_extension_types = _fast_raw_extension_storage.data();
+  } else {
+    _slow_raw_extension_storage = std::make_unique<int[]>(*count);
+    parse_client_hello_extension_types(msg, len, 
_slow_raw_extension_storage.get(), *count);

Review Comment:
   The second call to parse_client_hello_extension_types() ignores its return 
value. If it were to ever fail (e.g., due to unexpected callback buffer 
semantics), _raw_extension_types would be set to storage that may be only 
partially populated. Capture and validate the returned optional (e.g., 
ink_assert / early-return on failure) so the state remains consistent and 
failures are surfaced deterministically.



##########
tests/uranium_tests/pluginTest/jax_fingerprint/test_jax_fingerprint_raw_extensions.py:
##########
@@ -0,0 +1,56 @@
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+import re
+import sys
+
+import pytest
+
+from tools.uranium.services import ATSFactory, ServiceFactory, 
wait_for_file_lines
+
+
+def test_jax_fingerprint_raw_extensions(ats_factory: ATSFactory, services: 
ServiceFactory) -> None:
+    """Include ALPS but not GREASE in complete and fragmented Chrome 
fingerprints.
+

Review Comment:
   This docstring is a bit misleading relative to the behavior under test: the 
ClientHello being sent includes GREASE extension *types*, but the JA4 
computation drops GREASE values by design. Consider rewording to clarify that 
the test verifies the raw extension-type list includes unknown types like ALPS 
(and that GREASE is present on the wire but excluded from the computed 
fingerprint).



##########
tests/uranium_tests/pluginTest/jax_fingerprint/chrome_client_hello.py:
##########
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+'''
+Send a Chrome-shaped TLS ClientHello and report the JA4 fingerprint it should 
produce.
+
+The ClientHello carries GREASE cipher suites and extensions as well as the
+ALPS (0x4469) extension, which OpenSSL does not recognize. A fingerprint
+computed from the extensions OpenSSL reports would miss all of these.
+'''
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+import argparse
+import hashlib
+import os
+import socket
+import struct
+import sys
+
+SERVER_NAME = b'jax.server.test'
+
+GREASE_CIPHER = 0x0A0A
+CIPHERS = [
+    GREASE_CIPHER, 0x1301, 0x1302, 0x1303, 0xC02B, 0xC02F, 0xC02C, 0xC030, 
0xCCA9, 0xCCA8, 0xC013, 0xC014, 0x009C, 0x009D, 0x002F,
+    0x0035
+]
+
+SIGNATURE_ALGORITHMS = [0x0403, 0x0804, 0x0401, 0x0503, 0x0805, 0x0501, 
0x0806, 0x0601]
+
+EXT_SERVER_NAME = 0x0000
+EXT_ALPN = 0x0010
+EXT_ALPS = 0x4469
+FIRST_GREASE_EXTENSION = 0x2A2A
+LAST_GREASE_EXTENSION = 0x9A9A
+
+
+def is_grease(value: int) -> bool:
+    """Identify a reserved GREASE value.
+
+    :param value: Unsigned 16-bit cipher or extension identifier.
+    """
+    return (value & 0x0F0F) == 0x0A0A and (value >> 8) == (value & 0xFF)
+
+
+def u8_prefixed(data: bytes) -> bytes:
+    """Prefix bytes with their one-byte length.
+
+    :param data: Payload of at most 255 bytes.
+    """
+    return struct.pack('!B', len(data)) + data
+
+
+def u16_prefixed(data: bytes) -> bytes:
+    """Prefix bytes with their network-order two-byte length.
+
+    :param data: Payload of at most 65535 bytes.
+    """
+    return struct.pack('!H', len(data)) + data
+
+
+def u16_list(values: list[int]) -> bytes:
+    """Encode a list of network-order unsigned integers.
+
+    :param values: Unsigned 16-bit identifiers to concatenate.
+    """
+    return b''.join(struct.pack('!H', v) for v in values)
+
+
+def extensions() -> list[tuple[int, bytes]]:
+    '''Return the ClientHello extensions, in Chrome's wire order.'''
+    server_name = u16_prefixed(b'\x00' + u16_prefixed(SERVER_NAME))
+    alpn = u16_prefixed(u8_prefixed(b'h2') + u8_prefixed(b'http/1.1'))
+    groups = u16_prefixed(u16_list([0x1A1A, 0x001D, 0x0017, 0x0018]))
+    key_share = u16_prefixed(u16_list([0x1A1A]) + u16_prefixed(b'\x00') + 
u16_list([0x001D]) + u16_prefixed(os.urandom(32)))
+    supported_versions = u8_prefixed(u16_list([0x3A3A, 0x0304, 0x0303]))
+    return [
+        (FIRST_GREASE_EXTENSION, b''),
+        (EXT_SERVER_NAME, server_name),
+        (0x0017, b''),  # extended_master_secret
+        (0xFF01, b'\x00'),  # renegotiation_info
+        (0x000A, groups),  # supported_groups
+        (0x000B, u8_prefixed(b'\x00')),  # ec_point_formats
+        (0x0023, b''),  # session_ticket
+        (EXT_ALPN, alpn),
+        (0x0005, b'\x01\x00\x00\x00\x00'),  # status_request
+        (0x000D, u16_prefixed(u16_list(SIGNATURE_ALGORITHMS))),  # 
signature_algorithms
+        (0x0012, b''),  # signed_certificate_timestamp
+        (0x0033, key_share),  # key_share
+        (0x002D, u8_prefixed(b'\x01')),  # psk_key_exchange_modes
+        (0x002B, supported_versions),  # supported_versions
+        (0x001B, u8_prefixed(u16_list([0x0002]))),  # compress_certificate
+        (EXT_ALPS, u16_prefixed(u8_prefixed(b'h2'))),  # application_settings
+        (LAST_GREASE_EXTENSION, b'\x00'),
+        (0x0015, bytes(16)),  # padding
+    ]
+
+
+def client_hello_records(fragment_size: int = 0) -> bytes:
+    '''Return TLS records holding the ClientHello.
+
+    :param fragment_size: When non-zero, split the ClientHello across records
+        of at most this many bytes.
+    '''
+    body = struct.pack('!H', 0x0303) + os.urandom(32) + 
u8_prefixed(os.urandom(32))
+    body += u16_prefixed(u16_list(CIPHERS))
+    body += u8_prefixed(b'\x00')
+    body += u16_prefixed(b''.join(struct.pack('!HH', t, len(d)) + d for t, d 
in extensions()))
+    handshake = b'\x01' + struct.pack('!I', len(body))[1:] + body
+    size = fragment_size or len(handshake)
+    fragments = [handshake[i:i + size] for i in range(0, len(handshake), size)]
+    return b''.join(struct.pack('!BHH', 0x16, 0x0301, len(f)) + f for f in 
fragments)
+
+
+def truncated_sha256(values: list[str]) -> str:
+    """Hash comma-separated fields using JA4's truncated SHA-256 format.
+
+    :param values: Ordered hexadecimal fingerprint fields.
+    """
+    return hashlib.sha256(','.join(values).encode()).hexdigest()[:12]
+
+
+def expected_ja4() -> str:
+    '''Return the JA4 fingerprint computed from every extension on the wire.
+
+    The c section hashes the signature algorithms per the JA4 specification.
+    '''
+    ciphers = [c for c in CIPHERS if not is_grease(c)]
+    types = [t for t, _ in extensions() if not is_grease(t)]
+    hashed_types = [t for t in types if t not in (EXT_SERVER_NAME, EXT_ALPN)]
+
+    part_a = f't13d{len(ciphers):02d}{len(types):02d}h2'
+    part_b = truncated_sha256(sorted(f'{c:04x}' for c in ciphers))
+    sigalgs = ','.join(f'{a:04x}' for a in SIGNATURE_ALGORITHMS)
+    part_c = hashlib.sha256(f"{','.join(sorted(f'{t:04x}' for t in 
hashed_types))}_{sigalgs}".encode()).hexdigest()[:12]
+    return f'{part_a}_{part_b}_{part_c}'
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('port', type=int, help='The TLS port to send the 
ClientHello to.')
+    parser.add_argument(
+        '--fragment-size', type=int, default=0, help='Split the ClientHello 
across records of at most this many bytes.')
+    args = parser.parse_args()
+
+    with socket.create_connection(('127.0.0.1', args.port), timeout=5) as sock:
+        sock.sendall(client_hello_records(args.fragment_size))
+        # Wait for the ServerHello so that the ClientHello has been processed.
+        response = sock.recv(5)

Review Comment:
   The script closes the TCP connection immediately after reading 5 bytes of 
the server response, which can provoke server-side TLS errors/noise depending 
on logging configuration and timing (potentially making the subsequent 
diagnostics assertions flaky). To make the test more robust, perform a cleaner 
shutdown (e.g., read and discard more of the ServerHello/handshake or 
send/attempt TLS close_notify semantics if practical for this raw-socket 
approach) before closing.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to