← Back to CVE Explorer

CVE-2026-12044

Full vulnerability record from the local CVENow database.

Description

SQL injection in pgAdmin 4 across every dialog template that renders ``COMMENT ON ... IS '<description>'`` for a user-supplied description field. The Jinja templates for Domains (and their constraints), Foreign Tables, Languages, and Event Triggers, plus the Views OID-lookup query, interpolated the description directly inside a single-quoted SQL literal -- ``'{{ data.description }}'`` -- instead of passing it through the ``qtLiteral`` escape filter. An authenticated pgAdmin user with permission to create or alter the affected object types could submit a description containing an apostrophe, break out of the literal and chain arbitrary SQL. The injected SQL runs under the PostgreSQL role the user is already authenticated as; for a connected role with ``COPY ... TO/FROM PROGRAM`` (typically PostgreSQL superuser), this chains to OS command execution on the PostgreSQL host. The defect does not cross a privilege boundary -- the user already has direct SQL access to that role through pgAdmin's Query Tool -- so the attacker gains no capability beyond what their database role already grants. The marginal impact captures bypass of any application-layer Query Tool gating an operator may have configured. The defect was originally reported against the Domain Dialog ``description`` field; a code-wide audit identified sixteen sites of the same pattern across the templates listed above. The same review also surfaced ten related sinks in the pgstattuple/pgstatindex stats templates -- ``pgstattuple('{{schema}}.{{table}}')`` and the matching pgstatindex shape -- where ``qtIdent`` escapes embedded double quotes inside the identifier but not apostrophes, so a user with CREATE privilege on a schema could plant a table or index named ``foo'bar`` and a later stats viewer would render an unbalanced literal. Fix is layered: 1. Sites: replace every ``'{{ x.description }}'`` with ``{{ x.description|qtLiteral(conn) }}`` (no surrounding quotes -- the filter wraps the value in escaped quotes itself). Plumb ``conn=self.conn`` through every ``render_template`` call that loads one of these templates. Also corrects a ``{ % elif`` Jinja typo in the foreign-table schema diff (dead branch). Rewrite the ten pgstattuple/pgstatindex stats sites to address the relation via OID + ``::oid::regclass`` cast (e.g. ``pgstattuple({{ tid }}::oid::regclass)``), eliminating the embedded literal-call form entirely so that bug-class can no longer recur there. 2. Driver hardening: ``qtLiteral`` (in ``utils/driver/psycopg3/__init__.py``) used to silently return the raw unescaped value when its ``conn`` argument was falsy. It now raises ``ValueError`` -- surfacing the entire bug class going forward. The change immediately uncovered eight latent plumbing bugs (in ``schemas/__init__.py``, ``schemas/functions/__init__.py``, ``schemas/tables/utils.py``, ``foreign_servers/__init__.py``, and seven sites in ``roles/__init__.py``) -- all fixed as part of this patch. The inner ``except`` block that swallowed adapter-level failures and returned the raw value is also removed, so unadaptable inputs raise instead of leaking unescaped values. 3. Regression tests: a per-template behavioural test renders each previously-vulnerable template with an apostrophe-injection payload and asserts the escaped fragment is present and the vulnerable fragment absent; a lint test walks every ``*.sql`` template flagging any ``'{{ ... }}'`` single-quote-wrapped interpolation against an explicit allowlist; unit tests cover the new qtLiteral fail-fast and inner-except raise paths. This issue affects pgAdmin 4: from 1.0 before 9.16.

Severity
HIGH
CVSS score
8.7 (v4.0)
Vulnerability status
Analyzed
Source identifier
f86ef6dc-4d3a-42ad-8f28-e6d5547a5007
Published
2026-06-19 00:16:46.053000
Last modified
2026-10-26 11:10:00.157000
View original CVE JSON
{
  "id": "CVE-2026-12044",
  "sourceIdentifier": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
  "published": "2026-06-19T00:16:46.053",
  "lastModified": "2026-10-26T11:10:00.157",
  "vulnStatus": "Analyzed",
  "cveTags": [],
  "descriptions": [
    {
      "lang": "en",
      "value": "SQL injection in pgAdmin 4 across every dialog template that renders ``COMMENT ON ... IS '<description>'`` for a user-supplied description field. The Jinja templates for Domains (and their constraints), Foreign Tables, Languages, and Event Triggers, plus the Views OID-lookup query, interpolated the description directly inside a single-quoted SQL literal -- ``'{{ data.description }}'`` -- instead of passing it through the ``qtLiteral`` escape filter. An authenticated pgAdmin user with permission to create or alter the affected object types could submit a description containing an apostrophe, break out of the literal and chain arbitrary SQL. The injected SQL runs under the PostgreSQL role the user is already authenticated as; for a connected role with ``COPY ... TO/FROM PROGRAM`` (typically PostgreSQL superuser), this chains to OS command execution on the PostgreSQL host. The defect does not cross a privilege boundary -- the user already has direct SQL access to that role through pgAdmin's Query Tool -- so the attacker gains no capability beyond what their database role already grants. The marginal impact captures bypass of any application-layer Query Tool gating an operator may have configured.\n\nThe defect was originally reported against the Domain Dialog ``description`` field; a code-wide audit identified sixteen sites of the same pattern across the templates listed above. The same review also surfaced ten related sinks in the pgstattuple/pgstatindex stats templates -- ``pgstattuple('{{schema}}.{{table}}')`` and the matching pgstatindex shape -- where ``qtIdent`` escapes embedded double quotes inside the identifier but not apostrophes, so a user with CREATE privilege on a schema could plant a table or index named ``foo'bar`` and a later stats viewer would render an unbalanced literal.\n\nFix is layered:\n\n  1. Sites: replace every ``'{{ x.description }}'`` with ``{{ x.description|qtLiteral(conn) }}`` (no surrounding quotes -- the filter wraps the value in escaped quotes itself). Plumb ``conn=self.conn`` through every ``render_template`` call that loads one of these templates. Also corrects a ``{ % elif`` Jinja typo in the foreign-table schema diff (dead branch). Rewrite the ten pgstattuple/pgstatindex stats sites to address the relation via OID + ``::oid::regclass`` cast (e.g. ``pgstattuple({{ tid }}::oid::regclass)``), eliminating the embedded literal-call form entirely so that bug-class can no longer recur there.\n\n  2. Driver hardening: ``qtLiteral`` (in ``utils/driver/psycopg3/__init__.py``) used to silently return the raw unescaped value when its ``conn`` argument was falsy. It now raises ``ValueError`` -- surfacing the entire bug class going forward. The change immediately uncovered eight latent plumbing bugs (in ``schemas/__init__.py``, ``schemas/functions/__init__.py``, ``schemas/tables/utils.py``, ``foreign_servers/__init__.py``, and seven sites in ``roles/__init__.py``) -- all fixed as part of this patch. The inner ``except`` block that swallowed adapter-level failures and returned the raw value is also removed, so unadaptable inputs raise instead of leaking unescaped values.\n\n  3. Regression tests: a per-template behavioural test renders each previously-vulnerable template with an apostrophe-injection payload and asserts the escaped fragment is present and the vulnerable fragment absent; a lint test walks every ``*.sql`` template flagging any ``'{{ ... }}'`` single-quote-wrapped interpolation against an explicit allowlist; unit tests cover the new qtLiteral fail-fast and inner-except raise paths.\n\nThis issue affects pgAdmin 4: from 1.0 before 9.16."
    },
    {
      "lang": "es",
      "value": "Inyección SQL en pgAdmin 4 en cada plantilla de diálogo que renderiza “COMMENT ON ... IS ’[description]’” para un campo de descripción proporcionado por el usuario. Las plantillas Jinja para Dominios (y sus restricciones), Tablas Foráneas, Lenguajes y Disparadores de Eventos, además de la consulta de búsqueda de OID de Vistas, interpolaron la descripción directamente dentro de un literal SQL entre comillas simples - “’{{ data.description }}’” - en lugar de pasarla a través del filtro de escape “qtLiteral”. Un usuario autenticado de pgAdmin con permiso para crear o alterar los tipos de objetos afectados podría enviar una descripción que contenga un apóstrofe, salir del literal y encadenar SQL arbitrario. El SQL inyectado se ejecuta bajo el rol de PostgreSQL con el que el usuario ya está autenticado; para un rol conectado con “COPY ... TO/FROM PROGRAM” (típicamente superusuario de PostgreSQL), esto se encadena a la ejecución de comandos del sistema operativo en el host de PostgreSQL. El defecto no cruza un límite de privilegios - el usuario ya tiene acceso SQL directo a ese rol a través de la Herramienta de Consulta de pgAdmin - por lo que el atacante no obtiene ninguna capacidad más allá de lo que su rol de base de datos ya le otorga. El impacto marginal captura la omisión de cualquier control de la Herramienta de Consulta a nivel de aplicación que un operador pueda haber configurado.\n\nEl defecto fue reportado originalmente contra el campo “description” del Diálogo de Dominio; una auditoría de código a nivel general identificó dieciséis sitios del mismo patrón en las plantillas mencionadas anteriormente. La misma revisión también reveló diez sumideros relacionados en las plantillas de estadísticas pgstattuple/pgstatindex - “pgstattuple(’{{schema}}.{{table}}’)” y la forma coincidente de pgstatindex - donde “qtIdent” escapa las comillas dobles incrustadas dentro del identificador pero no los apóstrofes, por lo que un usuario con privilegio CREATE en un esquema podría “plantar” una tabla o índice llamado “foo’bar” y un visor de estadísticas posterior renderizaría un literal desequilibrado.\n\nLa solución está en capas:\n\n1.  Sitios: reemplazar cada “’{{ x.description }}’” con “{{ x.description|qtLiteral(conn) }}” (sin comillas circundantes - el filtro envuelve el valor en comillas escapadas por sí mismo). Conectar “conn=self.conn” a través de cada llamada a “render_template” que carga una de estas plantillas. También corrige un error tipográfico de Jinja “{ % elif” en la diferencia de esquema de tabla foránea (rama muerta). Reescribir los diez sitios de estadísticas pgstattuple/pgstatindex para abordar la relación a través de OID + conversión “::oid::regclass” (p. ej., “pgstattuple({{ tid }}::oid::regclass)”), eliminando por completo la forma de llamada literal incrustada para que esa clase de error ya no pueda repetirse allí.\n\n2.  Reforzamiento del controlador: “qtLiteral” (en “utils/driver/psycopg3/__init__.py”) solía devolver silenciosamente el valor sin escapar en bruto cuando su argumento “conn” era falso. Ahora lanza “ValueError” - sacando a la luz toda la clase de errores en el futuro. El cambio descubrió inmediatamente ocho errores de conexión latentes (en “schemas/__init__.py”, “schemas/functions/__init__.py”, “schemas/tables/utils.py”, “foreign_servers/__init__.py”, y siete sitios en “roles/__init__.py”) - todos corregidos como parte de este parche. También se elimina el bloque “except” interno que “tragaba” los fallos a nivel de adaptador y devolvía el valor en bruto, por lo que las entradas no adaptables lanzan una excepción en lugar de filtrar valores sin escapar.\n\n3.  Pruebas de regresión: una prueba de comportamiento por plantilla renderiza cada plantilla previamente vulnerable con una carga útil de inyección de apóstrofe y afirma que el fragmento escapado está presente y el fragmento vulnerable ausente; una prueba de lint recorre cada plantilla “*.sql” marcando cualquier interpolación “’{{ ... }}’” envuelta en comillas simples contra una lista de permitidos explícita; las pruebas --TRUNCADO--"
    }
  ],
  "affected": [
    {
      "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
      "affectedData": [
        {
          "vendor": "pgadmin.org",
          "product": "pgAdmin 4",
          "defaultStatus": "unaffected",
          "modules": [
            "Domains",
            "Domain Constraints",
            "Foreign Tables",
            "Languages",
            "Event Triggers",
            "Views",
            "Tables",
            "Indexes",
            "Index Constraints",
            "Exclusion Constraints",
            "Materialized Views",
            "Driver (qtLiteral)"
          ],
          "programFiles": [
            "https://github.com/pgadmin-org/pgadmin4/blob/master/web/pgadmin/utils/driver/psycopg3/__init__.py",
            "https://github.com/pgadmin-org/pgadmin4/blob/master/web/pgadmin/browser/server_groups/servers/databases/schemas/domains/templates/domains/sql/default/create.sql",
            "https://github.com/pgadmin-org/pgadmin4/blob/master/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/templates/tables/sql/16_plus/stats.sql"
          ],
          "repo": "https://github.com/pgadmin-org/pgadmin4",
          "versions": [
            {
              "version": "1.0",
              "lessThan": "9.16",
              "versionType": "custom",
              "status": "affected"
            }
          ]
        }
      ]
    }
  ],
  "metrics": {
    "cvssMetricV40": [
      {
        "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
        "type": "Secondary",
        "cvssData": {
          "version": "4.0",
          "vectorString": "CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
          "baseScore": 8.7,
          "baseSeverity": "HIGH",
          "attackVector": "NETWORK",
          "attackComplexity": "LOW",
          "attackRequirements": "NONE",
          "privilegesRequired": "LOW",
          "userInteraction": "NONE",
          "vulnConfidentialityImpact": "HIGH",
          "vulnIntegrityImpact": "HIGH",
          "vulnAvailabilityImpact": "HIGH",
          "subConfidentialityImpact": "NONE",
          "subIntegrityImpact": "NONE",
          "subAvailabilityImpact": "NONE",
          "exploitMaturity": "NOT_DEFINED",
          "confidentialityRequirement": "NOT_DEFINED",
          "integrityRequirement": "NOT_DEFINED",
          "availabilityRequirement": "NOT_DEFINED",
          "modifiedAttackVector": "NOT_DEFINED",
          "modifiedAttackComplexity": "NOT_DEFINED",
          "modifiedAttackRequirements": "NOT_DEFINED",
          "modifiedPrivilegesRequired": "NOT_DEFINED",
          "modifiedUserInteraction": "NOT_DEFINED",
          "modifiedVulnConfidentialityImpact": "NOT_DEFINED",
          "modifiedVulnIntegrityImpact": "NOT_DEFINED",
          "modifiedVulnAvailabilityImpact": "NOT_DEFINED",
          "modifiedSubConfidentialityImpact": "NOT_DEFINED",
          "modifiedSubIntegrityImpact": "NOT_DEFINED",
          "modifiedSubAvailabilityImpact": "NOT_DEFINED",
          "Safety": "NOT_DEFINED",
          "Automatable": "NOT_DEFINED",
          "Recovery": "NOT_DEFINED",
          "valueDensity": "NOT_DEFINED",
          "vulnerabilityResponseEffort": "NOT_DEFINED",
          "providerUrgency": "NOT_DEFINED"
        }
      }
    ],
    "cvssMetricV31": [
      {
        "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
        "type": "Secondary",
        "cvssData": {
          "version": "3.1",
          "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H",
          "baseScore": 8.8,
          "baseSeverity": "HIGH",
          "attackVector": "NETWORK",
          "attackComplexity": "LOW",
          "privilegesRequired": "LOW",
          "userInteraction": "NONE",
          "scope": "UNCHANGED",
          "confidentialityImpact": "HIGH",
          "integrityImpact": "HIGH",
          "availabilityImpact": "HIGH"
        },
        "exploitabilityScore": 2.8,
        "impactScore": 5.9
      }
    ],
    "ssvcV203": [
      {
        "source": "134c704f-9b21-4f2e-91b3-4a467353bcc0",
        "ssvcData": {
          "timestamp": "2026-06-22T18:36:59.059744Z",
          "id": "CVE-2026-12044",
          "options": [
            {
              "exploitation": "none"
            },
            {
              "automatable": "no"
            },
            {
              "technicalImpact": "total"
            }
          ],
          "role": "CISA Coordinator",
          "version": "2.0.3"
        }
      }
    ]
  },
  "weaknesses": [
    {
      "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
      "type": "Secondary",
      "description": [
        {
          "lang": "en",
          "value": "CWE-89"
        },
        {
          "lang": "en",
          "value": "CWE-116"
        }
      ]
    }
  ],
  "configurations": [
    {
      "nodes": [
        {
          "operator": "OR",
          "negate": false,
          "cpeMatch": [
            {
              "vulnerable": true,
              "criteria": "cpe:2.3:a:pgadmin:pgadmin_4:*:*:*:*:*:postgresql:*:*",
              "versionStartIncluding": "1.0",
              "versionEndExcluding": "9.16",
              "matchCriteriaId": "6C00C802-CCFB-4A7B-835E-FBE61FFC87FD"
            }
          ]
        }
      ]
    }
  ],
  "references": [
    {
      "url": "https://github.com/pgadmin-org/pgadmin4/commit/2ae0d3610",
      "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
      "tags": [
        "Patch"
      ]
    },
    {
      "url": "https://github.com/pgadmin-org/pgadmin4/commit/658bb585d",
      "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
      "tags": [
        "Patch"
      ]
    },
    {
      "url": "https://github.com/pgadmin-org/pgadmin4/issues/10078",
      "source": "f86ef6dc-4d3a-42ad-8f28-e6d5547a5007",
      "tags": [
        "Issue Tracking",
        "Patch",
        "Third Party Advisory"
      ]
    }
  ]
}