CVE-2024-58359
Executive Summary
This report details CVE-2024-58359, a denial of service (DoS) vulnerability in SurrealDB versions prior to 2.1.0. The flaw resides in the database's sorting mechanism, which can be triggered by an authorized client executing a query with the ORDER BY rand() clause. Successful exploitation causes a panic in the sorting function, leading to an immediate crash of the database server.
Business Impact: Organizations using SurrealDB as a backend database for critical applications, including web services, APIs, and data analytics platforms, are at risk. An attacker with valid, low-privilege credentials can disrupt service availability, leading to application downtime, data inaccessibility, and potential business continuity failures. The likely attacker is an authenticated user or an attacker who has compromised low-level credentials, aiming to cause a targeted service outage.
Vulnerability Class & Attack Vector: This is a Denial of Service (DoS) vulnerability. The attack vector is network-accessible, requiring the attacker to send a crafted SQL query to the SurrealDB server. The attack requires authentication, but only at a low-privilege level (e.g., a standard user or editor role).
Urgency Assessment: The CVSS score of 6.5 (Medium) reflects the high availability impact but the requirement for authentication. The EPSS probability of 0.0% indicates that, as of the publication date, there is no evidence of active exploitation in the wild. However, the vulnerability is trivial to exploit once discovered, and the lack of a patch for older versions increases the risk for unpatched systems. The urgency is Medium, but should be escalated to High for any internet-facing SurrealDB instance accessible to untrusted users.
Key Facts:
- Vendor: SurrealDB
- Affected Versions: All versions before 2.1.0
- Patch Status: Unpatched for versions < 2.1.0. The fix is included in version 2.1.0.
- CISA KEV: Not listed.
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
CVSS Vector: CVSS:3.1/AV:N/AC:L/PR:H/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 does not require any special conditions beyond sending a valid, albeit malicious, query. No race condition or complex sequence of events is needed.
- PR:H (High): The attacker must be authenticated to the SurrealDB instance. While the privilege level is high in the CVSS context, in practice, this could be a low-privilege user account (e.g., a standard user with query permissions), not necessarily an administrator.
- UI:N (None): No user interaction is required. The attack is executed entirely by the authenticated client.
- S:U (Unchanged): A successful attack does not compromise other components of the system. The impact is confined to the SurrealDB server process.
- C:N (None): There is no impact to the confidentiality of data.
- I:N (None): There is no impact to the integrity of data.
- A:H (High): The vulnerability causes a complete loss of availability. The database server process crashes, making the service unavailable until it is manually restarted.
Qualitative Severity: Medium. The requirement for authentication significantly reduces the attack surface, but the total loss of availability makes this a serious concern for production environments.
EPSS Interpretation: The EPSS score of 0.0% means that, based on current threat intelligence, there is no observed exploitation activity. This is common for newly published CVEs. It does not mean the vulnerability is not dangerous; it simply indicates a lack of active weaponization in the wild at this time.
Comparison to Historical CVEs: This vulnerability is similar to other DoS flaws in database systems caused by resource exhaustion or unhandled exceptions during query processing. For example, CVE-2023-30839 in PrestaShop allowed a DoS via a crafted sort parameter. The key differentiator here is the specific trigger (ORDER BY rand()) and the resulting panic, which is a hard crash rather than a gradual resource leak.
Temporal & Environmental Scores:
- Temporal: The score remains at 6.5 as there is no official patch for versions < 2.1.0 and no confirmed exploit code. The availability of a proof-of-concept would raise the temporal score.
- Environmental: Organizations should adjust the score based on their environment. If the SurrealDB instance is isolated on a management network with strict access controls, the risk is lower. If it is exposed to the internet or a large number of authenticated users, the risk is higher.
Technical Deep Dive & Attack Mechanics
Step-by-Step Technical Explanation:
- Authentication: An attacker authenticates to the SurrealDB server using valid credentials (e.g., a standard user account).
- Query Submission: The attacker submits a SQL query containing the
ORDER BY rand()clause. A typical malicious query might look like:SELECT * FROM some_table ORDER BY rand(); - Query Parsing & Planning: The SurrealDB query parser identifies the
ORDER BYclause and therand()function. The query planner determines that sorting is required. - Sorting Execution: The database engine begins the sorting process. The
rand()function is expected to return a random floating-point number for each row, which is then used as the sort key. - Panic Trigger: The vulnerability lies in the sorting function's inability to handle the non-deterministic nature of the
rand()function within the sort operation. The sort algorithm likely expects a stable, comparable key for each row. Whenrand()is called multiple times during the sort (e.g., during comparisons), it returns different values, leading to an inconsistent state. This violates an internal invariant, causing the Rust-based code to panic. - Server Crash: The panic is unhandled, causing the SurrealDB server process to terminate immediately. All active connections are dropped, and the database becomes unavailable.
Root Cause Analysis: The developer mistake is an improper check for unusual or exceptional conditions (CWE-754). The sorting function was not designed to handle a volatile, non-deterministic expression like rand() as a sort key. The code assumes that the sort key for a given row is stable and comparable, which is a false assumption when using rand(). The lack of input validation or a safety check for this specific case leads to the panic.
Attack Surface:
- Interface: The SurrealDB SQL query interface (typically over WebSocket or HTTP on port 8000).
- Protocol: SurrealDB's custom protocol or SQL-over-HTTP.
- Pre-conditions:
- Network access to the SurrealDB server.
- Valid authentication credentials with permission to execute
SELECTqueries on any table. - The target table must have at least one row to trigger the sort.
Attack Variants:
- Resource Exhaustion: While the primary trigger is a panic, an attacker could also attempt to cause a prolonged DoS by repeatedly sending the malicious query, causing the server to crash and restart in a loop.
- Combined Attacks: An attacker could use this DoS to disable logging or monitoring systems before launching a more sophisticated attack.
Why Standard Defenses May Fail:
- WAF/IDS: A Web Application Firewall (WAF) or Intrusion Detection System (IDS) may not flag a query containing
ORDER BY rand()as malicious, as it is a valid SQL construct. Signature-based detection would require a specific rule for this CVE. - Rate Limiting: Rate limiting may slow down an attacker but will not prevent a single, well-crafted query from crashing the server.
- Input Sanitization: The query is syntactically valid SQL. Sanitization routines that check for malicious keywords would not block
rand().
Vulnerable vs. Patched Code Analysis
Vulnerable Code (Conceptual - Pre-2.1.0):
// Pseudocode for the sorting function
fn sort_rows(rows: Vec<Row>, order_by: Vec<SortExpression>) -> Vec<Row> {
rows.sort_by(|a, b| {
let key_a = evaluate_expression(&order_by[0], a); // Calls rand() here
let key_b = evaluate_expression(&order_by[0], b); // Calls rand() again, may return different value
key_a.cmp(&key_b) // Comparison may be inconsistent
});
// ... rest of function
}
The issue is that evaluate_expression is called multiple times for the same row during the sort, and for rand(), each call returns a different value. This violates the sorting contract, leading to a panic.
Patched Code (Conceptual - 2.1.0+):
// Pseudocode for the patched sorting function
fn sort_rows(rows: Vec<Row>, order_by: Vec<SortExpression>) -> Result<Vec<Row>, Error> {
// Check if any sort expression is non-deterministic
if is_nondeterministic(&order_by[0]) {
return Err(Error::new("Cannot sort by a non-deterministic expression"));
}
// Pre-compute sort keys for each row
let mut keyed_rows: Vec<(SortKey, Row)> = rows
.into_iter()
.map(|row| {
let key = evaluate_expression(&order_by[0], &row); // Called once per row
(key, row)
})
.collect();
keyed_rows.sort_by(|a, b| a.0.cmp(&b.0));
Ok(keyed_rows.into_iter().map(|(_, row)| row).collect())
}
The patch introduces a check (is_nondeterministic) to detect volatile functions like rand() in the ORDER BY clause. If detected, it returns an error instead of proceeding with the sort. Additionally, the sort keys are pre-computed once per row, ensuring stability even if the expression were to be evaluated.
Regression Considerations: The patch changes the behavior of the database. Queries that previously worked (and crashed the server) will now return an error. Applications that rely on ORDER BY rand() for random row selection will need to be updated to use alternative methods (e.g., SELECT * FROM table ORDER BY rand() LIMIT 1 might be replaced with a client-side random selection or a different SQL function).
Timeline & Disclosure History
- CVE Publication Date: 2026-07-18T14:17:08.780
- Estimated Discovery Timeline: The vulnerability was likely discovered and reported to SurrealDB prior to the release of version 2.1.0. The exact discovery date is unknown.
- Disclosure Process: The CVE was published by the CNA (likely SurrealDB or a third-party coordinator). The fix was included in version 2.1.0, which was released before the CVE publication.
- Known Exploitation in the Wild: No known active exploitation as of 2026-07-18.
- CISA KEV Addition Date: Not applicable.
Threat Intelligence Context
- Threat Actor Profile: This vulnerability is most likely to be exploited by:
- Script Kiddies / Hacktivists: The attack is simple to execute once the technique is known. It can be used to disrupt services for ideological reasons.
- Disgruntled Insiders: An authenticated user with low-level access could easily crash the database server, causing significant operational disruption.
- Ransomware Operators (Pre-Encryption): As part of a ransomware attack, operators may use this DoS to disable database services before deploying the ransomware payload, increasing the pressure on the victim.
- Attack Campaign Context: No specific campaigns are associated with this CVE at this time.
- Geographic Targeting Patterns: None identified.
- Industry Verticals Most at Risk: Any industry using SurrealDB, including technology, finance, e-commerce, and gaming.
- Connection to Similar Vulnerability Classes: This is a classic example of a DoS vulnerability caused by an unhandled exception in a core processing function. Similar flaws have been found in other database systems (e.g., MySQL, PostgreSQL) when handling specific SQL constructs.
Exploitation & Lab Setup
Red Team Section
Lab Setup:
- Environment: Docker is the easiest way to set up a vulnerable instance.
- Pull Vulnerable Image:
docker pull surrealdb/surrealdb:v1.5.0(or any version < 2.1.0). - Run Container:
docker run --name vulnerable-surrealdb -p 8000:8000 surrealdb/surrealdb:v1.5.0 start --user root --pass root - Install SurrealQL Client:
npm install -g surrealdb.jsor use the SurrealDB CLI. - Authenticate:
surreal sql --endpoint http://localhost:8000 --namespace test --database test --user root --pass root - Create a Table with Data:
CREATE user:1 SET name = 'Alice'; CREATE user:2 SET name = 'Bob'; CREATE user:3 SET name = 'Charlie';
Exploitation Walkthrough:
- Execute Malicious Query: From the authenticated SurrealQL client, run:
SELECT * FROM user ORDER BY rand(); - Expected Output: The client will likely receive a connection error or a timeout. The Docker container will exit or become unresponsive.
- Verification: Check the container status:
docker ps -a. The container should show an "Exited" status. - Post-Exploitation: The attacker has successfully caused a denial of service. The database is unavailable until an administrator restarts the container. The attacker can repeat this process to maintain the DoS.
Blue Team Section
Detection:
- Log Entries: SurrealDB logs may show a panic message before the crash. Look for entries containing "panic", "thread 'main' panicked at", or "sorting function" in the server logs.
- Network Traffic: A sudden spike in queries containing
ORDER BY rand()from a single authenticated user is a strong indicator. - Endpoint Behavioral Indicators: The SurrealDB process (
surreal) will terminate unexpectedly. Monitoring tools (e.g., systemd, Docker health checks) will report the service as down.
Indicators of Compromise (IOCs)
- Network IOCs:
- Repeated SQL queries containing the string
ORDER BY rand()from the same source IP or authenticated session.
- Repeated SQL queries containing the string
- HTTP Request Patterns:
- POST requests to the SurrealDB endpoint (e.g.,
/sql) with a body containingORDER BY rand().
- POST requests to the SurrealDB endpoint (e.g.,
- File System Artifacts:
- Core dump files (if enabled) generated by the crashing
surrealprocess.
- Core dump files (if enabled) generated by the crashing
- Process Execution Anomalies:
- The
surrealprocess exiting unexpectedly with a non-zero exit code.
- The
- Log Entries:
- Server logs containing a Rust panic message, e.g.,
thread 'main' panicked at 'calledResult::unwrap()on anErrvalue: ...'.
- Server logs containing a Rust panic message, e.g.,
STIX-like IOC List:
| Type | Value | Description |
|---|---|---|
autonomous-system |
(N/A) | No specific ASN identified. |
ipv4-addr |
(N/A) | No specific IP addresses identified. |
url |
(N/A) | No specific URLs identified. |
file |
(N/A) | No specific file hashes identified. |
mutex |
(N/A) | No mutexes identified. |
pattern |
sql_query CONTAINS ORDER BY rand() |
SQL query pattern indicating exploitation attempt. |
log |
panic OR thread 'main' panicked |
Log entry pattern indicating successful crash. |
Detection Engineering
YARA Rule
rule CVE-2024-58359_Detection {
meta:
description = "Detects exploitation of CVE-2024-58359 in Surrealdb via log analysis"
author = "Valters IT Hub"
date = "2026-07-18"
reference = "https://www.valtersit.com/cve/cve-2024-58359"
strings:
$panic_msg = "panicked at"
$sort_func = "sorting"
$rand_func = "rand()"
condition:
all of them
}
Sigma Rule (SIEM)
title: CVE-2024-58359 Surrealdb Exploitation Detection
id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
status: experimental
description: Detects exploitation attempts targeting CVE-2024-58359 via server panic logs
author: Valters IT Hub
date: 2026-07-18
references:
- https://www.valtersit.com/cve/cve-2024-58359
logsource:
product: surrealdb
service: server
detection:
selection:
message|contains|all:
- 'panicked at'
- 'sorting'
condition: selection
falsepositives:
- Legitimate server errors unrelated to this CVE
level: high
Suricata IDS Rule
alert tcp $EXTERNAL_NET any -> $HOME_NET 8000 (msg:"CVE-2024-58359 Surrealdb ORDER BY rand() DoS Attempt"; flow:to_server,established; content:"ORDER BY"; nocase; content:"rand()"; nocase; within:100; classtype:attempted-dos; sid:1000001; rev:1;)
Elastic (EQL) Query
sequence by process.entity_id
[process where event.type == "start" and process.name == "surreal"]
[process where event.type == "end" and process.exit_code != 0 and process.name == "surreal"]
Splunk SPL Query
index=main sourcetype=surrealdb:server "panicked at" "sorting"
| stats count by host, source
| where count > 0
Wazuh Rule
<group name="surrealdb,">
<rule id="100001" level="12">
<decoded>json</decoded>
<field name="message">\.*panicked at\.*sorting\.*</field>
<description>SurrealDB: Possible CVE-2024-58359 exploitation - server panic in sorting function</description>
<mitre>
<id>T1499</id>
</mitre>
</rule>
</group>
Remediation & Mitigation
Immediate Actions (0-24 hours)
- Apply Patch: Upgrade to SurrealDB version 2.1.0 or later.
# If using Docker docker pull surrealdb/surrealdb:latest docker stop <container_name> docker run --name <new_container_name> -p 8000:8000 surrealdb/surrealdb:latest start - Compensating Controls (if patch cannot be applied):
- Network-Level: Restrict network access to the SurrealDB server to only trusted IP addresses using a firewall.
- WAF Rule: Create a custom WAF rule to block requests containing
ORDER BY rand(). - Authentication Hardening: Review and revoke unnecessary user accounts. Enforce multi-factor authentication (MFA) for database access if supported.
Short-term (1-7 days)
- Configuration Hardening: Implement a database proxy or middleware that can inspect and block dangerous queries before they reach the SurrealDB server.
- Monitoring Implementation: Deploy the detection rules provided in this report to monitor for exploitation attempts.
- Vulnerability Scanning: Use a vulnerability scanner to identify all SurrealDB instances running versions < 2.1.0.
# Example using curl to check version curl -s http://<surrealdb_host>:8000/version
Long-term
- Architecture Changes: Implement a database cluster with failover to ensure high availability. If one node is crashed, another can take over.
- Security Control Improvements: Integrate a database activity monitoring (DAM) solution to detect and block anomalous queries.
- Developer Training: Educate developers on the risks of non-deterministic functions in
ORDER BYclauses and the importance of input validation.
Validation
- Check Version: Connect to the SurrealDB instance and run:
The returned version should beSELECT * FROM information_schema.system_info WHERE key = 'version';2.1.0or higher. - Test the Fix: Attempt to execute the malicious query:
The patched server should return an error message (e.g., "Cannot sort by a non-deterministic expression") instead of crashing.SELECT * FROM user ORDER BY rand();
References & Resources
- NVD: https://nvd.nist.gov/vuln/detail/CVE-2024-58359
- CVE.org: https://www.cve.org/CVERecord?id=CVE-2024-58359
- Vendor advisory: See vendor security page at https://surrealdb.com/security
- OSV: https://osv.dev/vulnerability/CVE-2024-58359 (if applicable)
- Related CWE: https://cwe.mitre.org/data/definitions/754.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-2024-58359