GHSA-2XFQ-2J89-QC8J
SQLChatAgent PostgreSQL description extractor interpolates table names into SQL via f-string
Texto original en inglés · Ver en español
CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-2XFQ-2J89-QC8J divulgada · CVSS 8.8 (GitHub) | |
| Divulgación | Modificada | Última actualización del registro | |
| Remediación | Parche 0.68.8 | langroid · 0 d desde divulgación | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
The `extract_postgresql_descriptions()` function in `langroid/agent/special/sql/utils/description_extractors.py` constructs SQL statements by interpolating raw PostgreSQL table names into f-strings at lines 45 and 56. Table names are read from the database catalog via `inspector.get_table_names()` without sanitization or parameterization. An attacker who can create a table with a single-quote-containing name in the target PostgreSQL database triggers arbitrary SQL execution when `SQLChatAgent.__init__` calls this function during automatic metadata initialization.
Root Cause
The security invariant that all SQL values must be parameterized or properly escaped is violated. The PostgreSQL description extractor builds SQL using Python f-strings with the raw `table_name` variable placed inside a SQL string literal, while the MySQL extractor in the same file correctly uses parameterized queries with bind variables.
# Vulnerable PostgreSQL path (description_extractors.py:45)
text(f"SELECT obj_description('{table_name}'::regclass)")
# Correct MySQL path (description_extractors.py:106-111)
query = text(
"SELECT table_comment FROM information_schema.tables WHERE"
" table_schema = :schema AND table_name = :table"
)
conn.execute(query, {"schema": engine.url.database, "table": table_name})The `_validate_query` security validator at `langroid/agent/special/sql/sql_chat_agent.py:706` protects only the `run_query` tool handler path. The description extraction runs during `__init__` before any LLM interaction and constructs its own SQL independently; no validation, escaping, or parameterization covers this path.
Impact
An attacker requires `CREATE TABLE` privilege on the PostgreSQL database that the SQLChatAgent connects to. This is a standard low privilege: PostgreSQL grants `CREATE` on the `public` schema to the `PUBLIC` role by default in versions prior to 15, and it is routinely available in shared or multi-tenant databases.
When `SQLChatAgent` is initialized against the poisoned database, the injected SQL executes automatically with no user interaction. Demonstrated capabilities include:
- Data exfiltration: UNION-based injection retrieves arbitrary data accessible to the agent's database role (e.g., `SELECT current_user`, `SELECT usename FROM pg_user`).
- Data modification and destruction: With psycopg2 (the default PostgreSQL driver), multi-statement execution via `PQexec` enables `DROP TABLE`, `DELETE`, `UPDATE`, and other DDL/DML operations in a single injection.
- Limited to single-statement injection under psycopg (v3): The newer psycopg driver uses `PQexecParams`, which does not support multi-statement execution. Under psycopg3, only UNION-based exfiltration is achievable.
A second injection point exists at line 56 for `col_description`, with the same impact profile.
Proof of Concept
Dependencies: sqlalchemy, psycopg2-binary (or psycopg[binary])
Database: PostgreSQL 12+ (tested concept against standard catalog behavior)
Config: Set DATABASE_URL to a PostgreSQL connection stringThe following script demonstrates the injection at the source level. When `DATABASE_URL` is set, it creates a table with a malicious name and triggers `extract_postgresql_descriptions()` to execute the injected SQL.
from sqlalchemy import create_engine, text
# 1. Source-level demonstration of the f-string injection
table_name_safe = "test_table"
table_name_evil = "pg_class'::regclass) UNION SELECT usename FROM pg_user--"
query_safe = f"SELECT obj_description('{table_name_safe}'::regclass)"
query_evil = f"SELECT obj_description('{table_name_evil}'::regclass)"
print("Safe query:", query_safe)
# SELECT obj_description('test_table'::regclass)
print("Injected query:", query_evil)
# SELECT obj_description('pg_class'::regclass) UNION SELECT usename FROM pg_user--'::regclass)When executed against a live database, the attacker creates the poisoned table:
CREATE TABLE "pg_class'::regclass) UNION SELECT usename FROM pg_user--" (id int);Then any application initializing `SQLChatAgent` against this database triggers the injection automatically during `__init__` at `sql_chat_agent.py:400`.
Expected output (UNION-based exfiltration):
obj_description | usename
----------------+---------
| postgres
| app_userAttack Chain
- Exposure: The attacker holds `CREATE TABLE` privilege on a PostgreSQL database. The victim application initializes `SQLChatAgent` with a `database_uri` pointing to that database.
- Control: The attacker creates a table whose double-quoted identifier contains a single quote followed by SQL payload. PostgreSQL allows any character in double-quoted identifiers per the SQL standard.
- Path: `SQLChatAgent.__init__` (`sql_chat_agent.py:400`) calls `_init_table_metadata()` (`sql_chat_agent.py:469`), which calls `extract_schema_descriptions()` (`description_extractors.py:188`). The dialect dispatch selects `extract_postgresql_descriptions` when the engine dialect is `postgresql`. Inside that function, `inspector.get_table_names()` (`description_extractors.py:35`) returns the raw catalog name as a Python string.
- Guard: No validation, escaping, or parameterization exists on this path. The `_validate_query` validator protects only the `run_query` tool handler at `sql_chat_agent.py:832` and is never invoked during initialization.
- Primitive: The raw table name is interpolated into `text(f"SELECT obj_description('{table_name}'::regclass)")` at `description_extractors.py:45` and executed via `conn.execute()` at `description_extractors.py:44`. The single quote breaks out of the SQL string literal, enabling arbitrary SQL execution.
- Result: The attacker achieves arbitrary SQL execution within the agent's database connection. This includes data exfiltration via UNION injection and, under psycopg2, data modification or destruction via multi-statement execution.
Bypass Evidence
No security guard exists on the description extraction code path. The `_validate_query` method at `sql_chat_agent.py:706` applies only to the `run_query` tool handler and is not called during `__init__`. A search of `description_extractors.py` for any form of validation, sanitization, escaping, or parameterization on the PostgreSQL path returns zero matches. The MySQL extractor in the same file uses parameterized queries with `:table` and `:schema` bind variables (`description_extractors.py:106-111`), confirming the PostgreSQL f-string is an unintentional gap rather than a deliberate design choice.
Affected Versions
- Ecosystem: `pip`
- Package: `langroid`
- Confirmed affected range: `>= 0.1.48, <= 0.68.2`
- Latest release checked: `0.68.2` (PyPI
https://pypi.org/project/langroid/0.68.2/) - Fix status: not fixed
The vulnerable `extract_postgresql_descriptions` function was introduced in commit `f5171978` ("Added automatic context description extraction for PostgreSQL & MySQL databases", PR #207), first released in version `0.1.48`. No subsequent commits modify the f-string interpolation pattern at lines 45 and 56 of `description_extractors.py`. The pattern is confirmed present in the latest PyPI release (`0.68.2`).
Suggested Fix
Replace the f-string SQL construction in `extract_postgresql_descriptions()` with parameterized queries using SQLAlchemy bind parameters, matching the pattern already used in the MySQL extractor. Both the `obj_description` query at line 45 and the `col_description` query at line 56 must be updated. Because `obj_description` and `col_description` accept a `regclass` argument, the parameterized form should cast the bind parameter: `text("SELECT obj_description(:tbl::regclass)").bindparams(tbl=table_name)`.
As an interim mitigation, application developers can supply a pre-populated `context_descriptions` dict in `SQLChatAgentConfig` to skip automatic extraction. This workaround requires the developer to know all table and column descriptions in advance.
---
Reported by zx.
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 |
|---|---|---|---|---|
pypilangroid |
Corregida | 0.68.8 | 0 d | 0.69.22 no afectada |
0.68.8Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/langroid/langroid/security/advisories/GHSA-2xfq-2j89-qc8jLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
