The AK value is 6 bytes long, but it was logged using OGS_KEY_LEN (16 bytes),
which causes the hexdump to read beyond the end of the buffer. Replace
OGS_KEY_LEN with OGS_AK_LEN to ensure correct logging and avoid potential
out-of-bounds reads.
This issue is similar to the fix applied in hss-cx-path.c for CVE-2025-15555.
Issues: #4177, #4389
The HTTP upload handling in access_handler() used ogs_malloc() and
ogs_realloc() results directly assigned to request->http.content and
checked with ogs_assert(). On allocation failure this could abort the
process, leading to a potential denial-of-service condition. The pattern
was similar to the issue previously fixed in on_data_chunk_recv()
(CVE-2022-3299).
This change introduces a temporary pointer for memory allocation and
updates request->http.content only after successful allocation. It also
adds overflow-safe length checks before resizing the buffer and removes
assert-based error handling in favor of graceful failure.
This prevents process termination on allocation failure and aligns the
memory handling logic with the hardened implementation used in
nghttp2-based handlers.
Issues: #4387
Add bounds checking to ogs_sbi_parse_plmn_list() and handle_scp_info()
to prevent out-of-bounds writes when input exceeds the fixed array limits.
- ogs_sbi_parse_plmn_list(): limit to OGS_MAX_NUM_OF_PLMN (12)
- handle_scp_info(): limit to OGS_MAX_NUM_OF_SCP_DOMAIN (8)
Without these checks, an unauthenticated HTTP/2 request with oversized
arrays can crash any SBI-based NF (PLMN list: heap overflow → arbitrary
free, SCP domain: stack overflow → stack smashing).
Issues: #4382, #4383
AMF crashes when receiving crafted NGAP messages with an oversized
AMF-UE-NGAP-ID (e.g., 0xc0ffffffff). The value exceeds the 3GPP spec
maximum (2^40-1) and causes ngap_send_error_indication() to fail,
triggering ogs_assert().
Added MAX_AMF_UE_NGAP_ID (0xffffffffffULL) range check after
asn_INTEGER2uint64() in all NGAP handlers.
Issues: #4371, #4375, #4376, #4377, #4378, #4379
This patch improves robustness of several GTPv1/v2 parsing paths by
adding explicit length validation and replacing assert-based checks
on network-controlled data with graceful error handling.
Changes include:
- GTPv1 MM Context parser:
Add bounds checks for xres_len, autn_len and num_vectors to prevent
stack overflows when decoding authentication quintuplets.
- SMF Gn handler:
Validate IMEI(SV) IE length before memcpy to prevent heap overflow
in smf_ue->imeisv.
- SMF Gn handler:
Validate Common Flags IE length before dereferencing to avoid
out-of-bounds reads when malformed IE is received.
- GTPv1 ULI parser:
Replace ogs_assert-based length checks with proper validation and
error return to prevent abort() on truncated User Location
Information IE.
- SMF fd-path:
Replace assertions on ULI payload presence with runtime checks
to avoid process termination on malformed input.
These changes ensure malformed or truncated network messages are
handled gracefully instead of triggering process aborts.
When mme_ue_set_imsi() updates an existing UE IMSI, the previous
code overwrote mme_ue->imsi before removing the old hash entry.
As a result, the old IMSI key could remain in imsi_ue_hash and keep
pointing to the same mme_ue object. After the UE context was removed,
a later lookup by the stale IMSI key could return an invalid context
and trigger a fatal path during re-attach handling.
Remove the old IMSI hash entry before updating mme_ue->imsi, then
register the new IMSI after the update.
Issues: #4357
This patch addresses a potential subscription_data pool exhaustion
issue observed during repeated NF re-registration with the NRF.
Two improvements are introduced:
1) Prevent duplicate NF status subscriptions
Before sending a new NF status subscription request, the code now
checks whether an equivalent subscription already exists in the
local subscription_data list. If a matching subscription (based on
req_nf_instance_id and subscr_cond) is found and it is not already
marked with DELETE_SENT, the new subscription request is skipped.
This prevents repeated subscription creation during re-registration
loops.
2) Ensure local cleanup after DELETE response
When handling HTTP DELETE responses for NF status subscriptions,
the local subscription_data entry is now removed regardless of the
response status. Previously, the entry was only removed on
HTTP 204 (No Content), which could leave stale entries in the local
list when the NRF returned other statuses (e.g., 404).
Keeping stale entries could lead to unbounded growth of
subscription_data and eventual pool exhaustion.
Additionally, successful DELETE operations are logged to improve
debugging visibility.
This change affects all NF state machines that handle subscription
DELETE responses (AMF, AUSF, BSF, NSSF, PCF, SCP, SEPP, SMF, UDM, UDR,
and AF test code).
Issues: #4207
mme_find_served_tai() incorrectly compares the PLMN-ID of TAC range
entries using list0->tai[j].plmn_id instead of list1->tai[j].plmn_id.
When TAC ranges are configured in mme.tai (e.g. tac: [1-11]), the range
entries are stored in list1. However, the lookup logic mistakenly reads
the PLMN from list0 while validating list1 entries, which can cause the
Served TAI match to fail even though the TAC is within the configured
range.
As a result, eNB S1 Setup may fail with:
Cannot find Served TAI. Check 'mme.tai' configuration
This patch fixes the comparison to use list1->tai[j].plmn_id so that TAC
range entries are matched correctly.
Fixes TAC range configuration such as:
tac: [1-11]
Issues: #4345
In smf_gx_cca_cb(), smf_gy_cca_cb(), and S6b CCA callbacks, the code
assumed that a Diameter session always exists when processing a CCA
message and enforced this invariant with:
ogs_assert(new == 0);
However, if a malicious or misbehaving Diameter peer sends a
Credit-Control-Answer containing an unknown or mismatched Session-Id,
fd_msg_sess_get() returns new=1, indicating that the session does not
exist locally. The assertion then triggers ogs_abort(), terminating
the entire SMF process.
This allows a single malformed CCA message to cause a denial-of-service
by crashing the SMF and dropping all active UE sessions.
Replace the assertion with a runtime check. If the session does not
exist (new != 0), the message is logged and discarded via the existing
cleanup path instead of aborting the process.
Affected callbacks:
- smf_gx_cca_cb()
- smf_gy_cca_cb()
- smf_s6b_aaa_cb()
- smf_s6b_sta_cb()
This ensures that unexpected or malicious Diameter answers do not
terminate the SMF process and are handled gracefully.
Issues: #4343
When a UE sends TAU Request with active_flag=1 and a Bearer Context
Status that mismatches MME state, the BCS cleanup deletes all sessions
but the stored procedure remains InitialContextSetup. Building an
Initial Context Setup Request with zero E-RABs returns NULL, hitting
ogs_assert and killing the process — disconnecting all eNBs.
Guard in mme_send_tau_accept_and_check_release(): if no sessions remain
after BCS cleanup, downgrade to DownlinkNASTransport so TAU Accept is
delivered without requiring bearers.
ogs_pco_parse() previously relied on ogs_assert() to verify the bounds
of Protocol/Container fields while parsing PCO/EPCO data. If the outer
PCO/EPCO length was inconsistent with the internal container encoding
(e.g., truncated Container-ID, Container-Length, or container data),
the assert would trigger and terminate the process.
Because PCO/EPCO is derived from UE-supplied NAS messages (e.g.,
PDU Session Establishment Request), a malformed EPCO IE could trigger
a remote SMF crash, resulting in a denial-of-service condition.
This patch replaces the assert-based bounds checks with explicit
runtime validation and returns an error when malformed or truncated
PCO/EPCO is detected. The SMF can then reject the request cleanly
instead of aborting.
Checks added:
- Validate minimum PCO/EPCO length before accessing header fields
- Verify Container-ID bounds
- Verify Container-Length bounds
- Verify container payload length
- Detect container count overflow beyond
OGS_MAX_NUM_OF_PROTOCOL_OR_CONTAINER_ID
With these changes, malformed EPCO inputs are safely rejected and the
SMF remains operational.
Issues: #4341
The MME terminated with abort() when processing IDR or ULA messages
containing a malformed Served-Party-IP-Address (AVP 848) or
MIP-Home-Agent-Address (AVP 334).
In mme_s6a_subscription_data_from_avp(), the return value of
fd_msg_avp_value_interpret() was checked using ogs_assert(ret == 0).
However, this function may legitimately return an error if the Address
AVP contains an invalid encoding (e.g., invalid address family or
length mismatch). Since freeDiameter treats Address AVPs as raw
OctetString during decoding, malformed values can reach this code path.
As a result, receiving such an AVP caused ogs_assert() → ogs_abort() →
abort(), terminating the entire MME process.
Fix this by replacing the assertion with proper error handling.
If fd_msg_avp_value_interpret() fails, the malformed AVP is ignored
with a warning log and processing continues.
This prevents a malformed or malicious Diameter message from crashing
the MME while preserving normal operation for valid data.
Issues: #4334
Clear presence-driven fields before processing conditional IEs to prevent
stale state when find_or_add() returns an already-existing entry.
FAR: reset dst_if_type_presence and outer_header_creation_len
URR: reset all measurement/threshold/quota fields
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
When a PFCP control plane sends a Session Modification Request with
Create FAR, Create QER, or Create URR IEs for IDs that were not
previously created during PDR processing, the UPF rejects them with
"Cannot find [FAR|QER|URR]-ID[N] in PDR" errors.
This is because ogs_pfcp_handle_create_far/qer/urr() use
ogs_pfcp_[far|qer|urr]_find() which only looks up existing entries,
while ogs_pfcp_handle_create_pdr() correctly uses
ogs_pfcp_pdr_find_or_add() which creates new entries if needed.
In practice, some PFCP control planes (e.g., vendor-specific PGW-C
implementations) send Create URR/QER/FAR in Session Modification
without a corresponding Create PDR that would have pre-created these
entries. The resulting PFCP error responses cascade into GTP-U Error
Indications, causing bearer teardowns and IMS PDN disconnections.
This patch:
- Changes Create FAR/QER/URR handlers to use find_or_add, matching
the existing Create PDR behavior
- Makes Remove PDR/FAR/QER/URR handlers idempotent: removing a
non-existent entry now returns success with a warning instead of
failing with an error, since the desired state (entry removed) is
already achieved
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Some UEs and fuzzing inputs may send a Registration Request with
registration_type.value set to 0. According to TS 24.501 Table 9.11.3.7.1,
unused registration-type encodings shall be interpreted by the network
as "initial registration". Without normalization, the invalid value may
propagate into subsequent logic and lead to unexpected behavior during
UE context transfer handling.
This patch normalizes registration_type.value == 0 to
OGS_NAS_5GS_REGISTRATION_TYPE_INITIAL early in
gmm_handle_registration_request() so that later procedures operate on
a valid registration type.
Additionally, improve robustness in
gmm_registration_request_from_old_amf() by ignoring placeholder
5G-GUTIs where AMF-ID and M-TMSI are zero. Some devices (and fuzzing
tools) send such values even though they do not represent a valid
previous AMF context. Treating them as actionable may incorrectly
trigger N14 UE Context Transfer attempts.
With this change, placeholder GUTIs are treated as non-actionable and
the AMF falls back to normal registration / identity procedures.
Issues: #4321
Previously, the MME aborted when receiving a Cancel-Location-Request
(CLR) with an unsupported Cancellation-Type. The default case logged
a fatal message and called ogs_assert_if_reached(), which terminated
the process.
However, Cancellation-Type values such as UPDATE_PROCEDURE_IWF (3)
and INITIAL_ATTACH_PROCEDURE (4) are defined in 3GPP TS 29.272 but are
not implemented in Open5GS. Since this field originates from external
Diameter input, the MME must not crash when encountering unsupported
values.
Replace ogs_fatal() and ogs_assert_if_reached() with ogs_error() so the
MME logs the issue and continues running instead of aborting.
This prevents a potential denial-of-service condition where a malformed
or unexpected CLR message could terminate the MME.
Issues: #4309
The AMF could abort when processing malformed or oversized multipart
SBI requests due to an assertion triggered in the multipart parser
callback.
When the parser encountered an overflow condition while assembling
multipart part data, `on_part_data()` executed `ogs_assert_if_reached()`,
causing the AMF process to terminate. This allowed malformed HTTP/2
multipart requests to trigger a denial-of-service condition.
This patch replaces the assertion-based failure with graceful error
handling:
- Introduce `multipart_part_data_t` and explicit parser state tracking.
- Add `parse_error` flag to propagate parsing failures.
- Validate the result of `multipart_parser_execute()`.
- Reject malformed multipart payloads instead of aborting.
- Replace fatal assertions with error handling and proper cleanup.
- Add centralized cleanup via `multipart_parser_data_free()`.
As a result, malformed or oversized multipart bodies are now rejected
with an error, while the AMF process remains operational.
Issues: #4290
Two issues (#4277, #4278) reported crashes caused by malformed or
unexpected inputs.
In the TLV parser, several ogs_assert() checks could be triggered by
malformed TLV blocks, resulting in process termination. These checks
are replaced with proper error handling: the parser now logs the error,
limits hexdump size, frees allocated TLVs, and returns NULL instead of
aborting.
In the SMF S5-C Create Session Request handler, additional validation
is introduced for Bearer Context handling. The implementation now
rejects requests containing multiple Bearer Contexts, missing mandatory
fields (EBI or Bearer QoS), duplicate EBI values, or invalid TEID/IP
information. Several ogs_assert() calls that could be triggered by
malformed messages are also replaced with explicit error handling.
These changes prevent crashes caused by malformed TLV blocks or
unexpected Bearer Context structures and ensure the SMF rejects such
requests gracefully.
Issues: #4277, #4278
Several users reported intermittent AMF crashes when SM Context Update
procedures overlap with NG context release or a new Registration
procedure. In these situations the RAN-UE associated with a session may
change before the asynchronous SBI response arrives.
Typical trigger scenarios include:
* UEContextReleaseRequest followed by a new Registration Request
* PDU Session Update overlapping with UE deactivation or handover
* Registration Request arriving while a previous Service Request is
still being processed
In these cases the AMF may send an Update SM Context request to the SMF
while the NG context is being released or replaced. When the asynchronous
SBI response arrives later, the AMF uses the session's current ran_ue
pointer. However, that pointer may already have been switched to a new
RAN-UE or cleared due to the release procedure.
As a result, the AMF may reference the wrong RAN-UE context or an
inconsistent state, eventually triggering an assertion such as:
amf_nsmf_pdusession_handle_update_sm_context:
Assertion `ran_ue->deactivation.group' failed
The root cause is that SBI client transactions do not preserve the
RAN-UE association at the time the request was sent. Because SBI
operations are asynchronous, the session context may change before the
response is processed.
This patch introduces a generic mechanism to attach user-defined context
to an SBI transaction:
- Add `user_data` and `user_data_free` to `ogs_sbi_xact_t`
- Allow NF-specific code to store per-transaction context
- Ensure the memory is released automatically when the transaction
is removed
The AMF now stores a snapshot of the RAN-UE ID in the SBI transaction
when sending an Update SM Context request. When the SBI response is
processed, the AMF retrieves the RAN-UE using this snapshot instead of
the session's current ran_ue pointer. This guarantees that the response
is associated with the correct RAN context even if the session state has
changed in the meantime.
This approach avoids race conditions between asynchronous SBI responses
and NG context lifecycle events, preventing the AMF from accessing an
incorrect or partially released RAN-UE context.
Reported-by:
multiple users on v2.7.6 environments
Issues: #4174, #4274
Replace assertion-based checks on network-derived values with
validation and proper GTP error handling.
- Handle ogs_gtp1_gsn_addr_to_ip() and ogs_gtp1_eua_to_ip() failures
without aborting SMF
- Fix incorrect log message for End User Address failure
- Handle PFCP outer_header_creation failure gracefully instead of assert
Prevents SMF crash triggered by malformed Gn CreatePDPContextRequest.
Issues: #4285
Replace fatal asserts in mme_s11_handle_create_session_response() with
validation and a unified failure path.
- Reject malformed/invalid IEs (Cause, TEID, PAA, AMBR, Bearer QoS)
instead of aborting the MME process
- Fix Bearer QoS length handling: treat mismatch as invalid IE and fail
gracefully
- Consolidate error handling via mme_s11_create_session_fail() and goto fail
This prevents remote crashes triggered by malformed GTPv2-C
CreateSessionResponse messages on S11.
Issues: #4284
The MME trusted the PDN Address Allocation (PAA) IE length from
CreateSessionResponse (S11) without proper bounds validation.
An attacker-controlled or malicious SGW could forge an oversized
PAA IE length (e.g., 200 bytes), causing the MME to copy the
payload into sess->paa using the attacker-supplied length.
This leads to memory corruption and a SIGSEGV crash (remote DoS).
This patch adds explicit length validation for the PAA IE:
- Rejects PAA lengths smaller than OGS_PAA_IPV4_LEN
- Rejects PAA lengths larger than OGS_PAA_IPV4V6_LEN
- Sets cause to OGS_GTP2_CAUSE_INVALID_LENGTH on malformed IE
As a result, malformed or oversized PAA IEs are safely rejected,
and the MME no longer crashes.
Issues: #4283
Replace ogs_assert() checks in ogs_gtp2_parse_tft() with explicit
runtime length validation to prevent process abort on malformed
TFT/TAD IEs.
Previously, insufficient length checks could trigger assertion
failures when parsing crafted BearerResourceCommand messages with
invalid packet filter content lengths. This allowed a malformed
TFT/TAD IE to cause a crash (SIGABRT) in SMF.
This patch:
- Adds explicit boundary checks before every field access
- Validates that content.length does not exceed remaining IE length
- Protects component array bounds during parsing
- Logs errors and returns current parsed size instead of aborting
The function now gracefully rejects malformed input without
terminating the process, preventing potential denial-of-service
conditions on S5-C interface.
No functional change for valid messages.
Issues: #4281
Replace strtoll() with strtoull() in ogs_uint64_from_string() and
remove fatal abort on conversion errors to prevent remote crash via
malformed SupportedFeatures/requester-features values.
The previous implementation could trigger OGS_LOG_FATAL and
ogs_assert_if_reached() when strtoll() detected ERANGE, allowing a
malicious or buggy peer to cause a denial-of-service by sending an
overly large hexadecimal value.
Changes:
- Use strtoull() for proper unsigned parsing.
- Add strict endptr validation (no digits, trailing garbage).
- Handle ERANGE and invalid inputs gracefully without abort().
- Normalize errno handling: success paths set errno=0.
- In ogs_sbi_parse_request(), reject invalid requester-features
(EINVAL/ERANGE) and return OGS_ERROR instead of proceeding.
Empty string is treated as valid (0), consistent with 3GPP
SupportedFeatures pattern ('^[A-Fa-f0-9]*$').
This ensures malformed requester-features values no longer crash
NRF and are properly rejected during SBI request parsing.
Issues: #4263
Validate the PDN Address Allocation (PAA) IE length in
sgwc_s5c_handle_create_session_response() before copying it
into sess->paa.
Previously, the code directly performed:
memcpy(&sess->paa, rsp->pdn_address_allocation.data,
rsp->pdn_address_allocation.len);
without validating the IE length. A malicious or malformed
CreateSessionResponse (S5-C) from a PGW with an oversized
PAA IE length could trigger a buffer overflow and crash
SGW-C (remote DoS).
This patch adds explicit length validation and rejects
responses with invalid PAA IE length, returning
OGS_GTP2_CAUSE_INVALID_LENGTH instead of proceeding.
Issue originally reported in #4282.
An initial fix was submitted in PR #4330 but was reverted
in #4331 due to issues. This commit provides a corrected
and validated implementation.
Fixes: #4282
When traffic from UE is destined to an other UE on the same UPF, the packet shouldn't be sent to the TUN interface, but should be re-encapsulated and forwarded via the destination UE's GTP-U tunnel.
Before, in the gtp-path.c, there was a TODO placeholder for this. Logic:
- Look up the destination UE session by inner packet dest IP
- Find a matching downlink PDR with FAR
- Fall back to lowest precedence PDR
- URR accounting
- Buffering and dowlink data reporting
Additionally, the multi-ue-test was extended with each UE pinging the next UE.
Signed-off-by: akos011221 <orbanakos2001@gmail.com>
open5gs doesn't support the "SMS in MME" (3GPP TS 23.272 Annex C) yet,
so better announce that we support SGs interface than giving no
information the the HSS.
Add validation for PDU Session Identity (PSI) when handling
SMF Registration resource requests in UDM.
Previously, the PSI value extracted from the SBI resource
path was used directly to locate the session context.
If the value corresponded to
OGS_NAS_PDU_SESSION_IDENTITY_UNASSIGNED (0), the lookup
would proceed with an invalid identifier.
This could lead to inconsistent session handling and
unexpected error paths.
This patch introduces an explicit validation step:
- Detect PSI == OGS_NAS_PDU_SESSION_IDENTITY_UNASSIGNED
- Log an error with the received PSI value
- Return HTTP 400 Bad Request via SBI error response
- Abort further processing of the request
This ensures that only valid, assigned PSI values are
processed and improves protocol compliance and robustness
against malformed SBI requests.
Issues: #4255
Replace hard assertions with boundary checks when parsing
SMF and AMF information from NRF NFProfile.
Previously, multiple ogs_assert() conditions assumed that
slice, TAI, TAI range, and GUAMI counts would always remain
within static limits (e.g., OGS_MAX_NUM_OF_SLICE,
OGS_MAX_NUM_OF_TAI, OGS_MAX_NUM_OF_SERVED_GUAMI).
If NRF provided NFProfile data exceeding these limits,
the process could terminate due to assertion failure,
resulting in service instability.
This patch introduces explicit overflow validation:
- SMF
- Slice list overflow protection
- NR TAI list overflow protection
- NR TAI range TAC index overflow protection
- AMF
- Served GUAMI overflow protection
- NR TAI range overflow protection
When limits are exceeded, an error log is generated and
parsing of the affected list is stopped gracefully,
preventing crash while preserving existing data.
This improves robustness against malformed or excessive
NFProfile inputs from NRF or peer NFs.
Issues: #4249, #4250, #4252
Fix a crash triggered by SCP NFProfile registrations that do not
provide any usable endpoint information.
Previously, ogs_sbi_client_associate() asserted that a client must
exist after association. However, malformed or incomplete NFProfiles
(e.g., scpInfo containing only scpDomainInfoList without scpPorts or
instance/service endpoints) could bypass endpoint validation and
result in no client being created.
This led to an assertion failure in:
ogs_sbi_client_associate()
-> ogs_assert(client)
Root causes addressed:
1. Association safety
- Remove hard assertion on missing instance-level client.
- Perform association only when a client exists.
- Improve logging for missing instance/service endpoints.
2. Endpoint validation refactor
- Move endpoint validation after client association.
- Introduce nf_instance_has_usable_client() helper to verify:
* Instance-level client, or
* Any service-level client.
3. Registration rejection
- Reject NFProfile registrations that lack usable endpoints
with HTTP 400 instead of allowing inconsistent state.
4. SCP info handling
- Treat domain-only SCP registrations as valid nf_info inputs
when num_of_domain is present.
Impact:
- Prevents assertion crashes in NRF triggered by malformed SCP
registrations.
- Ensures NF instances are accepted only when at least one usable
endpoint is available.
- Improves diagnostic logging for operator troubleshooting.
Tested with:
- SCP registration containing only scpDomainInfoList
- Registrations with instance-level endpoints
- Registrations with service-level endpoints
Issues: #4243, #4248
Enforce a 256MB maximum payload size in
on_data_chunk_recv() to prevent excessive memory allocation
from large HTTP/2 DATA frames.
Requests exceeding the limit are rejected with HTTP 413,
and allocation failures return HTTP 503.
This mitigates large payload DoS conditions.
Issues: #4244, #4247
When an NF loses heartbeat and enters re-registration, existing
NRF subscription states tied to the previous NF instance remain
both remotely (NRF) and locally (subscription_data pool).
In environments with repeated heartbeat loss or timing races
(e.g., docker-compose deployments), this leads to continuous
re-subscription loops and unbounded growth of
subscription_data entries, eventually exhausting the pool and
triggering assertion failures in ogs_sbi_subscription_data_add().
This patch introduces a pre-registration cleanup mechanism:
- Send DELETE requests for all subscriptions associated with
the NF instance before re-registration.
- Perform asynchronous local cleanup in the unsubscribe
response handler (avoiding use-after-free and double free).
- Add duplicate DELETE guard using subscription flags.
- Improve logging visibility for subscription cleanup flow.
This ensures that stale NRF subscription states are removed
and prevents subscription_data pool exhaustion during
re-registration loops.
Issues: #4207
Problem
When the implicit detach timer expires, the MME may initiate local
UE context removal if no S1 context exists.
In the previous implementation, mme_ue_remove() could be triggered
directly from mme_send_delete_session_or_detach() in this path.
This leads to a structural issue:
- The UE context may be freed while the EMM FSM is still processing
the implicit detach timer event.
- Subsequent FSM operations (state transition, ENTRY/EXIT signals)
may access the freed mme_ue.
- This results in assertion failures or crashes such as:
emm_state_registered: Assertion `mme_ue' failed
Analysis
Implicit detach handling executes within the EMM FSM context.
Immediate UE context removal from this path violates the FSM
lifecycle assumption that the context remains valid until the
event handling and state transition complete.
This creates a use-after-free risk and can also cause double-free
depending on concurrent removal paths.
Solution
Introduce deferred UE context removal via FSM:
1. Add a new flag:
mme_ue->ue_context_will_remove
2. Modify mme_send_delete_session_or_detach():
- If no S1 context exists, do not remove immediately.
- Set ue_context_will_remove = true instead.
3. In implicit detach timer handling:
- Check the flag and select the next state accordingly.
4. Introduce a new FSM state:
emm_state_ue_context_will_remove
- UE context removal is performed safely on ENTRY_SIG.
This ensures:
- UE context is not freed inside the original EMM handler.
- FSM lifecycle is preserved.
- Removal happens after state transition.
Impact
- Prevents crashes caused by use-after-free during implicit detach.
- Avoids double-free scenarios.
- Aligns UE context lifecycle with FSM design.
This change only affects implicit detach paths where S1 context
does not exist and does not alter normal detach procedures.
Fixes: #4298
NFProfile plmn_list returned from NRF overwrites the local serving
PLMN configuration. Reset num_of_serving_plmn_id instead of the
unused nf_instance->num_of_plmn_id to avoid stale accumulation.
Issues: #4207