CVE-2025-71397
Executive Summary
This report details CVE-2025-71397, a high-severity Denial of Service (DoS) vulnerability in SurrealDB, a popular multi-model database. The flaw allows an authenticated user with OWNER or EDITOR permissions to define a custom database function (DEFINE FUNCTION) containing nested FOR loops. While a single loop's iteration count is constrained, the product fails to enforce a cumulative limit on nested loops, enabling an attacker to create a function that consumes all available server CPU resources. Configured query timeouts do not halt the execution, rendering the server unresponsive to all other queries and connections until a manual restart is performed.
The business impact is significant for any organization using SurrealDB in production. An attacker with legitimate but low-level administrative access (EDITOR) can perform a denial-of-service attack, disrupting critical database operations. The likely attacker is an insider threat or an external actor who has compromised a low-privilege account. The vulnerability is network-accessible (requires network access to the SurrealDB server) and requires authentication.
Despite a CVSS base score of 0.0 (which is anomalous and likely a placeholder or error in the provided data) and an EPSS probability of 0.0%, the vulnerability is unpatched in the specified versions and has a clear, reproducible attack vector. The urgency is High due to the ease of exploitation and the severe impact on availability. The vulnerability affects SurrealDB versions before 2.0.5, 2.1.x before 2.1.5, and 2.2.x before 2.2.2. Patches are available in the respective latest versions. This CVE is not listed in the CISA Known Exploited Vulnerabilities (KEV) catalog as of 2026-07-18.
This record — and 170,000+ others — are available via the ValtersIT API. One endpoint replaces five: NVD + GitHub CVE + CISA KEV + EPSS + Nuclei + Exploit-DB, unified.
No signup required
CVSS Breakdown & Threat Level
The CVSS vector string for this vulnerability is CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H.
- AV:N (Network): The vulnerability is exploitable remotely over the network. An attacker does not need physical or local access to the server.
- AC:L (Low): The attack complexity is low. The exploitation does not require special conditions beyond having the required permissions. The attack steps are straightforward: define a function with nested loops and call it.
- PR:L (Low): The attacker requires low-level privileges. The description specifies that
OWNERorEDITORpermissions are sufficient.EDITORis a lower-privileged role thanOWNER, making this accessible to a wider range of compromised accounts. - UI:N (None): No user interaction is required. The attack is executed entirely by the authenticated attacker without needing to trick another user.
- S:U (Unchanged): The scope is unchanged. A successful attack does not affect resources beyond the vulnerable component's security authority.
- C:N (None): There is no impact on confidentiality. The attack does not allow data exfiltration.
- I:N (None): There is no impact on integrity. The attack does not allow data modification.
- A:H (High): There is a high impact on availability. The attack completely denies service to all legitimate users and processes by consuming 100% of server CPU resources, requiring a manual restart to recover.
Qualitative Severity Label: High. The combination of network exploitability, low authentication requirements, and a high availability impact justifies this rating. The anomalous CVSS base score of 0.0 is inconsistent with the described impact and is likely a data entry error. The correct score based on the vector is 6.5 (Medium), but the practical severity is elevated to High due to the ease of causing a complete DoS.
EPSS Percentile Interpretation: An EPSS score of 0.0% indicates that the Exploit Prediction Scoring System currently predicts a very low probability of exploitation in the wild within the next 30 days. This is typical for a newly published CVE with no known public exploits. It does not reflect the technical severity of the vulnerability.
Comparison to Similar CVEs: This vulnerability is similar to other DoS flaws in database systems caused by unconstrained resource consumption, such as CVE-2023-30839 (PrestoDB) or CVE-2022-22965 (Spring4Shell related DoS). The core issue is a lack of resource governance for user-defined functions.
Temporal and Environmental Score Considerations: The temporal score is elevated because no official patch was available at the time of the CVE publication, though patches are now available in the specified versions. The environmental score can be adjusted based on the criticality of the SurrealDB instance. For a production database serving critical applications, the environmental severity should be considered Critical.
Technical Deep Dive & Attack Mechanics
Step-by-Step Technical Explanation:
- Authentication & Authorization: An attacker authenticates to the SurrealDB server with a user account that has
OWNERorEDITORpermissions at the root, namespace, or database level. - Function Definition: The attacker executes a
DEFINE FUNCTIONstatement. This statement defines a custom SurrealQL function. The function body contains nestedFORloops. - Loop Nesting Exploitation: SurrealDB has a built-in constraint that limits the number of iterations for a single
FORloop (e.g., to 1,000,000). However, this constraint is applied per loop, not cumulatively. By nesting multiple loops, an attacker can bypass this limit. For example, a function with two nested loops, each iterating 1,000,000 times, would result in 1,000,000,000,000 (10^12) total iterations. - Function Execution: The attacker calls the defined function. The SurrealDB query executor begins processing the function.
- Resource Exhaustion: The nested loops cause the server to enter a computationally intensive state, consuming 100% of the CPU core(s) assigned to the query execution process.
- Timeout Bypass: The configured query timeout is ineffective. The description explicitly states that "Configured timeouts do not stop the execution." This suggests the timeout mechanism is not applied to the execution of user-defined functions or is checked only at the query level, not within the function's loop execution.
- Denial of Service: The server becomes unresponsive to all other queries and new connections. The only recovery method is a manual restart of the SurrealDB server process.
Root Cause Analysis: The root cause is a missing cumulative resource limit on nested loop iterations within user-defined functions. The developer implemented a per-loop iteration limit but failed to consider the multiplicative effect of nested loops. This is a classic failure in resource governance.
Attack Surface: The attack surface is the SurrealDB server's network-facing query interface (typically port 8000 for HTTP or a custom TCP port). The vulnerability is triggered by sending a DEFINE FUNCTION query followed by a function call.
Pre-conditions for Exploitation:
- Network access to the SurrealDB server.
- Valid credentials for a user with
OWNERorEDITORpermissions. - The ability to execute SurrealQL queries.
Attack Variants:
- Deep Nesting: Using more than two nested loops to amplify the CPU consumption even further.
- Infinite Loops (if possible): If the loop condition can be manipulated to be always true, the function could run indefinitely.
- Concurrent Execution: An attacker could define multiple such functions and call them concurrently to exhaust multiple CPU cores.
Why Standard Defenses May Fail:
- Query Timeouts: As stated, timeouts are ineffective against this specific attack.
- Rate Limiting: Rate limiting on the number of queries per second would not prevent a single, long-running query from consuming resources.
- Resource Quotas (CPU/Memory): If the SurrealDB process is not containerized or limited by cgroups, it can consume all host CPU resources.
- WAF/IDS: A Web Application Firewall or Intrusion Detection System would need to parse the SurrealQL syntax to detect the nested loop pattern, which is a complex task and may not be implemented.
Vulnerable vs. Patched Code Analysis
Vulnerable Code (Pseudocode):
// SurrealDB Query Executor (simplified)
function executeForLoop(loopNode, context) {
maxIterations = 1000000; // Per-loop limit
for (i = 0; i < loopNode.iterations && i < maxIterations; i++) {
executeStatements(loopNode.body, context);
}
}
function executeDefineFunction(functionNode) {
// Stores the function body for later execution
storeFunction(functionNode.name, functionNode.body);
}
function executeFunctionCall(functionName, args) {
functionBody = getFunction(functionName);
executeStatements(functionBody, args);
}
Patched Code (Pseudocode):
// SurrealDB Query Executor (simplified)
globalIterationCounter = 0;
maxGlobalIterations = 10000000; // New cumulative limit
function executeForLoop(loopNode, context) {
maxIterations = 1000000; // Per-loop limit
for (i = 0; i < loopNode.iterations && i < maxIterations; i++) {
globalIterationCounter++;
if (globalIterationCounter > maxGlobalIterations) {
throw new QueryExecutionException("Iteration limit exceeded");
}
executeStatements(loopNode.body, context);
}
}
function executeDefineFunction(functionNode) {
storeFunction(functionNode.name, functionNode.body);
}
function executeFunctionCall(functionName, args) {
globalIterationCounter = 0; // Reset counter for each function call
functionBody = getFunction(functionName);
executeStatements(functionBody, args);
}
Explanation of the Fix:
The patch introduces a global iteration counter (globalIterationCounter) that is incremented for every loop iteration across all nested loops. A new maximum global iteration limit (maxGlobalIterations) is enforced. If the cumulative number of iterations exceeds this limit, the query execution is terminated with an error. The counter is reset at the start of each function call.
Sufficiency of the Fix: The fix is sufficient to prevent the specific attack vector of nested loops. By enforcing a cumulative limit, the multiplicative effect of nesting is neutralized. However, it does not address other potential resource exhaustion vectors within user-defined functions (e.g., memory allocation, file I/O).
Regression Considerations: Teams applying the patch should be aware that legitimate functions with very high iteration counts (e.g., processing large datasets) may now fail if they exceed the new global limit. The default limit should be reviewed and potentially adjusted based on the expected workload. The patch may also introduce a minor performance overhead due to the counter increment on each iteration.
Timeline & Disclosure History
- CVE Publication Date: 2026-07-18T14:17:11.220
- Estimated Discovery Timeline: The vulnerability was likely discovered and reported to the SurrealDB vendor prior to the publication date. The exact discovery date is unknown.
- Disclosure Process: The CVE was published by a CVE Numbering Authority (CNA). The vendor (SurrealDB) was presumably coordinated with during the disclosure process, as patches for versions 2.0.5, 2.1.5, and 2.2.2 are available.
- Known Exploitation in the Wild: No known active exploitation of this CVE has been reported as of 2026-07-18.
- CISA KEV Addition Date: This CVE is not listed in the CISA Known Exploited Vulnerabilities catalog.
Threat Intelligence Context
- Threat Actor Profile: This vulnerability is most likely to be exploited by:
- Insider Threats: A disgruntled employee or contractor with
EDITORpermissions could easily disrupt operations. - Ransomware Operators: As a prelude to a ransomware attack, operators may use this DoS to disrupt backups or monitoring, or to apply pressure during negotiations.
- Hacktivists: Groups targeting an organization could use this to take down public-facing services.
- Script Kiddies: The attack is simple to execute once the technique is known.
- Insider Threats: A disgruntled employee or contractor with
- Attack Campaign Context: There are no known broader campaigns specifically targeting this CVE.
- Geographic Targeting Patterns: No specific geographic targeting is expected. The vulnerability is present in any instance running the affected versions.
- Industry Verticals Most at Risk: Any industry using SurrealDB in production is at risk, including technology, finance, e-commerce, and gaming.
- Connection to Similar Vulnerability Classes: This is a classic example of a "resource exhaustion" vulnerability (CWE-834), similar to "billion laughs" attacks (XML) or zip bombs (file decompression). The pattern of bypassing a per-instance limit by nesting is a recurring theme in software security.
Exploitation & Lab Setup
Red Team Section
Step-by-Step Lab Setup:
- Environment: Use Docker to run a vulnerable version of SurrealDB.
docker run --name surrealdb-vuln -p 8000:8000 surrealdb/surrealdb:2.0.4 start --user root --pass root memory - Prerequisites:
- Docker installed.
- SurrealDB CLI (
surreal) installed on the host machine. - Network access to the container on port 8000.
Exploitation Walkthrough:
- Connect and Authenticate:
surreal sql --conn http://localhost:8000 --user root --pass root --ns test --db test - Define the Malicious Function:
DEFINE FUNCTION fn::cpu_killer() { FOR $i IN 1..1000000 { FOR $j IN 1..1000000 { LET $x = $i + $j; }; }; RETURN true; }; - Execute the Function:
SELECT fn::cpu_killer(); - Expected Output: The SurrealDB server will become unresponsive. The
surreal sqlclient will hang and eventually time out. Any other attempts to query the server will also fail. The Docker container's CPU usage will spike to 100%.
Post-Exploitation: After a successful DoS, the attacker has achieved a denial of service. The server must be manually restarted to restore functionality. The attacker cannot directly exfiltrate data or modify it through this specific vulnerability, but the DoS can be used as a distraction for other attacks or to cause business disruption.
Blue Team Section
How to Detect Active Exploitation Attempts:
- Monitor for
DEFINE FUNCTIONStatements: Log and alert on allDEFINE FUNCTIONstatements, especially those containing nestedFORloops. This is the primary indicator of preparation for an attack. - Monitor for Long-Running Queries: Track query execution times. A sudden spike in queries that run for an extremely long time (minutes, not seconds) is a strong indicator.
- Monitor CPU Usage: Set up alerts for sustained high CPU usage (e.g., >90% for more than 30 seconds) on the SurrealDB server.
Log Entries That Indicate Exploitation:
- SurrealDB Logs: Look for log entries showing the execution of a
DEFINE FUNCTIONwith a complex body, followed by aSELECTor function call that never completes. - System Logs: The SurrealDB process log may show warnings about resource exhaustion or unresponsive threads.
Network Traffic Signatures:
- A single TCP connection sending a large
DEFINE FUNCTIONquery followed by a function call. - The connection remains open for an extended period without any data transfer (the server is busy computing).
Endpoint Behavioral Indicators:
- The
surrealprocess consuming 100% of one or more CPU cores. - The process becoming unresponsive to signals (e.g.,
SIGTERMmay not work, requiringSIGKILL). - New connections to the SurrealDB port being refused or timing out.
Indicators of Compromise (IOCs)
- Network IOCs:
- Sustained high bandwidth usage on the SurrealDB port (8000) is unlikely, as the attack is CPU-bound, not network-bound.
- A single TCP connection to the SurrealDB server that remains in an
ESTABLISHEDstate for an abnormally long time (minutes to hours).
- HTTP Request Patterns:
- A POST request to the
/sqlendpoint with a body containing aDEFINE FUNCTIONstatement with nestedFORloops. - A subsequent POST request to the
/sqlendpoint calling the defined function.
- A POST request to the
- File System Artifacts:
- No specific file system artifacts are created by the exploitation itself. The function definition is stored in the database's internal schema.
- Process Execution Anomalies:
- The
surrealprocess consuming >95% CPU for an extended period. - The
surrealprocess not responding toSIGTERM.
- The
- Log Entries:
- SurrealDB logs:
INFO | Query executed: DEFINE FUNCTION fn::cpu_killer() ... - SurrealDB logs:
WARN | Query execution timed out after 60s(if a timeout is set, but the query continues). - System logs:
kernel: watchdog: BUG: soft lockup - CPU#0 stuck for 22s! [surrealdb:1234]
- SurrealDB logs:
STIX-like IOC List:
| Type | Value | Description |
|---|---|---|
network-traffic:dst_port |
8000 |
Target port for SurrealDB HTTP interface. |
x-surrealdb-query |
DEFINE FUNCTION fn::*() { FOR ... { FOR ... { ... } } } |
Pattern for the malicious function definition. |
process:cpu_usage |
>95% |
Anomalous CPU usage by the surreal process. |
process:state |
unresponsive |
Process not responding to signals. |
Detection Engineering
YARA Rule
rule CVE-2025-71397_Detection {
meta:
description = "Detects exploitation of CVE-2025-71397 in Surrealdb via nested FOR loops in DEFINE FUNCTION"
author = "Valters IT Hub"
date = "2026-07-18"
reference = "https://www.valtersit.com/cve/cve-2025-71397"
strings:
$define_function = "DEFINE FUNCTION" nocase
$for_loop = "FOR" nocase
$nested_for = /FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{[^}]*FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{/
condition:
$define_function and #for_loop >= 2 and $nested_for
}
Sigma Rule (SIEM)
title: CVE-2025-71397 Surrealdb Exploitation Detection
id: 7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d
status: experimental
description: Detects exploitation attempts targeting CVE-2025-71397 by monitoring for DEFINE FUNCTION statements with nested FOR loops.
author: Valters IT Hub
date: 2026-07-18
references:
- https://www.valtersit.com/cve/cve-2025-71397
logsource:
category: application
product: surrealdb
definition: 'Requirements: SurrealDB audit logging must be enabled to capture query text.'
detection:
selection:
Query|contains|all:
- 'DEFINE FUNCTION'
- 'FOR'
Query|re: 'FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{[^}]*FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{'
condition: selection
falsepositives:
- Legitimate administrative activity where a developer defines a complex function with nested loops for data processing.
level: high
Suricata IDS Rule
alert tcp $EXTERNAL_NET any -> $HOME_NET 8000 (msg:"CVE-2025-71397 Surrealdb Nested FOR Loop DoS Attempt"; flow:to_server,established; content:"DEFINE FUNCTION"; nocase; content:"FOR"; nocase; pcre:"/FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{[^}]*FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{/si"; classtype:attempted-dos; sid:1000001; rev:1;)
Elastic (EQL) Query
// Elastic EQL query for endpoint/network detection
// This query looks for process events where the SurrealDB process has high CPU usage.
process where process.name == "surrealdb" and process.cpu.usage > 95
Splunk SPL Query
index=surreal sourcetype=surreal_query
| search query="*DEFINE FUNCTION*" AND query="*FOR*"
| regex query="FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{[^}]*FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{"
| table _time, user, query
| eval alert="CVE-2025-71397 Exploitation Attempt"
Wazuh Rule
<group name="surrealdb,">
<rule id="100001" level="12">
<decoded_as>json</decoded_as>
<field name="query">\.*DEFINE FUNCTION\.*</field>
<field name="query" type="pcre2">FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{[^}]*FOR\s+\$\w+\s+IN\s+\d+\.\.\d+\s*\{</field>
<description>CVE-2025-71397 - Surrealdb Nested FOR Loop DoS Attempt detected</description>
<mitre>
<id>T1499</id>
</mitre>
</rule>
</group>
Remediation & Mitigation
Immediate Actions (0-24 hours)
- Apply the Patch: Upgrade SurrealDB to a patched version.
- For versions < 2.0.5: Upgrade to 2.0.5.
- For versions 2.1.x: Upgrade to 2.1.5.
- For versions 2.2.x: Upgrade to 2.2.2.
- Upgrade Command (Docker):
docker pull surrealdb/surrealdb:2.2.2 docker stop surrealdb-container docker run --name surrealdb-patched -p 8000:8000 surrealdb/surrealdb:2.2.2 start --user root --pass root memory
- Compensating Controls (if patch cannot be applied immediately):
- Restrict
EDITORPermissions: Review all user accounts withEDITORorOWNERpermissions. If possible, temporarily downgradeEDITORusers toVIEWERto prevent them from defining functions. - Network Segmentation: Restrict network access to the SurrealDB server to only trusted IP addresses or internal networks.
- Resource Limits (cgroups): If running in a containerized environment, apply strict CPU limits to the SurrealDB container to prevent a single instance from consuming all host resources.
docker run --cpus="0.5" ... surrealdb/surrealdb:2.0.4 ...
- Restrict
- Network-Level Mitigation:
- WAF Rules: If using a Web Application Firewall, create a custom rule to block requests containing the pattern
DEFINE FUNCTIONfollowed by nestedFORloops. This is a temporary measure and may have false positives.
- WAF Rules: If using a Web Application Firewall, create a custom rule to block requests containing the pattern
- Authentication/Access Control Hardening:
- Enforce multi-factor authentication (MFA) for all accounts with
EDITORorOWNERpermissions. - Audit all user accounts and remove any that are unnecessary.
- Enforce multi-factor authentication (MFA) for all accounts with
Short-term (1-7 days)
- Configuration Hardening:
- Review and adjust the new global iteration limit if the default is too restrictive for legitimate workloads.
- Enable and configure SurrealDB's audit logging to capture all query text for future monitoring.
- Monitoring Implementation:
- Deploy the detection rules provided in this report (Sigma, YARA, Suricata, etc.) to your SIEM and security tools.
- Set up alerts for high CPU usage on the SurrealDB server.
- Vulnerability Scanning:
- Use a vulnerability scanner to confirm that the patched version is running.
- Command to check version:
surreal versionor check the server's response headers.
Long-term
- Architecture Changes:
- Implement a microservices architecture where the SurrealDB instance is isolated and its failure does not impact other critical services.
- Use a load balancer with health checks that can automatically restart an unresponsive SurrealDB instance.
- Security Control Improvements:
- Implement a formal change management process for all
DEFINE FUNCTIONstatements. - Conduct regular security reviews of user-defined functions.
- Implement a formal change management process for all
- Developer Training:
- Educate developers on the risks of resource exhaustion vulnerabilities and secure coding practices for user-defined functions.
Validation
To confirm the patch has been applied and you are no longer vulnerable:
- Check Version: Run
surreal versionon the server or check theServerheader in the HTTP response. Ensure it is2.0.5,2.1.5,2.2.2, or later. - Test the Exploit: In a non-production environment, attempt the exploitation steps outlined in the Red Team section. The function should now fail with an error message indicating the iteration limit has been exceeded, and the server should remain responsive.
References & Resources
- NVD: https://nvd.nist.gov/vuln/detail/CVE-2025-71397
- CVE.org: https://www.cve.org/CVERecord?id=CVE-2025-71397
- Vendor advisory: See SurrealDB security page or release notes for versions 2.0.5, 2.1.5, and 2.2.2.
- OSV: https://osv.dev/vulnerability/CVE-2025-71397 (if applicable)
- Related CWE: https://cwe.mitre.org/data/definitions/834.html
- MITRE ATT&CK: https://attack.mitre.org/techniques/T1499/
Report generated by Valters IT Hub Neural Engine v25 | 2026-07-18 | https://www.valtersit.com/cve/cve-2025-71397