-
-
Notifications
You must be signed in to change notification settings - Fork 836
Description
Bug Description
I've discovered a potential memory safety issue in the popular node-sqlite3
JavaScript library that can lead to undefined behavior. The bug involves the unsafe use of memcpy
with unsanitized input, specifically when passing NULL as the second argument.
Technical Details
In the node-sqlite3
library, there's a vulnerability in the statement.h
file, around line 60, where memcpy
is called without validating that the source pointer is not NULL:
memcpy(ptr, NULL, 0);
According to the C standard, the second argument of memcpy
should never be NULL, even if the size is 0, as this results in undefined behavior.
How to Reproduce
- Create an SQLite database with a BLOB column containing empty data:
sqlite3 "test.db" <<EOF
CREATE TABLE files (id INTEGER PRIMARY KEY, data BLOB);
INSERT INTO files (data) VALUES (X'');
EOF
- Create a Node.js script to query this data:
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('test.db');
db.get("SELECT data FROM files LIMIT 1", (err, row) => {
if (err) {
console.error("Query error:", err);
return;
}
const blob = row.data;
console.log("Raw blob value:", blob);
console.log("Type:", typeof blob);
if (Buffer.isBuffer(blob)) {
console.log("Length of blob:", blob.length);
console.log("Hex dump:", blob.toString('hex'));
} else if (blob === null) {
console.log("Value is NULL");
}
db.close();
});
- When running this script with certain build configurations (particularly with sanitizers enabled), you'll see the undefined behavior error:
../src/statement.h:60:19: runtime error: null pointer passed as argument 2, which is declared to never be null
Current Status
I've found that this issue is already known and being addressed in the upstream repository:
- Issue: call to memcpy leads to undefined behavior #1827
- Fix: fix: potential null pointer dereference in Blob constructor #1832
The fix is relatively simple - adding a NULL check before calling memcpy
:
if (val != nullptr) {
memcpy(value, val, len);
}
Impact
This bug affects applications using node-sqlite3
that:
- Deal with empty BLOB values in SQLite databases
- May be running with sanitizers or in environments that strictly enforce memory safety
While it may not cause immediate crashes in normal operation, it's technically undefined behavior and could lead to unpredictable results, especially on different platforms or compiler configurations.
Recommendations
If you're using node-sqlite3
in your projects, consider one of these options:
- Watch for the next release that includes the fix (PR fix: potential null pointer dereference in Blob constructor #1832)
- Apply the patch manually if you're building from source
- Use an alternative SQLite library like
better-sqlite3
that might not have this issue
I'll continue to monitor the status of the fix and provide updates as needed.