Commit graph zephyr/subsys
Author SHA1 Message Date
Johan Hedberg
3b379ec594 Bluetooth: Host: Remove the BT_RECV_CONTEXT choice
Remove the BT_RECV_CONTEXT Kconfig choice and its BT_RECV_WORKQ_SYS
and BT_RECV_WORKQ_BT options. Low-priority HCI packets now always run
on the dedicated Bluetooth RX workqueue.

BT_RECV_WORKQ_SYS existed to save the RX thread stack on
memory-constrained targets, primarily nRF51. Removing the alternate path
simplifies the host threading model and removes a configuration-dependent
RX context and its associated test matrix. The following commit retunes
the affected in-tree nRF51 sample configurations.

This breaking Kconfig change is tracked by RFC #113007. Update the public
GATT callback context documentation, release notes and migration guide,
and remove tests specific to the system-workqueue RX path.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-12 19:24:15 -04:00
Robert Lubos
700888e3ec net: ip: tcp: Check result of ISN secret key generation
An ignored sys_csrand_get() failure left the RFC 6528 secret key zeroed
for the rest of the boot, making the ISN computable from the four-tuple
alone. Generate the key from a single guarded helper that only latches
on success, and fall back to sys_rand32_get() when no cryptographic
randomness is available, as already happens when
CONFIG_NET_TCP_ISN_RFC6528 is disabled.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-12 13:19:27 -04:00
Robert Lubos
f8b05ede94 net: ipv6: Stop using the IID when generation fails
Callers of net_ipv6_addr_generate_iid() only logged a warning and
carried on, so a failed generation left the configured SLAAC address as
:: or, in the ipip case, as uninitialized stack memory. Skip the address
configuration entirely when the IID cannot be generated.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-12 13:19:27 -04:00
Robert Lubos
253315829d net: ip: ipv6: Use CSPRNG for IID secret key
The secret key used to derive RFC 7217 stable and RFC 8981 temporary
interface identifiers is a long-lived protocol secret, so generate it
with sys_csrand_get() instead of the non-cryptographic sys_rand_get().
Fail the IID generation if no cryptographic randomness is available
rather than silently deriving addresses from a predictable key.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-12 13:19:27 -04:00
Emil Gydesen
7d48f226ee Bluetooth: ASCS: Reject ASE CP when there is pending state
If an ASE is already in a pending state change, we reject
any operations on it, as that would, from the point of view
of the client, result in invalid state changes.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-12 13:10:23 -04:00
Emil Gydesen
6c461f291f Bluetooth: CAP: Handle disconnects during procedures
Add support for handling disconnects during CAP procedures.
We treat a disconnect the same way as a write reject / error,
and stop the procedure when it happens.

This explicit handling is needed since many of the subprocedures
in CAP are notification based, and thus we won't get an error
from GATT when there's a disconnect.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-12 13:09:09 -04:00
Fin Maaß
92d269a7c5 net: lib: dns: mdns: improve event handler
reorder stuff in the ipv4 and ipv6 event handlers.

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-08-12 13:09:02 -04:00
Fin Maaß
066234c027 net: lib: dns: mdns: split event handler
split the event handler for the 3 different
event groups (ipv4, ipv6, dhcpv4).

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-08-12 13:09:02 -04:00
Fin Maaß
3747b7e540 net: lib: dns: mdns: use NET_MGMT_REGISTER_EVENT_HANDLER
use NET_MGMT_REGISTER_EVENT_HANDLER,
so we no longer need to init that part during runtime.

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-08-12 13:09:02 -04:00
Fin Maaß
321debc986 net: lib: dns: mdns: don't set external_records(_count)
The initial value of external_records and
external_records is already NULL/0, so we
don't need to set them.

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-08-12 13:09:02 -04:00
Fin Maaß
50d173ea7f net: lib: dns: mdns: use K_WORK_DELAYABLE_DEFINE
use K_WORK_DELAYABLE_DEFINE, so we
don't have do do that during runtime.

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-08-12 13:09:02 -04:00
Emil Gydesen
d38ea6d110 Bluetooth: ATT: rm att_write_rsp
att_write_rsp did 2 things:
1) Performed the write (calling the attr->write callback)
2) When called from att_write_req, it did also allocate
and send a response.

1) is kept in the function, and the function has been
renamed to better fit the functionality of the function.
2) Has been moved from the function to att_write_req, as
that code was only used for that function. Additionally
the code was refactored to allocate the right buffer when
needed, instead of always allocating a BT_ATT_OP_WRITE_RSP
and then unref this and allocate a BT_ATT_OP_ERROR_RSP on
error.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-12 13:08:25 -04:00
Zafer SEN
19289bd752 net: dns: read the dispatcher local port per address family
The dispatcher reads local ports through net_sin() regardless of the
address family, which works only because sin_port and sin6_port happen
to share an offset in struct net_sockaddr_in and net_sockaddr_in6. Add
a small helper that picks the member matching the family instead of
relying on that layout.

For the same reason, restore the address that was bound when
getsockname() fails, rather than clearing the port through a union
member that may not be the right one for the family. A failing call
may still have written to the buffer.

Signed-off-by: Zafer SEN <zafersn93@gmail.com>
2026-08-12 13:07:59 -04:00
Zafer SEN
d7859a7117 net: dns: tolerate getsockname() failure after bind(0)
Commit 9cc8b3a371 ("net: lib: dns: dispatcher: fix ephemeral port
usage") stores the ephemeral port chosen by bind(0) using
getsockname() and treats a failure as fatal. resolve.c propagates
anything other than -EALREADY, so dns_resolve_init() fails and the
device ends up with no DNS at all.

Every in-tree offloaded socket driver except nsos_sockets.c lacks a
.getsockname vtable entry, which VTABLE_CALL reports as -EOPNOTSUPP.

The stored port is only used to match dispatcher registrations, and an
unknown port no longer matches anything, so a failure here need not be
fatal for any errno. Keep the local port at 0 and carry on.

Signed-off-by: Zafer SEN <zafersn93@gmail.com>
2026-08-12 13:07:59 -04:00
Zafer SEN
25df0b462c net: dns: do not match dispatchers on an unknown local port
dns_dispatcher_register() compares the local port of a new context
against every registered one to reject duplicates and to pair a
resolver with a responder. bind(0) leaves the port at 0 when the
socket implementation cannot report the assigned one, and 0 means
"unknown", not "same port".

Two distinct resolver sockets that both kept port 0 were therefore
treated as duplicates and the second registration was rejected with
-EALREADY. Its replies were never dispatched, silently disabling the
server failover added by commit b433371253 ("net: dns: Fall back to
alternate servers").

Exclude port 0 from both the duplicate and the pairing comparison.
Dispatching is keyed per file descriptor, so contexts with an unknown
local port still receive their own traffic.

Signed-off-by: Zafer SEN <zafersn93@gmail.com>
2026-08-12 13:07:59 -04:00
Vinayak Kariappa Chettimada
fde17f2c3d Bluetooth: Controller: Fix retained RX node leak in CIS create
The local and remote CIS Create procedures retain an RX node for the
later host notification, for example when accepting a CIS_IND with a
future instant, or while awaiting the Host reply to a CIS request.

If an unexpected LL Control PDU arrives before that retained node is
consumed, it is routed to the active procedure and takes the invalid
PDU path in llcp_lp_cc_rx() or llcp_rp_cc_rx(). Those paths
completed the procedure without releasing the retained RX node,
violating the invariant checked in llcp_lr_check_done() and
llcp_rr_check_done(), and leaking the referenced RX node memory.

Release the retained RX node before completing the procedure,
mirroring the fix already applied to the remote Connection Update and
the PHY Update procedures.

Add unit tests to tests/bluetooth/controller/ctrl_cis_create that
inject an unexpected LL Control PDU while a retained RX node is
pending. Without the fix each test triggers the retained node
assertion in ull_llcp_local.c or ull_llcp_remote.c; with the fix the
connection is terminated with BT_HCI_ERR_LMP_PDU_NOT_ALLOWED and all
procedure contexts are released.

Assisted-by: GitHub Copilot: Claude Opus 4.8

Signed-off-by: Vinayak Kariappa Chettimada <vich@nordicsemi.no>
2026-08-12 13:07:39 -04:00
Vinayak Kariappa Chettimada
06bf10e3de Bluetooth: Controller: Fix retained RX node leak in PHY update
The local and remote PHY Update procedures retain the RX node for the
later host notification, for example when accepting a LL_PHY_UPDATE_IND
with a future instant.

If an unexpected LL Control PDU arrives before that retained node is
consumed, it is routed to the active procedure and takes the invalid
PDU path in llcp_lp_pu_rx() / llcp_rp_pu_rx(). Those paths completed
the procedure without releasing the retained RX node, violating the
invariant checked in llcp_lr_check_done() / llcp_rr_check_done() and
leaking the referenced RX node memory.

Release the retained RX node and clear the reference before completing
the procedure, mirroring the same fix in the Connection Update
procedure.

Add a unit test to tests/bluetooth/controller/ctrl_phy_update that
completes the remote PHY Update request with a future instant, then
sends an unexpected LL_LENGTH_REQ before the instant is reached.
Without the fix the test triggers the retained node assertion in
ull_llcp_remote.c; with the fix the connection is terminated with
BT_HCI_ERR_LMP_PDU_NOT_ALLOWED and all procedure contexts are released.

Add tests/bluetooth/controller/ctrl_phy_update case
test_phy_update_periph_loc_unexpected_pdu_awaiting_instant: a
peripheral initiates a local PHY Update, the central replies with a
LL_PHY_UPDATE_IND at a future instant so the local procedure retains
the RX node, and then an unexpected LL_REJECT_IND is routed to the
active local procedure before the instant is reached.

Assisted-by: GitHub Copilot: Claude Opus 5

Signed-off-by: Vinayak Kariappa Chettimada <vich@nordicsemi.no>
2026-08-12 13:07:39 -04:00
Vinayak Kariappa Chettimada
7b600129fa Bluetooth: Controller: Fix retained RX node leak in conn update
The remote Connection Update / Connection Parameter procedure retains
the RX node for later host notification, for example when accepting a
LL_CONNECTION_UPDATE_IND with a future instant.

If an unexpected LL Control PDU arrives before that retained node is
consumed, it is routed to the active remote procedure and takes the
invalid PDU path in llcp_rp_cu_rx(). That path completed the procedure
without releasing the retained RX node, violating the invariant checked
in llcp_rr_check_done() and leaking the referenced RX node memory.

Release the retained RX node and clear the reference before completing
the procedure.

Add a unit test to tests/bluetooth/controller/ctrl_conn_update that
sends a valid LL_CONNECTION_UPDATE_IND with a future instant, followed
by an unexpected LL_LENGTH_REQ before the instant is reached. Without
the fix the test triggers the retained node assertion in
ull_llcp_remote.c; with the fix the connection is terminated with
BT_HCI_ERR_LMP_PDU_NOT_ALLOWED and all procedure contexts are released.

Verified with the ctrl_conn_update, ctrl_invalid, ctrl_collision and
ctrl_terminate controller unit tests, all passing.

Assisted-by: GitHub Copilot: Claude Opus 5

Signed-off-by: Vinayak Kariappa Chettimada <vich@nordicsemi.no>
2026-08-12 13:07:39 -04:00
Jukka Rissanen
a1698dad7c net: tcp: Assemble TX segments into a single net_pkt
Each outgoing TCP segment was assembled from two allocations: a
header-only net_pkt, plus the payload net_pkt whose buffer chain was
appended after the headers. The IP/TCP header space that
net_pkt_alloc_with_buffer() already estimates and reserves for the
payload packet was left unused, so every data segment cost an extra
net_pkt and an extra net_buf.

Allocate one net_pkt sized for the payload only and use the header
space the allocator already reserves: write the IP and TCP headers
first and copy the payload right after them. This drops the separate
header-only allocation, and the whole segment lands in a single
net_buf fragment whenever it fits in one buffer, which helps drivers
that prefer contiguous data. Larger segments simply span multiple
fragments as before, so this applies to any buffer configuration and
needs no Kconfig option. Because the allocator's header estimate
also accounts for the TCP options, a segment that carries both an
MSS option and payload stays correct by construction.

tcp_pkt_alloc() now always allocates buffer space instead of
skipping it for a zero-length request: with the TCP protocol hint
the allocator reserves the header space anyway, and the data-less
segments (SYN, pure ACK, FIN) depend on it for their headers.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-12 13:07:09 -04:00
Carlo Kirchmeier
e9f1548135 net: coap: mark COAP OSCORE as experimental
OSCORE support for CoAP (RFC 8613) is a new addition and its API and
behavior may still change. Add "select EXPERIMENTAL" to the
COAP_OSCORE symbol so that enabling it emits the standard experimental
warning and users are aware of its maturity level.

Signed-off-by: Carlo Kirchmeier <carlo.kirchmeier.ext@siemens.com>
2026-08-12 13:03:21 -04:00
Anas Nashif
bba16a596a ztest: compare test_status against an explicit enumerator
end_report() used the enum valued test_status directly as the
controlling expression of an if statement.  MISRA C:2012 Rule 14.4
requires that expression to have essentially boolean type.

Compare against ZTEST_STATUS_OK instead, matching how the rest of the
file tests this variable.  No functional change.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-12 12:59:50 -04:00
Carlo Kirchmeier
ac16fb8efa net: coap: add OSCORE (RFC 8613) multi client support
Replace the per-service OSCORE context provider callback
with a shared, reference-counted context pool that the
server searches by Recipient ID. This lets a single
service protect exchanges for multiple clients
concurrently, each identified by its own OSCORE context,
instead of being limited to one lazily-provided context
per service.

Rework the public API accordingly:

  - coap_oscore_context_init() becomes
    coap_oscore_context_add(), which takes const params
    and inserts the derived context into the pool.
  - coap_oscore_context_free() becomes
    coap_oscore_context_remove(), which is
    reference-counted and returns -EAGAIN while an
    in-flight request, active exchange, or observer still
    references the context.
  - Drop the _oscore_ctx_provider argument from
    COAP_SERVICE_DEFINE_OSCORE and
    COAPS_SERVICE_DEFINE_OSCORE.

Update the OSCORE documentation to describe the
pool-based model.

Signed-off-by: Carlo Kirchmeier <carlo.kirchmeier.ext@siemens.com>
2026-08-12 12:59:15 -04:00
Emil Gydesen
8b54caf0d8 Bluetooth: ISO: Add SDU len checks before recv cb
ISO now verifies that the data received has the same length
as the length field in the BT_ISO_SINGLE or BT_ISO_START
fragment. If it does not, it is dropped in the same way
that ACL drops data.

`bt_conn.rx_len` was only used by ISO, so the field was moved
to `bt_conn_iso` instead. Unlike ACL where the buffer contains
the L2CAP header, the ISO `conn->rx` only contains the data
without the header, so we need to store this information
somewhere, and cannot just rely on the header within conn->rx.

Lastly, there was also a check added for BT_ISO_START to check
if it should have been a BT_ISO_SINGLE instead, effectively
disallowing BT_ISO_CONT or BT_ISO_END with length = 0.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-12 12:58:19 -04:00
Johan Hedberg
094f7de9ef Bluetooth: ATT: Fix truncation of prepare write length
att_prep_write_rsp() declared its len parameter as uint8_t while its only
caller, att_prepare_write_req(), passes buf->len which is a uint16_t. Any
prepare write carrying more than 255 octets of value data therefore had
its length silently truncated to the low byte before being stored in the
uint16_t len member of struct prep_data.

This is only reachable once the negotiated ATT MTU is allowed to exceed
255 via CONFIG_BT_L2CAP_TX_MTU, in which case long writes corrupt the
data handed to the attribute write callback, and a value length whose low
byte happens to be zero degenerates into repeated zero-length writes.

Widen the parameter to uint16_t so that it matches both the caller and
the struct member it is assigned to.

Fixes: #108227

Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Assisted-by: Claude:claude-opus-5
2026-08-12 12:57:54 -04:00
Krzysztof Chruściński
da95dbff26 logging: log_mgmt: Add missing cache releasing
Add missing cache releasing if log_link_get_source_name() fails.
As there was no release on failure it was draining cache to a
point where whole local cache was full but unused.

Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
2026-08-12 09:45:48 -07:00
Lyle Zhu
8ce7d9630c bluetooth: classic: l2cap: fix I/S-frame transmission logic
when an S-frame needs to be sent, the function
`l2cap_br_ret_fc_data_pull()` calls `l2cap_br_send_i_frame()` to
determine whether an I-frame should be sent instead. If an I-frame
needs to be sent, the S-frame is not transmitted; instead, the
S-frame information is sent within the I-frame.

Currently, when `L2CAP_FLAG_RET_I_FRAME` was set, the code would
block a S-frame transmission if any outstanding PDUs existed, and
try to perform a retransmission I-frame, regardless of whether
they needed retransmission. Similarly, when
`L2CAP_FLAG_RET_I_FRAMES` was set, the S-frame transmission was
always blocked without checking if I-frame retransmission was
actually needed.

It leads to an issue that no any I-frames or S-frames are performed.

Fix the L2CAP BR/EDR I-frame transmission logic to properly handle
retransmission scenarios by checking if retransmission is actually
required before blocking new frame transmission.

The change introduces a helper function
`l2cap_br_retransmit_is_required()` that checks if any outstanding
PDUs in the transmission window actually need retransmission by
examining the retransmit flag.

With the changes, the code checks if the outstanding queue is
non-empty for the single frame retransmission case, and uses the new
helper to verify if I-frame retransmission is truly required for the
multiple frames case. This prevents unnecessary blocking of S-frame
transmission when outstanding PDUs don't require retransmission.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-08-12 10:02:57 -04:00
Emil Gydesen
8d3eb55b42 Bluetooth: ISO: Add missing cis_channels[%u]
For the `!is_p_to_c && !is_c_to_p` check we did not log the
index of which parameter was using an invalid paramater.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-12 10:02:42 -04:00
Benjamin Perseghetti
15699711c2 net: gptp: request a TX timestamp for Pdelay_Req
Commit 5950810b0e made TX timestamping opt-in but only flagged Sync
and Pdelay_Resp, the messages that consume their egress timestamps
through callbacks. Pdelay_Req reads its timestamp straight back off the
retained packet, so on flag-gated drivers t1 is always zero, the
computed neighbor prop delay blows the threshold, and asCapable never
asserts, leaving the port DISABLED and the node mute. Set the flag when
the request is prepared.

Fixes: 5950810b0e ("net: ethernet: gptp: use net_pkt_set_tx_timestamping")
Signed-off-by: Benjamin Perseghetti <bperseghetti@rudislabs.com>
2026-08-11 20:54:55 -04:00
Appana Durga Kedareswara rao
6af898d155 debug: coredump: fix z_thread_monitor_lock held across SMP dump I/O
The SMP thread-list walk in process_memory_region_list() held
z_thread_monitor_lock for the entire per-thread dump loop, including
each thread's dump_thread() call. For slow backends (e.g. the UDP
logging backend, which transmits every thread's stack over the
network) this can hold the lock for seconds.

If another CPU's thread exits naturally during that window,
k_thread_abort() -> halt_thread() -> z_thread_monitor_exit() needs
the same lock and spins until the entire dump completes. Confirmed on
versalnet_apu_se9/amd_versalnet_apu/smp via a live backtrace showing
exactly that spin (arm_gic_irq_is_pending <- arch_spin_relax <-
k_spin_lock <- halt_thread <- z_impl_k_thread_abort) while
CONFIG_DEBUG_COREDUMP_BACKEND_LOGGING_UDP was mid-dump.

Snapshot the thread pointers into a small bounded array while holding
the lock, then release it before calling dump_thread() for each
snapshotted thread, so slow per-thread I/O never runs with the lock
held. Confirmed on hardware: hs6_smp_udp_backend now completes and
captures all 165 UDP datagrams cleanly, with no regression on the
non-SMP path.

The snapshot array's size is exposed as
CONFIG_DEBUG_COREDUMP_THREAD_SNAPSHOT_MAX (default 64) instead of a
hardcoded cap, so a system with more monitored threads can capture all
of them; systems that exceed it dump the first N rather than growing
fatal-path stack unbounded. A mid-dump truncation diagnostic is
intentionally not emitted, as it would corrupt the backend's parseable
coredump byte stream.

Signed-off-by: Appana Durga Kedareswara rao <appana.durga.kedareswara.rao@amd.com>
2026-08-11 17:02:57 -04:00
Sharon Lin
aed68ea540 Bluetooth: Host: extract bt_gen_irk() helper for IRK generation
Currently IRK generation via bt_rand() is open-coded in id_create().
Extract a shared bt_gen_irk() helper so that all IRK generation call
sites use the same code path and will always have the same behavior.

This also prepares for the bt_id_reset_irk() API (PR #114930) which
will use the same helper.

Assisted-by: Augment:GLM-5.2
Signed-off-by: Sharon Lin <slin@atmosic.com>
2026-08-11 17:02:49 -04:00
Jordan Yates
7b304fc341 modem: cellular: don't run NULL script
Don't attempt to run a `NULL` periodic script, and add assertions into
`modem_chat` to raise the issue if this does occur.

Signed-off-by: Jordan Yates <jordan@embeint.com>
2026-08-11 17:01:04 -04:00
Jordan Yates
6248e82012 modem: cellular: cmux: fix minimum buffer sizes
Ensure that the CMUX buffer sizes instantiated in `modem_cellular.h`
meet the minimum size required by the CMUX module.

Signed-off-by: Jordan Yates <jordan@embeint.com>
2026-08-11 17:01:04 -04:00
Jukka Rissanen
0aeab0da28 net: quic: Wipe key material that outlives its use
Two places left secret material in memory longer than needed.

The server session ticket cache cleared only the valid flag when a
ticket was consumed or expired, leaving the resumption PSK in bss until
the round-robin store happened to reuse that slot. The handshake code
around it is careful to wipe every stack copy of the same key, so this
was an oversight rather than a decision.

quic_tls_free() cleared the shared secret, the resumption master
secret, the session state and the whole key schedule with memset().
Those are the last writes before the endpoint slot goes back to the
slab, so a compiler is free to drop them. The rest of the file uses
crypto_zero(), which is mbedtls_platform_zeroize() and is not
eliminated.

Use crypto_zero() in both.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
a6c2ae77b1 net: quic: Select the PSK binder label by the PSK provenance
RFC 8446 Section 7.1 derives the PSK binder key with "ext binder" for
an externally provisioned PSK and "res binder" for one that came from a
session ticket. The binder helper hardcoded "ext binder" and was the
only binder routine, so session ticket PSKs were bound with the wrong
label. Both kinds of PSK exist here: TLS_CREDENTIAL_PSK provisions an
external PSK through tls_set_psk(), and resumption stores a ticket PSK
in the session state.

Both sides compute the binder the same way, so Zephyr talking to
Zephyr never noticed, but resumption did not interoperate with a
conforming peer and the domain separation the two labels exist to
provide was lost.

Record the provenance when the PSK is configured and pass it to the
binder helper: the server distinguishes a matched session ticket from
a matched external identity, and the client remembers whether its PSK
came from the session state or from a credential. External PSKs keep
using "ext binder".

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
3b90573230 net: quic: Honour the configured cipher suite list
tls_opt_ciphersuite_list_set() stored what the application passed with
TLS_CIPHERSUITE_LIST into options.ciphersuites, and nothing ever read
that array. An application that restricted the connection to a
particular suite got no enforcement at all: the ClientHello offered the
built-in list regardless, a server picked from the peer's offer
regardless, and a client accepted whatever the server selected.

Add tls_suite_allowed() and apply it in all three places. An empty list
still means no restriction. Building a ClientHello with every suite
excluded now fails with -ENOTSUP rather than sending an empty list.

The ServerHello check also now rejects a suite that was not in our
offer, which was previously accepted as long as it was one we
implement.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
916e08adc1 net: quic: Derive the peer stream limit from streams actually opened
A STREAMS_BLOCKED frame added the number of free pool slots to the
current limit. MAX_STREAMS is a cumulative limit, so adding to it on
every frame let a peer raise it repeatedly without opening or closing a
single stream: with nothing open, each frame added the whole pool size
again.

The limit is what the stream_seq >= limit check in the STREAM frame
handler tests against, so once it has been inflated past any sequence
number the peer intends to use, that check stops constraining anything.

Track how many peer-initiated streams have ever been opened and compute
the limit as that total plus the free slots, so it reflects real
progress and never exceeds what the pool can serve. Only send
MAX_STREAMS when the value actually moves.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
17461bc57b net: quic: Guard the address token buffer length before subtracting
quic_build_address_token() passes out_len minus the fixed header length
to the address copy helper, and only checks that the buffer is large
enough afterwards. Both are size_t, so a buffer shorter than the fixed
header wraps the subtraction to a huge value and the client address is
written past the end.

Every caller in the tree passes a buffer far larger than that, so this
is not currently reachable, but the function is exported for tests and
the check costs nothing.

Verify the buffer can hold the fixed part and the tag before doing the
arithmetic.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
6736c8114d net: quic: Do not answer short datagrams with Version Negotiation
The version check runs before the minimum Initial size guard, so a
datagram carrying an unsupported version was answered with a Version
Negotiation packet whatever its size. RFC 9000 Section 6.1 says a
server should not send one in response to a datagram smaller than the
minimum Initial size.

The reply also goes out before any endpoint lookup or token check, and
quic_send_version_negotiation() bypasses the anti-amplification budget,
so an eight byte long header was enough to make the server emit a
packet toward any spoofed address. The reply echoes the peer's
connection IDs so it is not much larger than the request, but it is
still an unbounded source of packets aimed at a third party.

Drop the datagram instead when it is below the minimum Initial size.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
0c55bc3327 net: quic: Reject malformed ACK ranges
When walking the additional ACK ranges, the start of a range is
computed as end minus the peer supplied range length, with no check
that the length fits. A peer that sends a range larger than the
current end underflows the unsigned subtraction and produces a range
whose start is far above its end. pkt_num_in_ack_ranges() tests
start <= pn <= end, so such a range never matches and the
acknowledgements it should have carried are silently dropped, stalling
loss recovery for those packets.

The existing check for a gap exceeding the available packet number
space also handled the error poorly: breaking out of the range loop
leaves the parse position in the middle of the frame, so the remaining
Gap and ACK Range varints get reinterpreted as frame types by the
outer frame loop.

Return -EINVAL for both malformed cases instead. The frame error path
maps that to a FRAME_ENCODING_ERROR connection close, which is what
RFC 9000 Section 19.3.1 prescribes for a frame that violates its
encoding rules.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
3d75725363 net: quic: Cap the packets sent in reply to one payload
DATA_BLOCKED, STREAM_DATA_BLOCKED, STREAMS_BLOCKED, PATH_CHALLENGE and
NEW_CONNECTION_ID are each answered with a separately encrypted packet,
and the frame loops place no limit on how many frames one payload may
contain.

A DATA_BLOCKED frame is two bytes, so a single 1-RTT datagram can carry
several hundred of them and produce several hundred outgoing datagrams,
each with its own AEAD operation and sendmsg call on one thread. That
turns a small datagram into a large amount of work and traffic, which
matters on a constrained device. The peer's address is already
validated at this point, so this is load against the device itself
rather than a reflector aimed at a third party.

Give each received payload a budget of replies and drop the ones past
it. The peer repeats these frames if it still needs an answer, so the
cost is a delay rather than a stall. CONNECTION_CLOSE and the ACK
covering the packet are sent outside the budget, since those are needed
for correctness.

handle_crypto_level_packet() becomes ZTESTABLE_STATIC so the
accompanying test can drive it.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
9229584027 net: quic: Reject replayed address validation tokens
A token was accepted every time it passed the tag, age and address
checks. Nothing recorded that it had already been used, so the nonce
placed in it was generated, covered by the tag, and then never looked
at again.

Tokens are carried in the Initial packet header before header
protection is applied, so anyone on the path can read one. Replaying it
from a spoofed source address produced an endpoint whose address was
marked validated, which exempts it from the 3x anti-amplification limit,
letting the server be used to send its full handshake flight at the
spoofed victim. NEW_TOKEN values last ten minutes by default, and the
same replay also supplied an unlimited stream of endpoints for
exhausting the endpoint pool.

Track the nonces of accepted tokens in a small table and refuse a token
whose nonce is already there. Entries are dropped once the token is too
old to pass the age check, so the table only covers tokens that can
still be in flight, and the oldest is evicted if it fills. The check
runs after the tag, age and address checks so a forged token cannot
consume a slot.

RFC 9000 Section 8.1.3 asks for exactly this for NEW_TOKEN. A client
retransmitting an Initial is unaffected, since retransmissions match the
existing endpoint and never reach token validation.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
019ca3341d net: quic: Keep the timeout checker running for half-open endpoints
The idle timeout work computes the delay until it next needs to run
from the endpoints it walked, and reschedules itself only when that
delay is non-zero. An endpoint that is still handshaking has no
negotiated idle timeout, so it took the "not negotiated yet" branch and
contributed nothing to that delay.

With every endpoint in that state the work computed a delay of zero,
did not reschedule, and stopped for good. The handshake timeout it
would have enforced then never fired, so half-open endpoints were never
reclaimed. Since the checker is only started when a child endpoint is
successfully created, and that cannot happen once the pool is full, the
endpoint pool stayed exhausted until reboot.

A peer can drive this with very few packets. CONFIG_QUIC_MAX_ENDPOINTS
defaults to a handful and one slot belongs to the listener, so a couple
of Initial packets carrying a valid token but no CRYPTO frame are
enough to fill it. An ACK-only exchange leaves nothing in flight, so the
PTO based reclaim does not run either.

Have an endpoint that is still handshaking contribute the time left on
its handshake timeout, so the checker keeps running and reclaims it.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
a9e71e6721 net: quic: Take the context and endpoint locks in a consistent order
quic_endpoint_unref() takes contexts_lock and then endpoints_lock, and
most of the subsystem follows that order. Three places did the reverse:
quic_context_unref(), the idle timeout sweep, and quic_connection_init(),
each holding the endpoint lock across a call that then wants the
context lock.

That is an AB-BA deadlock. The application thread closing a socket, or
the system workqueue running the idle sweep, can hold endpoints_lock and
block on contexts_lock while the RX thread tearing an endpoint down
holds contexts_lock and blocks on endpoints_lock. Both wait forever and
the networking stack stops. A peer that closes connections while the
application closes sockets is enough to reach it. It stays hidden in
single threaded runs because Zephyr mutexes are recursive per thread.

Acquire contexts_lock before endpoints_lock in all three, and release
both on every exit path.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
405ca2da24 net: quic: Close on a key phase flip that kept the old keys
QUIC_SHORT_KEY_PHASE_MASK was defined but never used anywhere.
Outgoing short headers hardcode key phase 0, and on receive the key
phase bit was discarded, with the application crypto context returned
unconditionally.

Return the unprotected header byte from quic_decrypt_packet() and
close the connection with KEY_UPDATE_ERROR when a packet decrypts
with the current keys but carries a flipped key phase bit. Such a
packet can only come from a peer that changed the bit without
rotating its keys, which RFC 9001 Section 6 does not permit.

This does not yet make a real key update work: a conforming peer that
initiates one protects its packets with the next-generation keys, so
they fail AEAD before the phase bit can be examined and the
connection still goes quiet until the idle timeout. Key update
support that trial-decrypts with the next-generation keys is added on
top of this.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
d9f0adba49 net: quic: Require CertificateVerify before completing the handshake
Handshake messages are dispatched on their type alone. ctx->state is
assigned in a few places but never read to decide whether a message is
allowed to arrive, and nothing recorded that CertificateVerify had been
processed. The only check before declaring the handshake complete was
that a certificate had been received at all.

A certificate is public, so presenting one proves nothing. An active
attacker could complete its own key exchange, replay the real server's
certificate, which chains to a real CA and passes verification, send
Finished, and never send CertificateVerify. Possession of the server's
private key was never demonstrated, and the handshake completed. The
same worked in reverse against a server that requested a client
certificate.

verify_certificate_verify() itself is correct; the problem was that
reaching it was optional. Record that it succeeded in a new
peer_cert_verified flag, clear the flag whenever a Certificate message
is parsed, and refuse to complete a handshake where a certificate was
received but the flag is not set.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
3264c5b31a net: quic: Verify the Finished message received from the peer
The Finished handler updated the transcript with the message and
declared the handshake complete without ever checking it. There was no
psa_mac_verify() anywhere in the subsystem; the only verify_data in the
file is the one built for our own Finished. A Finished carrying
arbitrary bytes was accepted from either peer.

Finished is what proves the peer derived the same handshake secrets and
saw the same handshake transcript, so skipping it removes the downgrade
and tampering protection for the whole exchange. In PSK and resumption
mode, where there is no Certificate and no CertificateVerify, it is the
only explicit peer authentication there is.

Add verify_peer_finished(), which derives finished_key from the peer's
handshake traffic secret, recomputes the HMAC over the transcript, and
compares with psa_mac_verify() so the comparison is constant time. It
runs before the transcript is extended, since verify_data covers every
message up to but not including this one, and it requires the message
to be exactly hash_len bytes.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
7ea45b9a97 net: quic: Check the peer certificate against the requested hostname
verify_peer_certificate() passed NULL as the common name argument of
mbedtls_x509_crt_verify(), which turns off name matching entirely. The
hostname the application set with TLS_HOSTNAME was only ever used to
emit the SNI extension and was never compared against the certificate
the server presented.

A client therefore accepted any certificate that chained to a CA in its
trust store, whatever name it was issued for. An attacker holding a
valid certificate for a domain they control could impersonate any
server the client connected to, without touching the CA.

Pass the configured hostname so the name is checked. Only a client has
a name to verify against; a server authenticating a client certificate
still passes NULL. When required verification runs on a client that set
no hostname, warn that the certificate is accepted for any name it was
issued for.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
1ac2d847d8 net: quic: Stop negotiating ChaCha20 until its header protection works
quic_hp_mask() never fed the sample to the cipher for ChaCha20. It
copied the sample into a local that nothing read, then called
psa_cipher_encrypt(), which is the one-shot API that generates its own
IV for a stream cipher. The first bytes of that output are the
generated IV, so the mask was five bytes of fresh randomness unrelated
to the key or the sample.

Both peers therefore derived different masks, recovered a wrong packet
number length and packet number, built the wrong AAD, and failed every
AEAD decryption. Any connection that negotiated the suite was wedged
from the first Handshake packet. A client could force this on a Zephyr
server by listing ChaCha20 first, and a Zephyr client accepted the
suite whenever a server selected it.

RFC 9001 Section 5.4.4 needs ChaCha20 run with the block counter taken
from the first four bytes of the sample and the nonce from the
remaining twelve. The PSA cipher API cannot express that: it starts the
block counter at zero and psa_cipher_set_iv() only accepts a twelve
byte IV, so the counter cannot be supplied. PSA_WANT_KEY_TYPE_CHACHA20
is not enabled in a QUIC build either, so importing the key would fail
in any case.

Stop offering the suite in the ClientHello, stop selecting it from a
peer's offer, stop accepting it in a ServerHello, and drop it from the
external PSK suites. Make quic_hp_mask() return -ENOTSUP for it rather
than produce a mask that is not derived from the sample, so a later
change that re-enables negotiation fails loudly instead of silently
corrupting headers.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
cb5e77e636 net: quic: Reference endpoints looked up on the RX path
quic_endpoint_lookup() and find_endpoint_by_sock() return an endpoint
found in a table the RX path does not own. Returning it without a
reference is not lifetime safe: a concurrent context close or idle
timeout can drop the endpoint's last reference and free and reuse its
slab slot while the RX path is still using it, for example while
process_short_header() decrypts into it or receive_data() fills its
pending buffer. The owning context's reference does not prevent this,
as closing the context is what drops it.

Take a reference in both lookups while endpoints_lock is still held, so
the slab free in quic_endpoint_unref(), which runs under the same lock,
cannot race the lookup. quic_endpoint_ref_unless_zero() refuses to
resurrect an endpoint whose refcount already reached zero, that is, one
that unref has committed to freeing.

Balance that reference on every caller path. process_short_header() and
process_long_header() release it at their exit labels; receive_data()
releases it once for the endpoint it uses, whether that came from the
socket lookup or the fallback hint.

This also removes an asymmetry that was a denial of service on its own.
process_short_header() released a reference it never took on four
paths, and receive_data() did the same on its address family mismatch
path. A server child endpoint sits at a refcount of one while it is
established, so a single unbalanced unref runs the full teardown and
returns the slot to the slab. On the AEAD failure path an attacker who
can see a connection ID on the wire, which is sent in the clear, and
can spoof the peer address needs one datagram with that connection ID
and a random payload to destroy an established connection, with no keys
and no handshake. RFC 9000 Section 21 requires a packet that fails
decryption to be discarded silently.

The regression needs an established connection with application keys
plus a registered endpoint, which the test suite can only produce
through its end to end helpers; those open and close their own
connections and offer no injection point, so no targeted test
accompanies this change. The existing suite exercises these functions
on every data transfer and passes under twister --enable-asan.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00
Jukka Rissanen
48a5319c57 net: quic: Initialise the context socket to an invalid value
quic_context_init() sets up the fifos, semaphores and lists but never
touches ctx->sock, unlike quic_stream_init() and quic_endpoint_init()
which both mark theirs invalid. Contexts live in bss, so a slot that
has never been used reads back as socket 0.

If such a context is released before a socket is assigned to it, the
teardown in quic_context_unref() sees "ctx->sock >= 0" and closes
descriptor 0, which belongs to something else entirely. This is
reachable when quic_connection_open() fails during connection setup,
for example because the endpoint pool is exhausted, which a peer can
provoke.

Set ctx->sock to -1 during init.

The failure needs a context slot that has never held a socket, which
only happens before the first connection is opened, so it is not
reachable from the test suite without exhausting the endpoint pool and
disturbing every test that follows. No test accompanies this change.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-11 13:45:36 -04:00