Vineet Ganti
Database Security: TLS, the Wire Protocol, Least Privilege and Computing on Encrypted Data
All posts

Data Engineering/Database Engineering · Part 13 of 14

·15 min read

Database Security: TLS, the Wire Protocol, Least Privilege and Computing on Encrypted Data

Turning on TLS for Postgres and watching it fail in useful ways, reading a real conversation on the wire, permissions that surprise you, the largest query I could send, and adding numbers that stay encrypted, live in your browser.

DatabasesPostgreSQLSecurityTLSEncryption

Most of this series has been about making databases fast and correct. This post is about who gets to talk to them, and what an attacker on the wire can see.

The course's lectures here are hands-on: enabling TLS, reading packet captures, building a to-do app with minimal permissions, and trying homomorphic encryption. I re-ran them on real servers, captured a real conversation through a logging proxy, and built a working homomorphic demo that runs in your browser. Several of the failures turned out to be the most useful part.

#Encrypting the connection

#Turning on TLS

The course's demo starts with a client insisting on TLS, against a fresh Postgres, and fails. I repeated it, including the mistakes:

✅ ran here · PostgreSQL 18.6 · TLS, step by step
-- a new container, client asks for TLS
error: The server does not support SSL connections

$ openssl req -x509 -newkey rsa:4096 -nodes -keyout private.pem -out cert.pem
# ssl = on in postgresql.conf, key left readable by everyone (chmod 644)
$ docker restart
container state: exited
FATAL:  private key file "private.pem" has group or world access

$ chmod 600 private.pem
$ docker restart
-- connect with TLS
{"ssl":true,"version":"TLSv1.3","cipher":"TLS_AES_256_GCM_SHA384"}

-- connect without TLS: it's still allowed
{"ssl":false}

-- connect with TLS, checking the certificate
error: self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca

# pg_hba.conf: host all all all  ->  hostssl all all all
-- connect without TLS again
error: no pg_hba.conf entry for host "172.17.0.1", user "postgres", database "postgres", no encryption

Reading that from the top:

  1. A new container has TLS off. The client got The server does not support SSL connections.
  2. With a key left world-readable, the server wouldn't start at all. private key file has group or world access, and the container exited. That protection is on purpose: the docs require it.
  3. After chmod 600, TLS works. TLS 1.3 here.
  4. A plain connection still works. This is the part to remember. TLS is now possible, and clients can still choose not to use it.
  5. Verifying the certificate fails, because it's self-signed. A client that doesn't verify is protected from eavesdropping, but not from an impostor.
  6. hostssl in pg_hba.conf finally refuses plain connections.

#A connection, byte by byte

The course reads Postgres and MongoDB packets in Wireshark. I put a small logging TCP proxy between a real client and a real server, so every byte passed through it, and decoded the messages. Compare the two tabs:

StartupMessage62 Buser postgres database postgres client_encoding UTF8
AuthenticationSASL24 BSCRAM-SHA-256
PasswordMessage / SASL response56 BSCRAM-SHA-256 !n,,n=*,r=XxzSam2NI0BaOhMBxQ6PNSoK
AuthenticationSASLContinue93 Br=XxzSam2NI0BaOhMBxQ6PNSoK6pmmkBZjELK+XnSfvvkbLKLm,s=kTihwWtT1FHOA1lC0vmFYw==,i=4096
PasswordMessage / SASL response109 Bc=biws,r=XxzSam2NI0BaOhMBxQ6PNSoK6pmmkBZjELK+XnSfvvkbLKLm,p=h50pDYG8YFovx3+BSooATI2JHVaxPM53LEFJaZNPU+Q=
AuthenticationSASLFinal55 Bv=MxyIkJg+zVtcO4zG+kjES1D+oF/98JqfuOb3nFCMN90=
AuthenticationOk9 B
ParameterStatus441 B15 settings, such as server_version and TimeZone
BackendKeyData13 B9 X
ReadyForQuery6 BI
Query38 BSELECT 'my secret value' AS note
RowDescription30 Bnote
DataRow26 Bmy secret value
CommandComplete14 BSELECT 1
ReadyForQuery6 BI
Terminate5 B
The query was SELECT 'my secret value'. Searching every captured byte for that text: found, in plain sight. ✅ captured from PostgreSQL 18.6

Here's the shape of that conversation:

Without TLS, anyone on the path reads the user, the database, the query and the result. The password is a different story: the SCRAM exchange proves knowledge of it without sending it. With TLS, after a one-byte S to accept, everything is opaque, and a search for the query text finds nothing.

#What the server tells a stranger

The course dislikes how much an error can reveal. Here's what a failed login gets back, field by field:

✅ ran here · PostgreSQL 18.6
SHOW password_encryption;
SELECT left(rolpassword, 30) FROM pg_authid WHERE rolname = 'postgres';
scram-sha-256
SCRAM-SHA-256$4096:kTihwWtT1FH…

-- three failed logins, and everything the server sent back
wrong password: FATAL 28P01 "password authentication failed for user "postgres"" (auth.c:317, auth_failed)
unknown user: FATAL 28P01 "password authentication failed for user "ghost"" (auth.c:317, auth_failed)
unknown database: FATAL 3D000 "database "ghost" does not exist" (postinit.c:1014, InitPostgres)

Two things are worth noticing. A wrong password and an unknown user get the same message, which is good, because it hides which accounts exist. But the error carries a source file and line number, and an unknown database gets a distinct reply, so a stranger can tell which databases exist. In your own API, log the detail and send the client something vague.

#MongoDB's wire

The course's other capture is MongoDB Atlas: a TLS 1.3 handshake, then a hello that returns the cluster's topology, then SCRAM. Drivers are lazy, so nothing is sent until the first real query. On a local server without TLS, I built the hello by hand to see the format:

✅ ran here · MongoDB 8.0.34 · OP_MSG, by hand
-- a hand-built OP_MSG for { hello: 1, $db: "admin" }, 52 bytes
34 00 00 00 01 00 00 00 00 00 00 00 dd 07 00 00 00 00 00 00 00 1f 00 00 00 10 68 65 6c 6c 6f 00  …

-- the reply's header, then fields of its BSON document
length 313, responseTo 1, opCode 2013 (OP_MSG)
isWritablePrimary: true
maxBsonObjectSize: 16777216
maxMessageSizeBytes: 48000000
minWireVersion: 0, maxWireVersion: 25
readOnly: false

dd 07 is 2013 in little-endian bytes: the OP_MSG opcode. The reply tells a client the server's limits, and with a replica set it would list the hosts, so that the client can find the primary.

#Least privilege

The course's to-do app question begins with an innocent idea: should an app run CREATE TABLE IF NOT EXISTS at startup? The answer leads to a bigger one: an app's database user shouldn't be able to do that, or anything else it doesn't need.

The design is three connection pools, one per role, with each route using the role it needs. Building it was full of surprises for the course, and for me:

✅ ran here · PostgreSQL 18.6 · three roles, tested
SET ROLE dbcreate;

INSERT INTO todos (text) VALUES ('second');
ERROR:  permission denied for sequence todos_id_seq

RESET ROLE;

GRANT USAGE ON SEQUENCE todos_id_seq TO dbcreate;

SET ROLE dbcreate;

INSERT INTO todos (text) VALUES ('second') RETURNING id;
ERROR:  permission denied for table todos

INSERT INTO todos (text) VALUES ('third');

SELECT * FROM todos;
ERROR:  permission denied for table todos

RESET ROLE;

SET ROLE dbdelete;

DELETE FROM todos WHERE id = 1;
ERROR:  permission denied for table todos

RESET ROLE;

GRANT SELECT ON todos TO dbdelete;

SET ROLE dbdelete;

DELETE FROM todos WHERE id = 1;

RESET ROLE;

SET ROLE dbread;

DELETE FROM todos;
ERROR:  permission denied for table todos

CREATE TABLE IF NOT EXISTS app_table (id int);
ERROR:  permission denied for schema public
LINE 1: CREATE TABLE IF NOT EXISTS app_table (id int);
                                   ^
What failedWhyThe fix
INSERTA serial column reads a sequenceGRANT USAGE ON SEQUENCE
INSERT ... RETURNING idRETURNING reads the row backGRANT SELECT, or don't use it
DELETE ... WHERE id = 1The WHERE reads the columnGRANT SELECT
CREATE TABLESince Postgres 15 public isn't writable by allRun migrations as a separate owner

The RETURNING failure wasn't in the course. I hit it because the first version of my test used it. Each of these looks like a bug until you see the reason, so test every role against every query it will run. Try them here:

Least privilege, testedruns in your browser
A role that can only insert. Each preset is a surprise from the course: read the error, then grant the missing right.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#What this buys you

Here's a SQL injection, with the string the attacker would supply, first as the table's owner, then as the read-only role:

✅ ran here · PostgreSQL 18.6
-- the app builds: SELECT * FROM todos WHERE id = ' + input + '
SELECT * FROM todos WHERE id = 1 OR 1 = 1;
 id | text 
----+------
  1 | a
  2 | b
(2 rows)

SELECT id, text FROM todos WHERE id = 0 UNION SELECT id, password FROM users;
 id |  text   
----+---------
  1 | hunter2
(1 row)

SET ROLE dbread;

SELECT id, text FROM todos WHERE id = 0 UNION SELECT id, password FROM users;
ERROR:  permission denied for table users

DROP TABLE todos;
ERROR:  must be owner of table todos

As the owner, the injected UNION read every password. As dbread, the same attack fails on users, and DROP TABLE fails too. Parameterised queries are what stop injection. Roles are what limit the damage if one gets through. The course's other habits: put credentials in environment variables, keep errors vague, and put a limit on every query.

#The largest query

The course asks how big a query can get. It builds WHERE id = 1 OR id = 2 OR ... in Node and sends it to a free hosted Postgres, which handled 100,000 ids and crashed at a million. I ran the same test on a local server:

✅ ran here · PostgreSQL 18.6 · one query, growing
-- SELECT count(*) FROM t WHERE id = 1 OR id = 2 OR ...
      100 ids        1 KB of SQL  ~     1 TCP segments  ok in 2 ms
     1000 ids       12 KB of SQL  ~     9 TCP segments  ok in 3 ms
    10000 ids      126 KB of SQL  ~    89 TCP segments  ok in 34 ms
   100000 ids     1356 KB of SQL  ~   952 TCP segments  ok in 800 ms
  1000000 ids    14540 KB of SQL  ~ 10198 TCP segments  ok in 54332 ms

A million ids is 14 MB of SQL and about 10,000 TCP segments, and it worked here, in 54 seconds. So the course's crash came from that small hosted server's memory limit rather than from a protocol limit. Most of the time goes on parsing and planning a huge expression. The fix is to send the data as data:

At 1M ids in the list: id = 1 OR id = 2 … 54,332 ms · id = ANY($1) 935 ms ✅ measured on PostgreSQL 18.6

The same million ids as one array parameter took under a second. It's also safe from injection, for free.

#Encrypting data in use

TLS protects data on the wire, and disk encryption protects it at rest. But to run a query, the server must see the data in the clear. Queries, indexes and analytics all need that. So does a layer 7 proxy that terminates TLS, as post 10 noted.

Homomorphic encryption computes on ciphertext directly. Encrypt 7 and 3, hand them to a server, and it can produce the encryption of 10 without learning any of them. Here it is for real, in your browser, with 512-bit Paillier keys. Paillier can only add, and that's enough to see the idea:

Client: holds the private key
Ana52,000
Ben61,000
Cara47,000
Server: sees only this
Nothing yet.
Press the first button. The keys are 512-bit Paillier keys, made here in your browser.

Adding became multiplying ciphertexts, and the server never held a key. Note the size: a number that fits in 16 bits became a ciphertext of over a thousand. Each encryption of the same value also comes out different, which matters: otherwise you could spot equal salaries.

The course goes further, with IBM's toolkit for fully homomorphic encryption, which handles any computation. Its demo looks up a capital city in an encrypted table of 48 countries, without the server learning the query.

🎓 On a 2015 MacBook, the lecture's single lookup took about two minutes. Its point stands, whatever the hardware: this works, it's slow, and today it suits batch analytics on sensitive data more than ordinary queries. I didn't re-run the toolkit, which dates from 2020.

#Things that can trip you up

  • ssl = on doesn't require TLS. Check pg_hba.conf.
  • sslmode=require doesn't verify the server. verify-full does.
  • Key file permissions. Too open, and the server won't start.
  • GRANT INSERT isn't enough for serial columns. Grant the sequence as well.
  • DELETE ... WHERE and RETURNING need SELECT.
  • Using the owner role in the app. One injection then reaches everything.
  • Sending error details to clients. Log them instead.
  • Huge IN or OR lists built as text. Pass an array.
  • Trusting a query log. It can hold the values you were trying to protect.

#Reproduce this yourself

  1. ✅ Generate a key and certificate in the data directory, as the course does:
    bash
    openssl req -x509 -newkey rsa:4096 -nodes -keyout private.pem -out cert.pem -days 30 -subj /CN=localhost
    chown postgres private.pem cert.pem
    chmod 600 private.pem
    
  2. ✅ In postgresql.conf: ssl = on, ssl_cert_file = 'cert.pem', ssl_key_file = 'private.pem', then restart. Check with SELECT ssl, version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid();.
  3. ✅ Change the last host line of pg_hba.conf to hostssl, and SELECT pg_reload_conf();.
  4. ✅ To watch the wire, point a client at a small TCP proxy that logs bytes. I wrote mine with Node's net module. 🎓 The course uses Wireshark, which works too.
  5. ✅ For roles, CREATE ROLE, GRANT, then SET ROLE to test each query.
  6. 📘 For the IBM toolkit, see the fhe-toolkit-linux repository. I didn't run it.

#Glossary

TermMeaning
TLSEncryption and server identity for a connection
hostsslA pg_hba.conf entry matching only TLS connections
SCRAMA login exchange proving a password without sending it
Wire protocolThe format of messages between client and server
OP_MSGMongoDB's message format
Least privilegeGiving each role only the rights it needs
SQL injectionInput that becomes part of a query
Parameterised queryQuery text and values sent separately
Encryption at restData encrypted in storage
Homomorphic encryptionComputing on data while it stays encrypted
PaillierAn encryption scheme where multiplying ciphertexts adds the plain values

#Summary

TLS has to be enabled, enforced with hostssl, and verified by clients, and each of those is a separate step. Without it, queries and results are readable on the wire, even though SCRAM protects the password. Least privilege turns an injection from a disaster into a failed query, and getting it right takes testing, because sequences, RETURNING and WHERE all need rights you might not expect. Queries are data too: a huge query text is slow to parse, and an array parameter isn't. Homomorphic encryption closes the last gap, data in use, and works today, at a high cost.

#Concepts at a glance

ConceptIn one lineWhy it matters
ssl = onTLS is availableNot the same as required
hostsslOnly TLS connections matchWhat enforces it
chmod 600Owner-only key filePostgres refuses anything looser
Certificate verificationIs this the right server?Stops an impostor, not only eavesdroppers
SCRAMA proof, not a passwordDefault since Postgres 14
A pool per roleEach route gets minimal rightsLimits an injection's reach
Hidden grantsSequences, RETURNING, WHEREWhy roles need testing
Array parametersSend data as dataFast, and safe from injection
Homomorphic encryptionCompute without decryptingCloses the "in use" gap, at a cost

#Test yourself

You set ssl = on and restart. A client connects without TLS and it works. What's missing?

ssl = on only makes TLS available. To require it, change the entry in pg_hba.conf to hostssl, so that plain connections no longer match any rule.

Someone captures an unencrypted Postgres session using SCRAM. What can they read, and what can't they?

They can read the user, database, queries and results. They can't read the password, since SCRAM only proves knowledge of it. They'd still see enough to do a lot of harm.

A role has INSERT on a table with a serial id, and the insert fails. Why, and what about RETURNING id?

The default value reads a sequence, which needs USAGE on it. RETURNING reads the new row back, so it needs SELECT on the table.

Why does a read-only role help against SQL injection, if parameterised queries already stop it?

Parameters stop injection where they're used. A role limits the damage from any mistake elsewhere: an injected DROP or a read of another table fails, because the role doesn't have the right.

In Paillier, how does a server add two numbers it can't read?

It multiplies their ciphertexts. The scheme is built so that decrypting the product gives the sum, and the server needs no key to multiply.

#Open questions and gaps

  • 🎓 I didn't re-run IBM's fully homomorphic toolkit, so its two-minute figure is the lecture's. The Paillier demo is my own, and only adds.
  • The course's crash at a million ids came from a free hosted server, and my local server survived. I can't say exactly what limit that host hit.
  • 📘 I didn't test verify-full, or MongoDB with TLS and SCRAM: my MongoDB server was local, without TLS.
  • Transparent Data Encryption and disk encryption are described, not run.

#Sources