Today on the Latacora blog, I’m going to talk about database encryption, and how you can protect extra-sensitive data in your database (end-user credentials, user-provided secrets, etc.) by adding application-layer encryption, on top of whatever disk-level encryption you (hopefully) have already.
SQL injection warm-up
But before that, let’s get warmed up. We’re going to be finding SQL injections in a demo app, so let’s start there and I’ll come back to that whole “encryption” thing later. It’ll be fun. I promise. If you’re new to SQL injection or a little rusty, there’s lots of good tutorials that will get you up to speed.
I’ve packaged up this app to run entirely client-side, so don’t view the source of this page or point Claude at the JavaScript bundle or anything silly like that; everything you need to do you’ll be able to do via the UI. (Sorry if you were hoping you’d actually get to hack our blog. Try sending us a phishing email or something?)
Your goal is to find a SQL injection that will let you read the body of another user’s private notes. I’ve given you some debugging tools; you can log in as any user and you can see the database and a log of SQL queries below the app. If you get stuck, there’s hints and a solution below.
Hint
To get the body and not just the title, use a UNION.
Solution
In the search box, enter: ' UNION SELECT id, body FROM notes --. The '
closes the search string in the SQL query, and then we UNION in the body of
all (un-filtered) notes. The -- at the end is a comment marker, so it ignores
the rest of the original query.
Adding encryption
So that’s not great. Someone should probably fix that SQL injection. But let’s talk about a defense-in-depth technique you can use to help secure the data in your database, even if an attacker is able to read data from it. SQL injection is one way, but there’s a whole host of other ways it might happen: database dumps saved to a compromised S3 bucket, syncs to a data warehouse that gets compromised, or read-only database credentials used for a business intelligence tool that get leaked, for example.
I’m going to add application-layer encryption to the body column, so just
being able to read values from the database isn’t enough. There’s a couple ways
to do this:
- When you can, store the secret values in a secret manager provided by your infrastructure, like AWS Secrets Manager. This is ideal in terms of not having to worry about the encryption details and getting a clear audit log of access, but it comes with throughput limitations, per-secret cost, latency, and size limitations. It should be your go-to option when it’s feasible, but for the rest of this post we’re going to assume it’s off the table.
- The second-best option is to use a key management service like AWS KMS to encrypt/decrypt your data. This avoids the need to manage encryption keys or pick algorithms, and is sufficiently cheap and high-throughput enough for most use cases.
- If neither of those work, you should generate a random key, give it to your application, and use the encryption algorithms recommended by some ostensibly smart folks over at an ostensibly reputable security firm.
I’m going to do that last one for this example, to keep everything running
in-browser: I’ll encrypt the body column using XChaCha20-Poly1305. Try your
SQL injection from above, and you’ll find that you’re only able to extract the
ciphertext.
This is great! I’m going to encrypt everything!
Well, wait a second. I love the enthusiasm, but there’s some limitations. You’ve put this data in a database for some reason, and there’s some functionality you’re going to lose by applying encryption. The biggest issue is search: you’ve hopefully followed our advice to use a long, random nonce for each ciphertext (or used a KMS, which handles that for you). So the same plaintext will encrypt to different ciphertexts! This breaks any straightforward search implementation, and for good reason: if the same plaintext encrypted to the same ciphertext, you’d be able to determine whether two values are the same just from looking at the ciphertext, which is especially bad if you can control the plaintext.
Imagine, for example, that the column contains the three-digit CVV code of a credit card. If I wanted to be able to decrypt any CVV, I’d just sign up for this super secure notes app, add 999 notes with each possible CVV, and then I could decrypt CVVs by seeing which of my 999 known ciphertexts they correspond to.
So this particular technique is only good for values where you’re just storing and reading them, and not doing any other work with them. That’s not actually great for a notes app (it’s just a simple example that’s easy for us to work with in this post). It is a good option for storing end-user OAuth credentials for an app that connects to your Google Calendar, or a financial app that needs to store bank account or credit card numbers, or an app that stores API credentials to connect to third party systems.
If you do need to also search the encrypted data, there’s some techniques for that too, and some other folks have written good introductions to that topic. But we’ll stick with the easier case of data that we just need to read and write.
Confused deputies
This is a good start, but we’re not quite finished here. Let’s talk a bit about the “confused deputy problem.” Our application (the “deputy”) is responsible for decrypting the ciphertext for us so that we can read it in when we’re using the application legitimately, but not when we find a SQL injection or some other way to access the database directly.
The “confusion” happens if we can trick the application into decrypting another user’s data. In this scenario, we’re working from a threat model that includes an attacker who has some access to the database directly (SQL injection or otherwise), or else we wouldn’t need to worry about encryption at all. So what happens if an attacker can move another user’s encrypted data into a location where our application will happily decrypt it for the attacker? Let’s find out.
Here’s the next version of our encrypted notes app. I’m trying to raise a couple mil in VC money, so I’ve added a killer feature: the ability to change the name of a note. Your task: figure out how to exploit this new feature to read another user’s encrypted notes, like we could before some dastardly cryptographer encrypted that column. Like before, there’s hints and a solution at the bottom if you get stuck.
Hint 1
Your goal is to copy the ciphertext of another note’s body into one of your own notes, so that the application will decrypt that body for you as if it was your own note.
The SQL that the rename is running is:
`UPDATE notes SET title = '${title}' WHERE id = ${noteId} AND user_id = ${state.userId}`;
Hint 2
You can add a second assignment to the UPDATE, and use a subquery to read
another user’s encrypted note.
Solution
To read Bob’s note from Alice’s account, rename one of Alice’s notes to:
x', body = (SELECT body FROM notes WHERE id = 3) WHERE id = 1 --
This copied the encrypted note with ID 3 (Bob’s note) to the body of the note
with ID 1 (Alice’s note). The application will then show Bob’s decrypted note
to Alice.
Wow. I guess cryptography is useless.
So true! Let’s fire all the cryptographers. Wait no, that’s not quite right. I
hear those smart folks have come up with something called “associated data,”
and we all know that slapping some more crypto on our problem thoughtfully
addressing our threat model with battle-tested primitives will address these
issues.
So what’s this associated data thing? Let’s talk about the operation of modern symmetric encryption algorithms, which are generally what we call “AEAD methods.” AEAD stands for Authenticated Encryption with Associated Data:
- Authenticated: nobody can tamper with the ciphertext without it being detected during the decryption process. This prevents issues like CBC bit-flipping, among others. We use a nonce during the encryption process, so that the same plaintext produces different ciphertexts each time.
- Encryption: you need the secret key to decrypt the data. You probably know about this one.
- Associated Data: you can provide some additional, non-secret data during the encryption process. This data gets folded into the authentication tag that’s used for that “Authenticated” property. If you don’t provide exactly the same associated data during decryption, the authentication step will fail and you’ll get an error. Importantly, the algorithm won’t even attempt decryption if the verification fails, so there’s no way to accidentally use un-authenticated data, or data where the associated data was different.
That last one doesn’t sound that useful at first, but it’s exactly what we need to solve this problem. This allows us to “bind” the ciphertext to a particular context, which we’ll provide as the associated data. In this case, we’ll pass the user ID (and, for good measure, the database table name and database column name) as our context / “associated data.” When we decrypt, we’ll pass those values again and if there’s a mismatch, we know that we’re decrypting the data for the wrong user (and immediately stop). The ciphertext we store in the database becomes “bound” to the user it was encrypted for. Even if an attacker can relocate that ciphertext to a location that the application would decrypt for them, the application will do it in a different context (passing a different associated data), and decryption will fail.
Most modern encryption algorithms support associated data, as do most standard KMS systems. One key thing to remember: the associated data does not get stored alongside the ciphertext, tag, and nonce. Instead, you re-derive it from the context. In this case, the table and column name would be hard-coded into the application source code, and the user ID would come from your application’s authentication code (for example, from a session cookie). This ensures that an attacker who can tamper with the database can’t tamper with the associated data.
Here’s the final version of our application, with that protection in place. The
body column is encrypted using the table name, column name, and user ID as
additional data. Try the same SQL injection from the previous step!
You should get an error in the UI, “Unable to display this note.” That corresponds to the error in the decryption log, “Poly1305 tag verification failed.” Poly1305 is the authentication tag component of our XChaCha20-Poly1305 algorithm, and that error means that the authentication part of decryption failed, because the user ID the application passed during decryption didn’t match the user ID the secret data was encrypted for.
Takeaways
Good work! Hopefully you feel at least a little accomplished, and I hope you walk away with a couple of lessons in mind:
- If you have especially valuable data in your database, and you don’t need to search or manipulate it, consider applying application-level encryption to that data to protect it from attackers who get read or write access to the database.
- Do that by following some good advice on how to encrypt it.
- Use associated data (sometimes called “encryption context”) to bind the ciphertext to the context it should be locked to: the table name, the column name, and something that identifies the authenticated user, like their user ID (or tenant ID, for a multi-tenant system where encrypted values can be shared within a tenant). This protects you from an attacker who can move data around the database to try and trick your application into decrypting it for them.