Sub topic 8
How SCRAM-SHA-256 works
This chapter explains what happens on the wire and inside the server when a client authenticates with scram-sha-256. It assumes you know how pg_hba.conf rules select a method, how password_encryption controls what is stored in pg_authid, and what a hash function and an HMAC are at a basic level.
Why SCRAM exists
Password authentication has two weaknesses to avoid. The first is that the password, or something equivalent to it, crosses the network. The second is that anyone who steals the stored password data can log in with it.
- With
password, the clear-text password is sent to the server. Only TLS protects it. - With
md5, the client sends a hash derived from the stored hash. The stored MD5 value is itself enough to log in, so a stolenpg_authidrow is a usable credential. MD5 is also fast to brute-force. - With SCRAM-SHA-256, the password is never sent. The server stores values that can check a proof but cannot create one. The hashing is deliberately slow, using a salt and many iterations.
SCRAM stands for Salted Challenge Response Authentication Mechanism. PostgreSQL implements it as defined in RFC 5802 and RFC 7677, carried inside the SASL framework of the PostgreSQL protocol.
What the server stores
When you set a password with password_encryption = 'scram-sha-256', PostgreSQL stores a verifier in pg_authid.rolpassword:
SCRAM-SHA-256$<iterations>:<salt>$<StoredKey>:<ServerKey>The fields are:
| Field | Meaning |
|---|---|
| iterations | PBKDF2 iteration count. The default is 4096. From PostgreSQL 16 the `scram_iterations` setting controls it. |
| salt | Random per-password value, base64 encoded. |
| StoredKey | SHA-256 of the ClientKey. Used to verify the client. |
| ServerKey | HMAC of the salted password with the label `Server Key`. Used to prove the server's identity to the client. |
You can inspect the non-secret parts as a superuser:
SELECT rolname,
split_part(rolpassword, '$', 1) AS scheme,
split_part(split_part(rolpassword, '$', 2), ':', 1) AS iterations
FROM pg_authid
WHERE rolname = 'app_user';The password itself is not recoverable from the verifier. Neither is the ClientKey, because StoredKey is a one-way hash of it. That is why a leaked verifier cannot be replayed as a client login. The attacker still has to guess the password offline, and each guess costs the full iteration count.
The key derivation
Both sides derive the same keys from the password. Only the client ever has the password during a login. The server holds the results.
SaltedPassword = PBKDF2-HMAC-SHA-256(password, salt, iterations)ClientKey = HMAC(SaltedPassword, "Client Key")StoredKey = SHA-256(ClientKey)ServerKey = HMAC(SaltedPassword, "Server Key")
Before hashing, PostgreSQL normalizes the password with SASLprep (RFC 4013) when the password is valid UTF-8. If it is not valid UTF-8, the raw bytes are used. This matters for passwords with non-ASCII characters typed on different platforms.
The message exchange
After the startup packet and the pg_hba.conf match, the server asks for SASL authentication and lists the mechanisms it offers. These are SCRAM-SHA-256, and also SCRAM-SHA-256-PLUS when the connection uses TLS. The client then exchanges four messages.
The proof is built from an AuthMessage, which is the three message parts joined by commas: the client-first message without its gs2 header, the server-first message, and the client-final message without the proof. Using it binds the proof to this one exchange.
ClientSignature = HMAC(StoredKey, AuthMessage)ClientProof = ClientKey XOR ClientSignature
The server cannot compute ClientKey, but it does not need to. It computes ClientSignature itself from StoredKey and AuthMessage, XORs it with the received proof to recover a candidate ClientKey, then checks that SHA-256(candidate) == StoredKey. If the check passes, the client knew the password.
For the reverse direction the server sends ServerSignature = HMAC(ServerKey, AuthMessage). The client can compute this because it can derive ServerKey from the password. A server that only has a copy of the password hash from another source, or no password at all, cannot produce it. So SCRAM gives mutual authentication.
PostgreSQL ignores the username in n= and uses the user from the startup packet. Libpq sends it empty. Each side contributes a random nonce, so a recorded exchange cannot be replayed against a new login.
Running the math yourself
This Python script plays both roles using only the standard library. It builds a verifier, runs the exchange in memory, and checks both proofs.
import base64
import hashlib
import hmac
import os
def b64(data: bytes) -> str:
return base64.b64encode(data).decode()
def hmac256(key: bytes, msg: bytes) -> bytes:
return hmac.new(key, msg, hashlib.sha256).digest()
def xor(a: bytes, b: bytes) -> bytes:
return bytes(x ^ y for x, y in zip(a, b))
def derive(password: str, salt: bytes, iterations: int):
salted = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
client_key = hmac256(salted, b"Client Key")
stored_key = hashlib.sha256(client_key).digest()
server_key = hmac256(salted, b"Server Key")
return client_key, stored_key, server_key
# --- Server side: what ALTER ROLE ... PASSWORD would store ---
password = "correct horse battery staple"
salt = os.urandom(16)
iterations = 4096
_, stored_key, server_key = derive(password, salt, iterations)
verifier = (
f"SCRAM-SHA-256${iterations}:{b64(salt)}"
f"${b64(stored_key)}:{b64(server_key)}"
)
print("verifier:", verifier)
# --- The exchange ---
client_nonce = b64(os.urandom(18))
server_nonce = b64(os.urandom(18))
nonce = client_nonce + server_nonce
client_first_bare = f"n=,r={client_nonce}"
server_first = f"r={nonce},s={b64(salt)},i={iterations}"
client_final_no_proof = f"c=biws,r={nonce}" # biws = base64("n,,")
auth_message = ",".join(
[client_first_bare, server_first, client_final_no_proof]
).encode()
# Client: knows only the password plus salt and iterations from server-first
client_key, c_stored, c_server_key = derive(password, salt, iterations)
client_signature = hmac256(c_stored, auth_message)
client_proof = xor(client_key, client_signature)
# Server: knows only StoredKey and ServerKey
recovered_key = xor(client_proof, hmac256(stored_key, auth_message))
print("client accepted:", hashlib.sha256(recovered_key).digest() == stored_key)
server_signature = hmac256(server_key, auth_message)
# Client: checks the server really holds ServerKey
print("server accepted:", hmac256(c_server_key, auth_message) == server_signature)Both lines print True. If you change one character of password on the client side only, the first check prints False, which is how a wrong password is detected.
Channel binding and the -PLUS variant
SCRAM by itself does not stop a man-in-the-middle who relays the exchange between a client and the real server, if the client does not verify the server's TLS certificate. SCRAM-SHA-256-PLUS closes that gap. The c= field in client-final carries data derived from the TLS connection. PostgreSQL uses the tls-server-end-point type, a hash of the server certificate. The server compares it with its own certificate. A relay holding a different certificate produces a mismatch and the proof is rejected.
Libpq controls this with channel_binding set to disable, prefer (the default) or require. Chapter-level details of TLS setup come later. Here, remember that channel binding only exists on TLS connections.
Behaviors and common errors
- A
scram-sha-256rule needs a SCRAM verifier. If the role still has an MD5 hash, the login fails withpassword authentication failed, and the server log says the user "does not have a valid SCRAM secret". The reverse is allowed: anmd5rule accepts a role whose stored password is SCRAM and uses SCRAM instead. - Old clients fail. A driver without SCRAM support, or libpq before version 10, reports
authentication method 10 not supportedorSCRAM authentication requires libpq version 10 or above. Upgrade the driver. Do not weaken the rule. - Unknown roles look like wrong passwords. For a nonexistent role, or one with no password, the server runs a mock exchange and fails at the end. A client cannot use the exchange to learn which roles exist.
- SCRAM does not encrypt the session. An eavesdropper without TLS sees the nonces, salt, iterations and proof. That is enough to attempt an offline guess of a weak password. Use TLS for any network path you do not control.
- The verifier is not a login credential, but it is not harmless. Anyone holding StoredKey and ServerKey can impersonate the server to a client that knows the password, and can guess passwords offline. Protect
pg_authidand backups as sensitive data. - Higher iteration counts cost CPU on both sides. Each login does one PBKDF2 run on the client and none on the server, because the server stores the derived keys. Raising
scram_iterationsslows an attacker's guessing and your clients' logins by the same factor.
Exercises
Exercise
In the SCRAM exchange, which values does the server need in order to verify a client, and why can't an attacker who steals them log in as the client?
Show answer
The server needs StoredKey (and ServerKey for its own signature). The client proves itself by sending ClientProof, which is ClientKey XOR ClientSignature. StoredKey is SHA-256 of ClientKey, so the thief has only the hash and cannot compute ClientKey without reversing SHA-256 or guessing the password. They can still run an offline guessing attack against the verifier, so a strong password and a high iteration count matter.
Exercise
A role's rolpassword starts with md5. The matching pg_hba.conf rule uses scram-sha-256. What happens at login, and what is the minimum fix?
Show answer
The login fails with password authentication failed, and the server log reports that the user has no valid SCRAM secret. The fix is to run SET password_encryption = 'scram-sha-256'; and then set the role's password again, for example with \password app_user in psql. Changing the setting alone does not convert the existing hash.
Exercise
Why does the client-final message include a hash of the earlier messages (the AuthMessage) in its proof, and what attack does that prevent?
Show answer
The proof is computed over the AuthMessage, which contains both nonces and the server's salt and iteration count. A proof captured from one login is therefore valid only for that exchange. Replaying it against a later login fails, because the server uses a new nonce and the AuthMessage differs.