Remote code execution vulnerability in SQLite
blade.tencent.com
blade.tencent.com
My best guess for the bug is that arbitrary SQLite queries, prior to 3.26.0, were permitted to write to the shadow tables used by various plugins to implement features. fts3/4, prior to 3.25.3, appear to contain an integer overflow bug which can be triggered by manually modifying the fts index data. A careful application of this integer overflow appears to make it possible to truncate a writable buffer, leading to a nice heap overflow condition that can be exploited by further crafted SQL queries.
The primary integer overflow bug was fixed in https://sqlite.org/src/info/940f2adc8541a838 "Add extra defenses against strategically corrupt databases to fts3/4.", committed as part of the 3.25.3 update (which is what Chromium updated to). Later, in 3.26.0, they further secure it by making shadow tables optionally read-only.
The worrying thing here is that SQLite3, in its default configuration, is still not convincingly secure. Being able to write arbitrary data to the shadow tables has the potential to break all sorts of assumed invariants, and it's pretty clear that the SQLite3 developers did not necessarily anticipate all the ways in which this could break. The "SQLITE_DBCONFIG_DEFENSIVE" option which was added does not appear to be on by default, and it breaks backwards compatibility (setting it causes SQL imports from .dump to fail because .dump assumes shadow tables are writable during import).
There may be more bugs lurking in this area - this would be an excellent opportunity to fuzz all the plugins in SQLite to see if any of them barf when their shadow tables are corrupted.
The vulnerability only exists in applications that allow a potential attacker to run arbitrary SQL. If an application allows that, it is usually called an "SQL Injection" vulnerability and is the fault of the application, not the database engine. The one notable exception to this rule is WebSQL in Chrome.
I put up https://www.sqlite.org/security.html recently to serve as guidance for people who want to live on the edge and give unrestricted SQL access (or unrestricted database file access) to potentially hostile attackers. That page is a work in progress. More could be said. For example, it is probably also a good idea to use various obscure APIs to limit the length of SQL statements or the amount of memory that can be used, to avoid DOS attacks. I'll keep improving the document as I have time.
Our intent is that SQLite should be secure against these kinds of attacks. We have spent years fuzzing it to try to find these problems. But the thing is, we never configured a fuzzer in such a way that it might start modifying the shadow tables of FTS3, and so we missed this one. Moral: never underestimate the ingenuity of a motivated gray-hat.
The Chrome people have recently starting fuzzing SQLite database files on Google's infrastructure. We had previously only fuzzed database files on our own workstations. It's amazing the number of new problems you can find when you run a fuzzer at scale. :-) A few more problems have been fixed. We are not aware of any exploits. And in particular, if you follow the advice of the article above and "PRAGMA quick_check" untrusted database files or set "PRAGMA cell_size_check=ON" then none of the recently found and fixed issues are reachable.
To me, "trusted" is: queries entered by the local user (or, for setuid programs, by the local system administrator instead of the local user), or that are built in to the program. Others are untrusted.
And yet, I have already considered these kind of vulnerability before even knowing about it.
Start with the 2018 nominations but feel free to check the archives. Drive-by browser vulnerabilities are RCEs.
I would never argue they aren't, but by this logic ("it's like saying PDF or JPEG parsers can't be vulnerable to RCE") virtually every code execution vuln in a library can be called RCE. I haven't noticed this to be the case with e.g. libtiff vulnerabilities (of which many make it into my inbox regularly), although image libraries are one of the cases were CE = RCE is still fairly reasonable.
Let's assume this SQLite bug is only exploitable if you can input arbitrary SQL. Almost no applications use it this way (except Chrome). I think it's clearly unreasonable to call it a RCE in SQLite then.
Should we fix bugs? Yes. Should we scream at people that expose raw APIs they don't understand far beyond their design constraints? Yes yes yes.
In practice, however, the community gets more bang for their buck if they label the SQLite code execution vulnerability as an RCE since the vast majority of use is in a networked setting. You have to remember the audience used for these terms. They aren’t scientists in the traditional sense where taxonomy is highly aligned the ontology — instead, the labeling serves the operators with metaphors that depart from reality insofaras they increase security engineers ability to do their job effectively.
(This is still a serious security vulnerability)
You may not notice that you do when apps use sqlite as their file format:
e.g. SQLite has an ACE. Chrome has a RCE (which is SQLite's fault).
I sort of intellectually in the back of my head know that "arbitrary code execution" is a term that has been coined and used in the past, but I don't offhand know of anyone that uses it (among other things, it's kind of redundant). "Local only" code execution vulnerabilities aren't "LCE", but rather (usually) "privilege escalation".
Say for some reason someone used an exploitable version of SQLite in a program that had the setuid bit set. You wouldn't say SQLite had a privilege escalation vulnerability, would you?
Usage example: "I got code execution!"
I think a better way of looking at it is that it's an ACE Vulnerability in the e.g. JPEG parser that causes an RCE in the Online Service.
Or, in this case, an ACE vulnerability in SQLite that causes an RCE in Chromium.
Since SQLite in and of itself is just a library, it doesn't have that problem. You have to expose it to untrusted inputs manually somehow (e.g. by setting up a socket).
value = 1 / input;
You can get "100% coverage" if you test that with `input = 1`, but unless you check with `input = 0` you're missing a quite important logical check. data Nat = Z | S Nat
data NonZeroNat = OnePlus Nat
data NonZeroInt = Negative NonZeroNat | Positive NonZeroNat struct nonzero_t {
int is_negative;
unsigned int one_less_than_the_absolute_value;
};
which, under interpretation, ranges from -(2^32) to -1 and +1 to +(2^32).I try to only use random data when possible, less and smaller tests to write with a proper setup. End result: more bugs found.
Random data is a great method of testing.
Consider a function which checks 5 simple if-statements in a row, always in the same order. Getting each branch means you tested 10 things.
But there are 32 ways for 5 if-statements to jointly evaluate. If there is a logical dependency between the state checked by one if-statement and the state checked by another one, your perfect coverage may not pick up on that.
If the if-statements might be checked in an arbitrary order... there are 120 ways to order 5 things. But you'll still get perfect branch coverage by checking 10 of them.
int returns_less_than_twelve(int input1, int input2) {
int sum = 0;
if (input >= 5) {
sum += 5;
}
if (input2 >= 5) {
sum += 8;
}
return sum;
}
The following test cases will pass and achieve 100% branch coverage. int x = returns_less_than_twelve(5,0);
test_assert(x < 12);
int y = returns_less_than_twelve(0,5);
test_assert(x < 12);
However, this does not cover the entire input space so returns_less_than_twelve(5,5);
test_assert(x < 12);
Will fail. However, branch coverage won't tell you that there's a hole in your test coverage.Generally however, writing full branch coverage will find a lot of issues, and also cause you to really think through how your code works; but still, it doesn't guarantee correctness. If you want that you need to start bringing tools that either exhaust your input space (a function which takes 5 booleans can be exhaustively tested for correctness in trivial amounts of time), or you start modeling your chosen language well enough that you can use a mathematical prover to demonstrate that your program or function is safe on all inputs.
This of course requires you to come up with a definition of 'correct' or 'safe'. For the above program, it's clear how to define correctness. For things like "Don't let an unauthorized individual access this data or data that is derived from it in a way contrary to the desires of the owner of said data" it gets 'tricky' ;).
Achieving 100% MC/DC does not prove that you always get the right answer. All it means is that your tests are so extensive that you managed to get every machine-code branch to go in both directions at least once. It is a high standard and is difficult to achieve. It does not mean that the software is perfect.
But it does help. A lot. When I was young, I used to think I could right flawless code. Then I wrote SQLite, and it got picked up and used by lots of applications. It will amaze you how many problems will crop up when your code runs on in millions of application on billions of devices.
I was getting a steady stream of bug reports against SQLite. Then I took 10 months (2008-09-25 through 2009-07-25) to write the 100% MC/DC tests for SQLite. And after that, the number of bug reports slowed to a trickle. There still are bugs. But the number of bugs is greatly reduced. (Note that 100% MC/DC was first obtained on 2009-07-25, but the work did not end there. I spend most of my development time adding and enhancing test cases to keep up with changes in the deliverable SQLite code.)
100% MC/DC is just an arbitrary threshold - a high threshold and one that is easy to measure and difficult to cheat - but it is just a threshold at which we say "enough". You could just as easily choose a different threshold, such as 100% line coverage. The higher the threshold, the fewer bugs will slip through. But there will always be bugs.
My experience is that the weird tests you end up having to write just to cause some obscure branch to go one way or another end up finding problems in totally unrelated parts of the system. One of the chief benefits of 100% MC/DC is not so much that every branch is tested, but rather that you have to write so many tests, and such strange, weird, convoluted, and stressful tests, that you randomly stumble across (and fix) lots of problems you would have never thought about otherwise.
Another big advantage of 100% MC/DC is that once they are in place, you can change anything, anywhere in the code, and if the tests all still pass, you have high confidence that you didn't break anything. This enables us to evolve the SQLite code much faster than we could otherwise, using relatively few eyeballs.
Yet another advantage of 100% MC/DC is that you are really testing compiled machine code, not source code. So you worry less about compiler bugs. "Undefined behavior" is a big bugbear with C. We worry less than others about UB because we have tested the output of the compiler and we know that the compiler did what we wanted, even if the official C-language spec didn't require it to. We still avoid UB, and SQLite does not currently contain any UB as far as we know. But is is nice to know that even if we missed some UB in the code someplace, it probably doesn't matter.
A thought: would it help to have a modified C compiler that would crash the app whenever UB was encountered? It might help find some bugs where non-default C compiler was used (which I assume happens, given the large amount of platforms sqlite supports). Or am I missing something?
In this specific case, a unit test that checked this integer overflow seeems to prevent the vulnerability.
To be clear: This is not to admonish sqlite. They have taken testing further than any other project i've heard of, except maybe the NASA software that might cost lives if it fails.
This has much less to do with C, than it has to do with the fact that sqlite is a huge codebase.
Software can be vulnerable regardless of the programming languages used.
Edit: Apparently the exploit vector is due to WebSQL.
And my guess as for the vulnerability area are "strategically corrupt databases", because there have been numerous commits related to this in the relevant SQLite releases and some seem like they were added relatively late in the process (e.g. after changing the VERSION file but before releasing).
Afaik Chrome and its derivatives lack any form of user control over local storage. No Quota mechanisms, no domain black/white listing, no feature toggle. localStorage, webSql, IndexedDB, Filesystem API, all forced on with no limits under user control.
In a better world this would be an easy fix for Chrome users unable to upgrade their browser, flip one config setting to disable webSql and you are done, alas Google wont let you do that. Cant wait for first worm using this vuln.
https://chromium.googlesource.com/chromium/src/+/c368e30ae55...
for(i=0; i<nChar; i++){
if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
if( (unsigned char)p[n++]>=0xc0 ){
- while( (p[n] & 0xc0)==0x80 ) n++;
+ while( (p[n] & 0xc0)==0x80 ){
+ n++;
+ if( n>=nByte ) break;
+ }
}
}
return n;
Looks like there may have been an issue in parsing malformed multibyte unicode characters properly. const secondStatements = [
"SELECT quote(root) from ft_segdir;",
"UPDATE ft_segdir SET root = X'0005616261636B03010200FFFFFFFF070266740302020003046E646F6E03030200';",
"SELECT * FROM ft WHERE ft MATCH 'abandon';"
];
Just saw the proof of concept page. Looks like they are building quite the usual string in hex... Starting with a null terminator? MmmhmmmEdit: it's "To be allocated": "[$TBD][900910] High To be allocated: Multiple issues in SQLite via WebSQL. Reported by Wenxiang Qian of Tencent Blade Team on 2018-11-01" (from https://chromereleases.googleblog.com/2018/12/stable-channel...)
Skimming that log doesn't give me any ideas.. maybe the diff would help elucidate?
SQLITE_DBCONFIG_DEFENSIVE The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the "defensive" flag for a database connection. When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. The disabled features include but are not limited to the following: The PRAGMA writable_schema=ON statement. Writes to the sqlite_dbpage virtual table. Direct writes to shadow tables.
https://chromium.googlesource.com/chromium/src/+/c368e30ae55...
The fact that Chromium also saw fit to patch this suggests further that there was likely some way that it could be tricked into issuing queries that did this, allowing some compromise of the browser. If this could have been triggered by a web page, then that explains why they are light on details.
It should be noted that a lot of applications embed SQLite internally. If one as well studied as Chromium could be tricked in this way, I'm sure that others can as well. And since the upgrade has to happen to an embedded component, we're probably going to hear about this one for a while.
Please note, this is all educated guesswork from knowing the software ecosystem and reading release notes. I have absolutely no knowledge of the vulnerability.
Chromium still supports WebSQL, though, which gives you essentially free reign on a SQLite database. This is quite different from the way most applications expose SQLite to untrusted data (i.e. only through parameter binding).
Then, the rest is "to be safe" measures, because it was possible for carefully crafted SQL to intentionally corrupt the database in controllable ways, including triggering the former bug. This isn't really the bug fix, but rather a measure to reduce the attack surface against similar undiscovered bugs.
This is speculation, though.
The new SQLITE_DBCONFIG_DEFENSIVE features is more of a defense-in-depth, designed to head off future vulnerabilities by making shadow-tables read-only to ordinary SQL, along with some other restrictions. If you have an application that allows potential attackers to run arbitrary SQL, then the use of SQLITE_DBCONFIG_DEFENSIVE is recommended. It is not required. We still consider it a serious bug if somebody is able to find an exploit even with SQLITE_DBCONFIG_DEFENSIVE turned off. But that setting reduces the attack surface, making future bugs less likely.
"Compatibility Note: The behavior of ALTER TABLE when renaming a table was enhanced in versions 3.25.0 (2018-09-15) and 3.26.0 (2018-12-01) in order to carry the rename operation forward into triggers and views that reference the renamed table. This is considered an improvement. Applications that depend on the older (and arguably buggy)..."
A problem that (well tailored) enables a RCE is just "arguably buggy" in their view?
The comments in checkin a61ed147 for "renameColumnFunc()" give me the willies.
Edit: Yes, this is probably it.
the app installed on your phone to control say a Chromecast,
or a smart speaker.
I think that this is an important lesson about testing. We should have fewer tests but we should try to get the most value possible out of each one and for developers that means actively seeking out unusual edge cases that are likely to break things.
(1) The coverage testing used by SQLite is very good at finding problems that occur when the system is used as it was intended. Fuzz testing is better for finding vulnerabilities that can be exploited by a hacker. The 100% MC/DC testing in SQLite is very useful in ensuring that the code does what is intended for sane inputs. And 100% MC/DC helps prevent us from breaking things as we evolve and enhance the code. But the MC/DC testing is less useful at fending off attackers.
(2) The magellan vulnerability exploits a bug in an SQLite extension, FTS3, which while very well tested, is not testing to 100% MC/DC. (See the second sentence at https://www.sqlite.org/testing.html#test_coverage)
Hence my takeaways from this episode include that I need to extend 100% MC/DC testing to all commonly used extensions in SQLite, including FTS3, FTS5, and RTREE, and I need to improve fuzz testing throughout SQLite but especially in extensions.
Advocates of "safe" language correctly observe that this particular problem would not have happened if SQLite were written in (say) Rust. Rewriting SQLite in Rust in not (yet) a viable solution. (See https://www.sqlite.org/whyc.html) But I can start moving SQLite in that direction, and perhaps make use of techniques taken from safe languages to improve its resistance to attack.
Does this mean Python needs to ship a security path? What should Python users be doing about this?
Python binaries (e.g. the Windows installers) may need to be updated. For Linux distros Python would depend on a system package.
Of course, on Windows, it's going to have to use its own sqlite3.
On Linux/macos, the Python extension (usually) links dynamically to a shared sqlite3 system library.
If I write a hello world C program that does some sort of IO with SQLite, it will be vulnerable to remote code execution? (if this turns out to be true, that will be quite impressive!)
Guessing something was lost in translation there. Sounds more like someone found a way to get code execution if you can inject certain data into SQLite, then found various applications that expose this functionality remotely?
But if that is the case this is huge. SQLite is used in many places nowadays: Websites, browsers (Chromium and Firefox, I know of), various software including some Android apps. That also probably means the attack vector is some procedure where input is sanitized (assuming SQLite provides that, I never programmed against the C API).
(Edit: wrong term, it's not "HTML5 Local Storage", it's "HTML5 Database" thanks):
Chromium (EDIT: idk yet)
Webkit2: https://webkitgtk.org/reference/webkit2gtk/stable/WebKitSett...
Edit: don't disable local storage! you'll break lots of things that way, and I don't think that includes WebSQL.
And the phrase "uses SQLite or Chromium" is pretty close to gibberish. Those two things... are not really related.
I highly doubt this would affect, say, a blog running with a sqlite database. From the alarmist nature of this post, though, it's unclear.
I see chromium, in their patch, switched to using new flags when opening the DB. There are also some sqlite changes that seem to prevent meddling with virtual table shadow tables (eg inverted index for the fts3 extension).
The question I think everyone is asking is how much sqlite needs to be exposed by an application in order to be vulnerable?
Just my thoughts. Eager to learn more.
https://chromereleases.googleblog.com/2018/12/stable-channel...
The Chromium exposure is through Web SQL.