Commit graph zephyr/subsys
Author SHA1 Message Date
Robert Lubos
505e454514 net: ipv4: acd: Assert that the interface link address is valid
net_if_get_link_addr() returns NULL when passed a NULL interface, so
static analysis reports both dereferences of its result in the ARP input
handler as possible NULL dereferences. The link address is never NULL
for an initialized interface, so fetch it once for the whole function
and assert on it instead of adding a runtime check for a case that
cannot happen.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-14 15:16:30 +02:00
Robert Lubos
e6853592c7 net: core: Assert that the interface link address is valid
net_pkt_lladdr_if() returns NULL when the packet has no interface set,
so static analysis reports passing its result to memcpy() as a possible
NULL argument. The interface is always set for a packet reaching the
send path, so assert on it and reuse the pointer for both copies.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-14 15:16:30 +02:00
Jukka Rissanen
c95d8a5f33 net: lwm2m: Copy only the resolved address, not the whole storage
lwm2m_parse_peerinfo() copied sizeof(client_ctx->remote_addr_storage)
bytes out of res->ai_addr. That field is a struct net_sockaddr pointer
and nothing in the API says the object behind it is storage sized. The
in-tree resolver happens to point it at zsock_addrinfo._ai_addr, which
is a struct net_sockaddr_storage, but the offloaded resolvers do not:
eswifi, simplelink and the standalone modem drivers all point ai_addr
at a struct net_sockaddr_in. Reading 24 bytes out of an 8 byte heap
allocation is an out of bounds read.

Use res->ai_addrlen, which the resolver is required to set, and fail
the lookup if that length does not fit the destination, so that a bad
length from an offloaded resolver cannot overflow the storage either.
Clear the storage first, as the path is only reached after a failed
net_addr_pton() that has already written part of it, and a short copy
would leave those bytes behind.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 15:15:57 +02:00
Jukka Rissanen
9e7cc806c8 net: coap: Do not size the pending address copy by guesswork
Commit c2d40b3010 ("net: coap: Use net_sockaddr_storage for address
storage") made the address copy in coap_pending_init() pick its length
by testing for NET_AF_INET and falling back to sizeof(struct
net_sockaddr_in6) for everything else. That fallback is 24 bytes
regardless of the configuration, while coap_pending.addr_storage is
only NET_SOCKADDR_MAX_SIZE, which is sizeof(struct net_sockaddr_in)
(8 bytes) in an IPv4 only build.

The fallback is reachable. coap_client_req() accepts a NULL address
when the socket is connected, which leaves coap_client_internal_request
addr zeroed, and the zeroed family is then passed on to
coap_pending_init(). The resulting overflow starts at the first member
of struct coap_pending and clobbers pending->id, so the ACK for the
request never matches and the message is retransmitted until it times
out.

Use net_family2size() instead. An unknown family yields 0, so nothing
is copied and the address is left zeroed, which is what the connected
socket case wants. A family whose address cannot fit the destination
at all is a caller error and is now rejected with -EINVAL rather than
stored truncated.

coap_observer_init() and coap_observer_init_oscore() already used
net_family2size(), but neither bounded it by the destination either,
so an oversized family runs past coap_observer.addr into the token
that follows it. Both return void and cannot report the error, so
clamp there. Use min() rather than MIN(), as the family size is a
function call that MIN() would expand twice.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 15:15:57 +02:00
Aziz Sellami
0a99b8611f shell: shell_help: handle intentional indentation
The whitespace-skipping loop in formatted_text_print() advances past
every character for which isspace() returns non-zero. Because isspace()
matches both newlines and ordinary spaces, any leading spaces that
follow
a '\n' in a help string were being discarded, stripping intentional
indentation from continuation lines.

Fix this by breaking out of the loop immediately after consuming the
'\n'. The newline itself must still be skipped to prevent an empty line
from being printed, but the spaces that follow it on the next line are
part of the author's intended layout and must be preserved.

Before this fix, a help string such as:

  "[-v] [-n <count>]\n"
  "    Options:\n"
  "        -v          verbose output\n"
  "        -n <count>  number of iterations (default: 1)"

was rendered as:

  test - [-v] [-n <count>]
         Options:
         -v          verbose output
         -n <count>  number of iterations (default: 1)

After this fix:

  test - [-v] [-n <count>]
             Options:
                 -v          verbose output
                 -n <count>  number of iterations (default: 1)

Signed-off-by: Aziz Sellami <aziz.sellami@nxp.com>
2026-08-14 15:14:18 +02:00
Anas Nashif
d2e051d6ae testsuite: add tc_capture output-capture helper
Add a reusable helper that records printk and logging output produced
during a test into an in-memory buffer, so tests can assert on the text
emitted without wiring up their own log backend or printk hook.

Both output routes are handled transparently: printk output (and logging
in minimal mode, which is routed through printk) is captured by wrapping
the printk character-output hook, while full logging output is captured
through a dedicated log backend. The API (tc_capture_start/stop/contains/
get/clear) is declared in zephyr/tc_capture.h and gated behind the new
CONFIG_TEST_CAPTURE option.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-14 15:13:19 +02:00
Can Wang
4a40584619 bluetooth: classic: map: fix macro usage and variable references
Fix several issues in the MAP (Message Access Profile) implementation:

- Fix issues in `MAP_REQUIRED_APP_PARAM_LIST` and
  `MAP_REQUIRED_HDR_LIST` macro handling.
  The original implementation does not correctly detect
  single-argument invocations. When only one parameter is
  provided, `count` is evaluated as 0 and `tags` becomes
  NULL, resulting in incorrect parsing behavior.

- Correct field name from `tags to `hdrs` in `MAP_REQUIRED_HDR_LIST`
  empty case to match the actual struct member

- Add missing `BT_MAP_APPL_PARAM_TAG_ID_MAS_INST_ID` to
  `SEND_EVENT_REQUIRED_AP` definition

- Fix incorrect reference from `map_mas_functions` to
  `map_mns_functions` in `mce_mns_get_req_cb` function

Fix #115628.

The bug reported in #115628 was masked by the macro handling
issue and became visible only after that issue was fixed.

Signed-off-by: Can Wang <can.wang@nxp.com>
2026-08-14 10:49:37 +01:00
Jukka Rissanen
d5738bba5c net: quic: Do not evict in-flight packets from the sent history
The sent-packet history is a fixed ring: recording a new packet
overwrote whatever the ring index pointed at, even an entry still in
flight. Overwriting an in-flight entry forgets its loss-recovery
state, and for a packet carrying stream data it also drops the
annotation that releases the stream TX buffer when the packet is
acknowledged. Once more packets than the history size were in flight
at once, which is easy for a fast sender bursting small writes before
the first acknowledgment returns, the acknowledgments for the evicted
packets released nothing, the acked-bytes frontier could never advance
past the hole, and the stream TX buffer stayed permanently full: the
stream wedged and the connection died at the idle timeout.

Reproduced with the QUIC echo service on native_sim and an aioquic
client sending 100 small packets: the echo stopped at exactly
CONFIG_QUIC_STREAM_TX_BUFFER_SIZE bytes and the connection idled out.

Fix it in three parts. Recording a sent packet now scans for a slot
that is no longer in flight before falling back to an overwrite, and
a forced overwrite prefers a victim without a stream annotation,
whose loss does not wedge anything. The stream data send paths refuse
to send when the history has no free slots beyond a small reserve and
return -EAGAIN, so the application backs off and retries when
acknowledgments free slots; the reserve keeps room for ack-eliciting
control packets, window updates and the like, that are sent from
paths that cannot back off. Finally, the ACK processing raises the
stream send signal even when no buffer bytes were released, so a
sender gated on the full history wakes up to retry.

Verified with the echo service: 100 and 1000 packet runs now pass
repeatedly, where 100 packets previously wedged every time.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 10:39:27 +01:00
Jukka Rissanen
a048d9fdf0 net: quic: Implement key update for 1-RTT packets
RFC 9001 Section 6 rotates the packet protection keys during a
connection: a sender derives the next-generation traffic secret with
the "quic ku" label, protects new packets with keys from it, and
signals the change by flipping the key phase bit. The header
protection keys never change. Until now the phase bit was only used
to detect an update and close the connection, so keys were never
rotated and a peer-initiated update ended the connection at the idle
timeout.

Keep the generation 0 application traffic secrets when they are
installed and select the RX keys by the key phase bit: a packet whose
bit does not match the current phase is trial-decrypted with the
next-generation keys. The bit is attacker controlled until the AEAD
check passes, so a failed trial drops the packet without touching any
state. The candidate keys are derived once per generation and
retained across failed trials (Section 6.3), so a forged phase bit
costs one AEAD check like any other forged packet instead of a key
derivation per packet. On success the update commits atomically: the
send keys follow the peer to the new phase first (Section 6.2), then
the old RX keys become the previous generation so packets reordered
from before the update still decrypt, disambiguated by the lowest
packet number seen in the current phase.

quic_endpoint_initiate_key_update() starts an update locally. Per
Section 6.1 it refuses to run before the handshake is confirmed,
tracked with a new endpoint flag set when the server completes the
handshake and when the client receives HANDSHAKE_DONE, and it
refuses a subsequent update until the peer has acknowledged a packet
sent in the current phase, tracked from application-level ACK
frames. A phase comparison would not do: with simultaneous updates
the phases align while the peer has yet to decrypt anything of the
new generation, and updating again would skip a generation and
silently end the connection. Nothing calls the function
automatically yet; wiring it to the Section 6.6 AEAD limits is left
as follow-up work, as is serializing the TX key replacement against
a concurrent send, which a caller must currently avoid.

The traffic secrets and the previous- and next-generation keys are
destroyed and wiped with the rest of the endpoint crypto state.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 10:39:20 +01:00
Johan Hedberg
204c36b896 Bluetooth: Classic: HFP: Cancel AG work items on disconnect
hfp_ag_disconnected() cancels the TX work and the per-call work items
(via release_call()), but leaves ongoing_call_work and slc_work
untouched. Nothing else cancels them on the disconnect path either:
ongoing_call_work is only canceled when the application reports the
ongoing calls in time, and slc_work is never canceled anywhere.

A work item that survives the disconnect is more than just a stale
timeout: hfp_ag_disconnected() clears ag->acl_conn, which marks the AG
slot as reusable, and hfp_ag_create() then wipes the whole struct with
memset() when the slot is picked up for a new connection. Zeroing a
delayable work whose timeout is still linked into the kernel timeout
list, or a work item still queued on a workqueue, corrupts the kernel's
bookkeeping.

Cancel both work items when the connection goes down, next to the
existing TX work cancellation.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-14 10:39:11 +01:00
Johan Hedberg
a10d18c3be Bluetooth: Classic: AVDTP: Cancel timeout work on disconnect
Every AVDTP response handler cancels session->timeout_work before
clearing the pending request, but bt_avdtp_l2cap_disconnected() only
clears the request. A command that is still outstanding when the
signalling channel goes down therefore leaves the AVDTP_TIMEOUT timer
armed.

The stale timeout itself is harmless (session->req is NULL by the time
it fires), but the session object is embedded in struct bt_a2dp, and
a2dp_get_connection() wipes that struct with memset() when the
connection slot is reused. Zeroing a delayable work whose timeout is
still linked into the kernel timeout list corrupts the kernel's timeout
bookkeeping.

Cancel the timeout work on disconnect, like the response handlers do.
To make sure the work item is always initialized by the time the
disconnected callback can run, move its initialization from
avdtp_send_cmd() to the session establishment paths (bt_avdtp_connect()
and bt_avdtp_l2cap_accept()), next to the existing session work
initialization. This also stops avdtp_send_cmd() from re-initializing
the work item on every command.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-14 10:39:00 +01:00
Johan Hedberg
901130ae2d Bluetooth: Classic: Guard limited discoverable timeout during disable
The limited discoverable duration timer is only canceled by
bt_br_set_discoverable(false, ...). Nothing on the bt_disable() path
stops it.

In the normal disable path this goes unnoticed, because
hci_reset_complete() clears BT_DEV_LIMITED_DISCOVERABLE_MODE and a late
firing of the timer is a no-op. But when the HCI driver has the
no-reset quirk, the flag survives, and the timer can then fire with the
transport closed: the handler calls bt_br_set_discoverable(false,
false), which sends HCI_Write_Scan_Enable through
bt_hci_cmd_send_sync(). No response can ever arrive, so the call ends
in the 10 second "Controller unresponsive" assertion.

Canceling the timer in bt_disable() would trade this for a different
bug: disabling can fail and resume operation (the driver close op is
optional, so bt_hci_close() may return -ENOSYS, and an actual close
failure also restores the stack to an operational state), and a
canceled timer would then leave the controller in limited discoverable
mode indefinitely.

Instead, guard the timeout handler with BT_DEV_READY: a timeout that
fires while the stack is disabled (or is being disabled) becomes a
no-op, while a failed bt_disable() restores BT_DEV_READY with the timer
still armed, so the limited discoverable deadline keeps being honored.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-14 10:38:48 +01:00
Jukka Rissanen
18bc474809 net: if: Move the all-routers join comment next to the join
The comment explaining the all-routers multicast join and why it is
done outside net_if_lock() sat above net_ipv6_ra_update_timer(), which
reads as if it described the timer update. Move the timer call above
the comment so that the comment is attached to the code it explains.

Assisted-by: Claude:Opus-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 10:38:35 +01:00
Jukka Rissanen
f60ecc3301 net: dhcpv6: server: Do not invent a lease for Renew and Rebind
Renew and Rebind ask the server to extend an existing lease, but both
were routed through dhcpv6_server_bind(), which creates a binding when
the client DUID is not found. A client whose lease had already been
reaped, or one the server never knew about, was therefore handed a
brand new address and prefix as if it had gone through the usual
Solicit/Request exchange.

Look up the binding first and only extend the lease when it exists.
Without one, a Renew is answered with empty IAs carrying the NoBinding
status (RFC 8415 ch. 18.3.4) so that the client falls back to
Solicit/Request, and a Rebind, which is multicast and may well be
meant for another server on the link, is silently discarded
(ch. 18.3.5).

The reply construction shared by Solicit, Request, Renew and Rebind is
split out into dhcpv6_server_grant() as the three cases no longer run
in sequence.

Assisted-by: Claude:Opus-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 10:38:35 +01:00
Jukka Rissanen
8b9b878124 net: dhcpv6: server: Answer Confirm based on the client addresses
RFC 8415 ch. 18.3.3 has the server decide whether the addresses a
client sends in a Confirm are still appropriate for the link it is
attached to. The server did not look at those addresses at all: it
only checked whether a binding for the client DUID existed, replied
NotOnLink when it did not and Success when it did. That is wrong in
both directions. A client that kept its DUID but moved to another
link was told Success, and a client the server has no record of was
told NotOnLink even though the RFC requires a server that cannot
perform the test to stay silent.

Parse the IA Address options in the incoming IAs and compare them
against the address pool prefix, which is the link the server serves.
All addresses on link gives Success, any address elsewhere gives
NotOnLink, and a Confirm without any address is not answered at all.

The Reply now carries only the Client ID, Server ID and Status Code
options as ch. 18.3.3 describes, instead of also echoing the IA_NA and
IA_PD of the binding.

Assisted-by: Claude:Opus-5
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2026-08-14 10:38:35 +01:00
Anas Nashif
303c5a11ba usb: name the parameters in function declarations
MISRA C:2012 Rule 8.2 requires every parameter in a function type to be
named, including the parameters of function pointer parameters.
usb_transfer_ep_callback() and the endpoint iteration helper declared
their parameters with bare types.

Name them after the arguments the documentation or the
definitions already use. No functional change.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-14 10:38:08 +01:00
Anas Nashif
eaba510c54 Revert "settings: make the TF-M PSA backend enable PSA Crypto"
This reverts commit 05d03cfeb4.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-14 05:22:53 +02:00
Tomi Fontanilles
05d03cfeb4 settings: make the TF-M PSA backend enable PSA Crypto
It is now needed to have the TF-M Crypto partition enabled, and the
backend needs it in all cases.

Signed-off-by: Tomi Fontanilles <tomi.fontanilles@nordicsemi.no>
2026-08-13 16:22:25 -07:00
Anas Nashif
9ccf9583f3 subsys/profiling: perf: streamline the SMP conditionals
The SMP support was woven through the file as thirteen separate
which made it hard to follow what runs where.

Collapse them into a single PERF_IPI_SAMPLING feature macro and keep the
conditional code behind named helpers:

- The spinlock is now taken unconditionally. On uniprocessor builds
  k_spin_lock() is just an IRQ lock, and it protects the sample buffer
  against the shell commands racing with the timer ISR, which was
  previously unprotected there.
- The IPI plumbing lives in perf_sampling_start(), perf_sampling_stop()
  and perf_sample_other_cpus(), with empty versions when there is no IPI
  sampling, leaving the timer handler and the shell command free of
  conditionals.
- The statistics move into struct perf_stats with reset/print helpers.
  The per-CPU arrays are sized by CONFIG_MP_MAX_NUM_CPUS, which is 1 on
  uniprocessor, so the counters no longer need guarding. As a result the
  statistics are now also printed on uniprocessor builds, minus the IPI
  specific counters. The per-CPU sample counter is now incremented only
  when a trace is actually stored, matching its description, and the
  work handler snapshots buf_full under the lock before printing the
  final status.

Two defects are fixed along the way:

- struct k_ipi_work and the k_ipi_work_*() API are gated on
  CONFIG_SCHED_IPI_SUPPORTED, not on CONFIG_SMP, so an SMP architecture
  without IPI support failed to build.
- The target CPU bitmask was hardcoded to 0x00ff. k_ipi_work_add()
  strips the calling CPU but keeps the remaining bits in work->bitmask
  and waits on those events on the next call, so with fewer CPUs online
  than CONFIG_MP_MAX_NUM_CPUS the bits of the absent CPUs stayed set and
  every later call returned -EBUSY, silently stopping the sampling of
  the other CPUs. Use BIT_MASK(arch_num_cpus()) and check the return
  value.

Assisted-by: Claude:claude-opus-5
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-13 13:16:03 -04:00
Johan Hedberg
9fd2cf1ac1 Bluetooth: SMP: Persist CSRK sign counters across reboots
The local and remote CSRK sign counters are part of the bt_keys
storage blob, but were only ever written to persistent storage when
the bond was initially stored upon pairing completion, i.e. with a
counter value of 0. The increments done at runtime by bt_smp_sign()
and bt_smp_sign_verify() were never written back to storage.

As a consequence, after a reboot the remote sign counter would be
restored to its pairing-time value. Since ATT Signed Write Commands
are sent in plaintext over an unencrypted connection, a passive
eavesdropper could capture them and replay the entire sequence in
its original order after the reboot, passing signature verification
again. This defeats the replay protection required by the Core
Specification, which ties the sign counter to the lifetime of the
CSRK rather than to a power cycle. Security erratum 26047,
integrated in Core Spec v6.2, states this requirement explicitly:
"Conforming implementations shall be required to store the last
verified SignCounter in the security database if data signing is
used" (listed in Core Spec v6.3, Vol 1, Part C, Section 16.3).

Similarly, the local sign counter would be restored to its
pairing-time value, causing the device to reuse already-used counter
values when signing, which a compliant peer will reject as replays.

Fix this by storing the keys after each counter increment. Note that
CSRKs are only ever distributed for bonding pairings, so the keys
being stored here are guaranteed to already have a settings entry,
and bt_keys_store() is a no-op when CONFIG_BT_SETTINGS is disabled.

If storing the keys fails, fail closed: an incoming Signed Write
Command is dropped rather than executed without durable replay
protection (the in-memory increment is kept, since the peer has
already consumed that counter value), and an outgoing signed PDU is
not sent (with the increment reverted, since the counter value has
not been consumed by the peer in that case).

Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Assisted-by: Claude:claude-fable-5
2026-08-13 13:13:23 -04:00
Johan Hedberg
ba8627d91c Bluetooth: ATT: Fix buffer handling on signed write send failure
chan_send() unreferenced the buffer when bt_smp_sign() failed, but
its callers retain ownership of the buffer on failure: process_queue()
and bt_att_chan_send_rsp() requeue it for a later retry,
bt_att_chan_req_send() puts it back into the request, and
att_req_retry() unreferences it. Consuming the buffer inside
chan_send() therefore resulted in a freed buffer being requeued (or
freed a second time) whenever signing an outgoing ATT Signed Write
Command failed, e.g. due to a missing local CSRK.

Additionally, save and restore the buffer state around the signing
call: bt_smp_sign() extends the buffer with the 12-octet signature
before it can fail, so retrying a buffer from a failed attempt would
otherwise extend it by another 12 octets each time. This mirrors what
is already done for the bt_l2cap_send_pdu() error path further down
in the same function.

That pre-signing state also needs to be kept around past the sign
call rather than re-saved afterwards: bt_smp_sign() persists its
incremented sign counter as soon as it succeeds, before the PDU is
handed to L2CAP. If bt_l2cap_send_pdu() subsequently fails, restoring
the already-signed buffer would let a later retry sign it a second
time, appending another 12-octet signature onto a buffer only sized
for one and consuming a second counter value for a single logical
send. Restoring the pre-signing state instead makes a retry sign the
buffer fresh, at the cost of skipping the counter value consumed by
the failed attempt, which is harmless since the receiver only
requires the counter to strictly increase, not stay contiguous. Note
that Zephyr's own signature verification only tolerates such skipped
counter values since the preceding commit, which made it authenticate
PDUs with the received counter value as required by the Core
Specification.

Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Assisted-by: Claude:claude-fable-5
2026-08-13 13:13:23 -04:00
Johan Hedberg
fa3d5b61de Bluetooth: SMP: Fail closed on local sign counter exhaustion
bt_smp_sign() incremented the local sign counter without bound, so
after signing with the final possible value (0xFFFFFFFF) the counter
would silently wrap around to zero and start reusing counter values,
which a compliant peer rejects as replays.

Fail closed with -EOVERFLOW instead once the counter space of the
CSRK is exhausted, making it explicit that signing with this key is
over and that a new pairing needs to distribute a fresh CSRK before
signing can resume. The final possible counter value is intentionally
never used for signing, since a receiver cannot accept it without its
own next expected value wrapping around to zero (see the reasoning in
bt_smp_sign_verify()).

As the spec notes, exhausting a 32-bit sign counter takes roughly 117
years at 100,000 signed messages a day, so this is a purely defensive
measure.

Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Assisted-by: Claude:claude-fable-5
2026-08-13 13:13:23 -04:00
Johan Hedberg
d25a6f7e84 Bluetooth: SMP: Verify signed data using the received sign counter
bt_smp_sign_verify() substituted the locally expected sign counter
value into the received PDU before running the Signing Algorithm,
which effectively requires the peer's counter to match the expected
value exactly. The Core Specification instead requires the received
counter value to be used when authenticating the PDU, with replay
protection provided by rejecting counter values that have already
been used. Core Spec v6.2, Vol 3, Part C, Section 10.4.2 (the last
version to specify the data signing feature, before its removal in
v6.3):

  "The signed data shall be authenticated by performing the Signing
  Algorithm where m is the Data PDU to be authenticated, k is the
  stored CSRK and the SignCounter is the received counter value."

and:

  "The receiving device shall protect against a replay attack by
  comparing the received SignCounter with previously received
  SignCounter from the same peer device. If the SignCounter was
  previously used then the receiving device shall ignore the Data
  PDU."

Vol 3, Part H, Section 2.4.5 states the same in terms of the last
verified counter value:

  "The device performing verification shall store the last verified
  SignCounter in the security database and shall compare it with a
  received SignCounter to prevent replay attacks. If the received
  SignCounter is greater than the stored value then the message has
  not been seen by the local device before and the security database
  can be updated."

Requiring an exact match permanently desynchronizes signing with the
peer as soon as the peer skips a counter value, something that can
happen for legitimate reasons: the peer may consume counter values
for signed PDUs that never end up being received, e.g. when retrying
a locally failed send with a fresh signature, or when disconnecting
with signed PDUs still queued. Once the peer's counter is ahead of
the expected value every subsequent Signed Write Command gets
rejected, with re-pairing as the only way to recover.

Fix this by authenticating the PDU against the counter value it was
received with, accepting any value not lower than the expected one,
and recording the successor of the received value as the new
expectation.

The final possible counter value (0xFFFFFFFF) is rejected as
exhausted rather than accepted, since accepting it would wrap the
next expected value around to zero, re-opening the replay window for
every previously used counter value. A peer that has consumed its
entire counter space needs to distribute a fresh CSRK through a new
pairing to resume signing. As the spec notes, this takes roughly 117
years at 100,000 signed messages a day, so this is a purely
defensive measure.

Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Assisted-by: Claude:claude-fable-5
2026-08-13 13:13:23 -04:00
Robert Lubos
8b81f7131e net: gptp: Make the per-port array bound explicit
The port loops run up to GPTP_PORT_END, which is derived from the
runtime nb_ports field, so static analysis cannot tell that the port
index stays within the CONFIG_NET_GPTP_NUM_PORTS sized arrays and
reports an out-of-bounds access. gptp_add_port() never registers more
ports than those arrays can hold, so assert the bound where the arrays
are indexed rather than changing how the loops terminate.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Robert Lubos
dd7a650781 net: gptp: Assert that interface accessors return valid pointers
net_if_l2_data() and net_if_get_link_addr() return NULL when passed a
NULL interface, so static analysis reports every unchecked dereference
of their result as a possible NULL dereference. These pointers are never
NULL for an initialized interface, so assert on them instead of adding
runtime checks for a case that cannot happen.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Robert Lubos
a110aaa0e3 net: l2: Assert that the interface device pointer is valid
net_if_get_device() returns NULL when passed a NULL interface, so static
analysis reports the unchecked dereference of its result as a possible
NULL dereference. The device is never NULL for an initialized interface,
so assert on it instead of adding a runtime check for a case that cannot
happen.

While at it, reuse the device pointer already fetched rather than
calling net_if_get_device() a second time in the same function.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Robert Lubos
5ee5d00d15 net: virtual: Assert that interface accessors return valid pointers
net_if_get_device() and net_if_l2_data() return NULL when passed a NULL
interface, so static analysis reports every unchecked dereference of
their result as a possible NULL dereference. These pointers are never
NULL for an initialized interface, so assert on them instead of adding
runtime checks for a case that cannot happen.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Robert Lubos
7f1c1f4f54 net: ppp: Assert that context pointers are valid
net_if_get_device(), net_if_l2_data() and net_if_get_link_addr() return
NULL when passed a NULL interface, and ppp_fsm_ctx() returns NULL for an
unknown protocol, so static analysis reports every unchecked dereference
of their result as a possible NULL dereference. These pointers are never
NULL for an initialized interface, so assert on them instead of adding
runtime checks for a case that cannot happen.

While at it, reuse the device pointer already fetched rather than
calling net_if_get_device() a second time in the same function.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Robert Lubos
c37d252e2a net: ethernet: Assert that interface accessors return valid pointers
net_if_get_device(), net_if_l2_data(), net_if_l2() and
net_if_get_link_addr() return NULL when passed a NULL interface, so
static analysis reports every unchecked dereference of their result as a
possible NULL dereference. These pointers are never NULL for an
initialized interface, so assert on them instead of adding runtime
checks for a case that cannot happen.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Robert Lubos
21841bac75 net: ieee802154: Assert that interface accessors return valid pointers
net_if_get_device(), net_if_l2_data() and net_if_get_link_addr() return
NULL when passed a NULL interface, so static analysis reports every
unchecked dereference of their result as a possible NULL dereference.
These pointers are never NULL for an initialized interface, so assert on
them instead of adding runtime checks for a case that cannot happen.

While at it, reuse the device pointer already fetched in
ieee802154_utils.h rather than calling net_if_get_device() again for
every radio API call.

Assisted-by: Cursor:claude-opus-5
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2026-08-13 13:12:11 -04:00
Eliott Speyser
4e53e3712b net: wifi: shell: Fix TWT params typo
Fix typo in wifi shell: `TWT internal` -> `TWT interval`.

Signed-off-by: Eliott Speyser <eliott.speyser@st.com>
2026-08-13 13:11:39 -04:00
Aleksandr Khromykh
ea445d87d2 bluetooth: mesh: delayable_msg: do not send a msg before it is due
k_work_reschedule() withdraws a pending timeout, not a submission that
has already been made: once work_timeout() has fired it clears
K_WORK_DELAYED_BIT and queues the work, and a later reschedule arms a
new timeout while that submission stays queued. delayable_msg_handler()
can therefore run for an expiry that another context has already
consumed, and it popped the head of busy_ctx without looking at
fired_time.

A msg is then transmitted before its deadline, which truncates the
random delay the Access layer transmission rules require and defeats
the collision avoidance the module exists to provide. Any call to
reschedule_delayable_msg() between the timeout firing and the system
workqueue running leaves such a stale invocation behind; the purge path
in bt_mesh_delayable_msg_manage() is the easiest way to hit it, since
it consumes the head itself.

Split the two ways the queue is drained. take_expired_msg() pops the
head only if it is due, and the handler uses it, so a stale invocation
finds nothing to send and only re-arms. take_earliest_msg() pops the
head whatever its fired_time and keeps the purge path forcing out the
oldest msg as before. The due test runs in the same critical section as
the dequeue, so a concurrent context cannot swap the head in between,
and the sending half of push_msg_from_delayable_msgs() becomes
send_delayable_msg() for both callers.

The handler still sends at most one msg per invocation and re-arms;
when the next msg is already due the delay is K_NO_WAIT and the work
runs again straight away, as before.

msg_expired() and reschedule_delayable_msg() compare with a signed
delta, which the previous curr_time < fired_time test got wrong at the
32-bit uptime wrap.

Assisted-by: Claude:claude-opus-4.7
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-08-13 13:10:07 -04:00
Aleksandr Khromykh
0a6da68955 bluetooth: mesh: delayable_msg: serialize list access with a spinlock
free_ctx, busy_ctx, free_chunks and the k_work_delayable are mutated
from two contexts: bt_mesh_delayable_msg_manage() on the BT RX
workqueue and delayable_msg_handler() on the system workqueue. Both are
cooperative, but the enqueuer blocks in bt_mesh_access_send() and
bt_rand(), which lets the handler interleave on unsynchronized state.

That produced two NULL dereferences. delayable_msg_handler() used the
result of sys_slist_get() on busy_ctx unchecked, so once the other
context had drained the list, the fired_time update faulted at a
NULL-based address. allocate_delayable_msg_ctx() tested
sys_slist_is_empty() and then assumed a separate sys_slist_get() would
succeed.

Guard every list mutation, and the fired_time of any ctx on busy_ctx,
with a k_spinlock that is never held across a blocking call.
push_msg_from_delayable_msgs() detaches the head atomically, so
concurrent pushers cannot send the same msg, and the handler no longer
touches busy_ctx.

Detaching before the send has a consequence. A msg being sent is on no
list, so the drain in bt_mesh_delayable_msg_stop() cannot see it, and
on -EBUSY or -ENOBUFS it was queued again behind that drain. On the
suspend path that never resolves, as adv_create_from_pool() refuses to
allocate while suspended. Drop a msg that reaches the front of the
queue while the stack is down instead, so nothing is handed to the
transport after a suspend or a reset, however it got queued.
bt_mesh_suspend() sets BT_MESH_SUSPENDED and bt_mesh_reset() clears
BT_MESH_VALID before stopping the module.

The release-and-report sequence this shares with the send path and with
the drain moves into complete_delayable_msg().

The unit test initialises the mesh flags in tc_setup(), since the
module only sends for a provisioned, running node.

Assisted-by: Claude:claude-opus-4.7
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-08-13 13:10:07 -04:00
Aleksandr Khromykh
097001f187 bluetooth: mesh: delayable_msg: fix ctx leak on manage() ENOMEM path
release_delayable_msg_ctx() used sys_slist_find_and_remove() and only
appended the ctx to free_ctx when it had been found on busy_ctx. But
bt_mesh_delayable_msg_manage()'s ENOMEM error path releases a ctx that
was popped from free_ctx and never inserted on busy_ctx, so
find_and_remove() returns false and the ctx is silently lost from both
lists, permanently reducing the pool.

Append unconditionally; find_and_remove() is a no-op when the ctx is
not on busy_ctx, so the behaviour on the normal release path (ctx
present on busy_ctx) is preserved.

Assisted-by: Claude:claude-opus-4.7
Signed-off-by: Aleksandr Khromykh <aleksandr.khromykh@nordicsemi.no>
2026-08-13 13:10:07 -04:00
Jason Yu
ddc0ea8c28 dsp: powerquad: add NXP PowerQuad hardware DSP backend
Add a DSP backend that offloads element-wise math operations to the
NXP PowerQuad hardware coprocessor found on LPC55S6x and similar SoCs.
Unsupported operations fall back to CMSIS-DSP software implementations.

Accelerated operations: add, sub, mult, scale, negate, and dot_prod
for f32, q31, and q15 types. The implementation uses PowerQuad's
matrix engine with three-tier chunking: full 16x16 blocks, partial
rows of 16, and a CMSIS-DSP tail for remainders under 16 elements.

The backend is enabled via Kconfig (DSP_BACKEND_POWERQUAD) and is
auto-selected when the nxp,lpc-powerquad devicetree node is present.

Assisted-by: Claude Code:claude-opus-4-6
Signed-off-by: Jason Yu <zejiang.yu@nxp.com>
2026-08-13 13:09:32 -04:00
Anas Nashif
bd8c153823 wifi: name the parameters in function declarations
MISRA C:2012 Rule 8.2 requires every parameter in a function type to be
named, including the parameters of function pointer parameters.
The Wi-Fi NAN shell dispatcher, the esp_hosted and Bouffalo Lab drivers
and the hostap and nrf_wifi glue declared callbacks with bare types.

Name them after the arguments the documentation or the
definitions already use. No functional change.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-13 06:36:11 -04:00
Emil Gydesen
007af2bded Bluetooth: Classic: Remove bt_hfp_hf.hf_buffer
Remove bt_hfp_hf.hf_buffer as it is unused.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-13 06:35:50 -04:00
Emil Gydesen
b6afd60c13 Bluetooth: Classic: Remove struct bt_avrcp_req
struct bt_avrcp_req is unused.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-13 06:35:39 -04:00
Emil Gydesen
572453728a Bluetooth: Classic: Remove struct bt_avctp_event_cb
struct bt_avctp_event_cb was unused.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-13 06:35:28 -04:00
Emil Gydesen
03a703c7a5 Bluetooth: ATT: Remove struct bt_att_tx_meta
struct bt_att_tx_meta is unused.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-13 06:35:18 -04:00
Emil Gydesen
2f01c11428 Bluetooth: Host: Remove struct bt_iso_create_param
struct bt_iso_create_param is unused in the stack.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-13 06:35:07 -04:00
Emil Gydesen
4b7a068cdc Bluetooth: Host: Remove unused bt_dev fields
Removed a few unused fields form bt_dev to reduce
memory usage.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2026-08-13 06:34:56 -04:00
Jani Hirsimäki
748a0b1b02 net: mdns_responder: fix wrong A/AAAA addrs on multi-homed hosts
On multi-homed hosts each mDNS listener socket is already bound to one
interface (SO_BINDTODEVICE), so replies still outbound on the interface
that received the query. However, when building the DNS answer,
send_response() chose the address list via
net_if_ipv6_select_src_iface(querier). For link-local queriers that
lookup returns no route and falls back to the default interface, so
A/AAAA records could advertise addresses from the wrong link even though
the UDP reply left the correct socket.
Pass the bound socket's interface from the dispatcher into send_response()
and use it for create_answer(), so advertised addresses match the link
the query arrived on.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2026-08-13 06:33:59 -04:00
Lyle Zhu
b020633f4b bluetooth: classic: sdp: improve error handling in sdp_client_get_total
Refactor `sdp_client_get_total()` to add comprehensive error handling
and validation for SDP sequence parsing.

Check the remaining buffer length before pulling data from the buffer.
Using `BT_SDP_SEQ_UNSPEC` to check the SEQ type. And only handle the
frame if the total length is valid.

The function now properly validates input data and returns appropriate
error codes, preventing potential buffer underflow and invalid data
processing in SDP client operations.

Signed-off-by: Lyle Zhu <lyle.zhu@nxp.com>
2026-08-13 06:33:28 -04:00
Anas Nashif
d46238fd27 logging: do not pass an uninitialized spinlock key
process_lock_acquire_if_needed() returns early without writing *key when
CONFIG_LOG_IMMEDIATE_CLEAN_OUTPUT is disabled or the lock is not needed.
msg_commit() then passes that indeterminate value by value to
process_lock_release_if_needed(), which is undefined behaviour even
though the callee does not use it in that case.

Reported by the GCC static analyzer
(-Wanalyzer-use-of-uninitialized-value).

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Assisted-by: Claude:claude-opus-5
2026-08-13 06:32:45 -04:00
Nicolas Pitre
7fab907cf1 kernel: timeout: add sys_clock_idle_enter() for the low-power idle handoff
Entering idle is signalled to the driver through the idle argument of
sys_clock_set_timeout(), which every driver has to carry whether or not
it has anything to hand off. Give the transition its own interface.

Add a weak sys_clock_idle_enter() hook, called by the power management
path when the CPU is about to be put to sleep. A driver that can
reconfigure for low power, hand over to a wakeup timer, or stop its
clock does so there; one that cannot needs no implementation at all.
The default forwards to sys_clock_set_timeout() with the deprecated idle
argument set to true, so a driver keying on that argument keeps working
until it migrates. Recovery is sys_clock_idle_exit(), as before.

The decision in pm_system_suspend() mirrors the one reprogram_next()
makes for a running system. Nothing to wake up for, with the uptime
allowed to drift, is handed over as SYS_CLOCK_IDLE_FOREVER so a driver
can stop its clock knowing sys_clock_idle_exit() will follow; anything
else is a wakeup deadline, adjusted for the exit latency as before.

The hook is issued on every suspend. The idle argument it replaces only
reached the driver when the exit latency was non-zero, so a platform
declaring none left a driver no way to learn the CPU was going to sleep,
which is when a handoff to a low-power wakeup timer has to happen. Where
the deadline needs no adjusting the driver is simply asked for the one it
already has.

That condition arrives in its own value rather than as K_TICKS_FOREVER,
which is unusable in an unsigned tick count: it is (int64_t)-1 with
CONFIG_TIMEOUT_64BIT and UINT32_MAX without it, so a driver comparing
against it would be testing two different things depending on the
configuration. SYS_CLOCK_IDLE_FOREVER sits above SYS_CLOCK_MAX_WAIT, the
longest wait the kernel ever asks for, so it cannot alias a deadline.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-08-12 19:27:28 -04:00
Appana Durga Kedareswara rao
23a45fb0e2 debug: coredump: export per-CPU current-thread offsets on SMP
subsys/debug/thread_info.c previously refused to build DEBUG_THREAD_INFO
at all on SMP: its K_CURR_THREAD offset is offsetof(struct _cpu, current)
applied to struct z_kernel, which only ever resolves to cpus[0].current,
so it #error'd out for CONFIG_MP_MAX_NUM_CPUS > 1 and DEBUG_THREAD_INFO
carried a "depends on !SMP".

Remove that restriction and append two new offset-table entries,
CPU_STRIDE (sizeof(struct _cpu)) and NUM_CPUS, so a consumer can compute
every CPU's current thread as cpus[i].current = K_CURR_THREAD +
i * CPU_STRIDE. The entries are append-only, so they don't change the
interpretation of any existing offset: a debugger plugin that doesn't
know about them keeps seeing cpus[0] only, exactly as before.

With DEBUG_THREAD_INFO now SMP-safe, the coredump THREADS-mode and
threads-metadata options select it unconditionally instead of falling
back to THREAD_MONITOR on SMP, so the offline GDB thread enumeration
path is available on both SMP and non-SMP targets.

Signed-off-by: Appana Durga Kedareswara rao <appana.durga.kedareswara.rao@amd.com>
2026-08-12 19:25:12 -04:00
Johan Hedberg
be50057884 Bluetooth: Classic: Route work items to the Bluetooth workqueue
Migrate the BR/EDR (Classic) host's internal work items from the system
workqueue to the dedicated Bluetooth workqueue by using the
bt_work_submit(), bt_work_schedule() and bt_work_reschedule() helpers.

This covers AVCTP, AVDTP, BR, HFP AG state-machine, SLC and call work,
HID Device (INTR connection timeout and Virtual Cable Unplug
disconnect), L2CAP BR, and RFCOMM.

Keep HFP AG TX-notification work on the system workqueue because it
releases TX contexts that Bluetooth-workqueue handlers may wait for.

Since the Bluetooth workqueue stays alive across bt_enable()/bt_disable()
cycles, a delayable item armed at teardown time can fire after its
connection is gone. Add the same ACL connection guard to
l2cap_br_rtx_timeout() that the retransmission and monitor timeout
handlers already have, and a corresponding guard to
rfcomm_session_rtx_timeout(), so that a stale timeout cannot attempt
signalling (including a potentially blocking K_FOREVER PDU allocation)
on a connection that no longer exists.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-12 19:24:15 -04:00
Johan Hedberg
22896cb8d6 Bluetooth: Host: Route LE host work items to the Bluetooth workqueue
Migrate the LE host's internal work items from the system workqueue to the
dedicated Bluetooth workqueue by using the bt_work_schedule(),
bt_work_reschedule() and bt_work_submit() helpers.

This covers advertising (limited advertising timeout), ATT (channel
timeout, EATT connection work), connections (deferred work and
auto-initiated procedures), GATT (service changed, delayed store,
database hash, multiple notifications), identity (RPA update), L2CAP (RTX
and RX work), settings (ID and IRK store), and SMP (timeout).

Migrating the per-connection deferred work is what keeps the existing
teardown code correct: that work item performs the L2CAP channel and
profile teardown (including the ATT and SMP disconnected callbacks), and
the non-blocking k_work_cancel*() calls in those paths only reliably stop
a concurrently running work item when both run on the same workqueue.
Keeping teardown on the system workqueue while the canceled work items
run on the Bluetooth workqueue would turn those cancellations into races.
For the same reason the SMP timeout moves along with it.

Additionally, cancel a dynamic L2CAP channel's RX work in
l2cap_chan_destroy() so that a queued work item cannot be left behind
with a reference to a channel object that the application may free or
re-use after teardown.

Update the id and conn host unit test mocks accordingly: id.c now uses
bt_work_schedule() and conn.c uses bt_work_submit(), bt_work_schedule()
and bt_work_reschedule(), so add fakes for these to the respective
hci_core.c mocks (and drop the now-unused k_work_schedule() and
k_work_reschedule() fakes from the kernel mocks).

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-12 19:24:15 -04:00
Johan Hedberg
9ef7acd7d7 Bluetooth: Host: Add a general purpose Bluetooth workqueue
Add bt_work_submit(), bt_work_schedule() and bt_work_reschedule()
helpers that submit internal host work to the dedicated Bluetooth RX
workqueue instead of the shared system workqueue.

Start the workqueue on the first bt_enable() call and keep it alive for
the lifetime of the system. Delayable host work can outlive an individual
Bluetooth enable/disable cycle, so aborting and reinitializing the queue
could strand work item state.

The RX thread abort that bt_disable() used to perform is replaced with a
graceful equivalent: before resetting and closing the transport,
bt_disable() now stops queuing new low-priority HCI packets, discards
the ones already queued, and cancels the RX work synchronously. An
in-flight RX work item is thereby waited for while the transport is
still able to serve any HCI commands it may issue, and a packet that
slips into the queue during the teardown is dropped by the handler
instead of being dispatched after the transport is gone. Unlike the
abort, this cannot terminate the RX handler mid-execution with a buffer
still referenced.

The RX workqueue and dedicated TX processor thread are intentionally kept
separate. Merging them would allow a blocking application callback in the
RX context to stall command processing and reintroduce the deadlock the
TX processor thread was created to avoid.

Subsequent commits migrate selected delayed and immediate host work items
to these helpers.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
2026-08-12 19:24:15 -04:00