Dev.to Security 🔐 Cybersecurity 👁 0 📖 11 min read

[CVE-2026-116331] Deep Dive - How One SORTOP Handed Over PostgreSQL

On November 12, 2026, the PostgreSQL project released 18.7, 17.12, 16.16, 15.20, and 14.25 together, disclosing CVE-2026-116331. It's a privilege escalation that lets any role that can simply log in — even a near-permiss

[CVE-2026-116331] Deep Dive - How One SORTOP Handed Over PostgreSQL

On November 12, 2026, the PostgreSQL project released 18.7, 17.12, 16.16, 15.20, and 14.25 together, disclosing CVE-2026-116331. It's a privilege escalation that lets any role that can simply log in — even a near-permissionless application account — climb all the way to the OS user running the database server, using nothing but the default TEMPORARY privilege. Security research team Depthfirst published the triggering SQL and the exploitation rationale on November 18. CVSS 3.1 score: 8.8 (High).

This post walks through why one SORTOP option tricks the planner into treating an integer as a pointer.

TL;DR

  • Root cause: when PostgreSQL's planner speeds up a user-defined aggregate that behaves like MIN/MAX with an index scan, it never checks whether the aggregate's input type matches its result type. If they differ, the planner skips the FINALFUNC (the final conversion function) entirely and returns the raw value read from the index — which the caller then interprets as the declared result type. Read an int8 (passed by value) as a text (passed by reference), and an integer bit pattern instantly becomes a memory address.
  • Affected: PostgreSQL 14.0–14.24, 15.0–15.19, 16.0–16.15, 17.0–17.11, 18.0–18.6 (all 64-bit builds)
  • Privilege required: any role that can log in, plus TEMPORARY privilege on a database (granted to PUBLIC by default — effectively every login role)
  • Severity: CVSS 3.1 8.8 (High)
  • CWE: CWE-843 (Type Confusion)
  • Fix: committed November 12, 2026 as 2c03c7c48fb6 (Tom Lane), backported across the 14–18 lines
  • Status: Depthfirst published the trigger SQL and exploitation rationale on Nov 18. No shellcode or full payload has been published, and as of Nov 19 there's no reported in-the-wild exploitation; it's not in the CISA KEV catalog.
Branch Affected versions Fixed in
PostgreSQL 18 18.0 – 18.6 18.7
PostgreSQL 17 17.0 – 17.11 17.12
PostgreSQL 16 16.0 – 16.15 16.16
PostgreSQL 15 15.0 – 15.19 15.20
PostgreSQL 14 (EOL) 14.0 – 14.24 14.25 (the 14 line reached end-of-life as of 2026-11-12)

1. Background: MIN/MAX aggregates and the index shortcut

For SELECT MAX(col) FROM t with a B-tree index on col, PostgreSQL doesn't scan and sort the whole table — it just reads the single last value off the end of the index. In planner code, this optimization is called a MinMaxAggPath.

This shortcut isn't limited to the built-in MIN/MAX. PostgreSQL lets a user-defined aggregate take the same shortcut if it declares a SORTOP option in CREATE AGGREGATE.

CREATE AGGREGATE my_max(int8) (
    SFUNC = int8larger,
    STYPE = int8,
    SORTOP = '>'          -- "this aggregate behaves like MAX"
);

SORTOP = '>' tells the planner: "this aggregate's result equals the last value you'd get by sorting with >, so it's safe to use the index instead of a full scan." For a legitimate aggregate this is true, and naturally the input type and the result type match too (MAX(int8) returns int8).

2. Background: FINALFUNC, and pass-by-value vs. pass-by-reference

A PostgreSQL aggregate has three parts:

  • SFUNC (state transition function): updates a running state, one row at a time
  • STYPE (state type): the type that holds the running state
  • FINALFUNC (final function, optional): converts the final state into the result type

Usually the state type and result type are the same, so no FINALFUNC is needed — but PostgreSQL happily allows a FINALFUNC that converts to a completely different result type. An aggregate that turns an int8 state into text is perfectly valid SQL.

CREATE FUNCTION as_text(int8) RETURNS text AS $$ SELECT $1::text $$ LANGUAGE sql;

CREATE AGGREGATE confused(int8) (
    SFUNC = int8larger,
    STYPE = int8,
    FINALFUNC = as_text,   -- converts state (int8) to result (text)
    SORTOP = '>'           -- but SORTOP is declared too
);

The memory representation matters here. Internally, PostgreSQL values travel around in a generic 8-byte slot called a Datum.

Type Passing convention What's in the Datum
int8 (bigint) Pass-by-value the integer itself
text, bytea, etc. Pass-by-reference a pointer to a struct holding the actual data

An int8's 8 bytes and a pointer's 8 bytes are the same size, and there's no type tag to tell them apart once you're holding the raw Datum. If the caller believes "this is text" and dereferences it, whatever bit pattern is actually in there gets treated as a memory address.

3. The vulnerable code: an unverified promise

Whether a SORTOP-bearing aggregate is eligible for a MinMaxAggPath is decided by fetch_agg_sort_op() in src/backend/optimizer/plan/planagg.c. Here's the pre-patch code, as of REL_18_6:

static Oid
fetch_agg_sort_op(Oid aggfnoid)
{
    HeapTuple   aggTuple;
    Form_pg_aggregate aggform;
    Oid         aggsortop;

    /* fetch aggregate entry from pg_aggregate */
    aggTuple = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(aggfnoid));
    if (!HeapTupleIsValid(aggTuple))
        return InvalidOid;
    aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
    aggsortop = aggform->aggsortop;
    ReleaseSysCache(aggTuple);

    return aggsortop;
}

It just reads aggsortop straight out of the pg_aggregate catalog and returns it. The caller, can_minmax_aggs(), accepts it as soon as the value is simply valid:

aggsortop = fetch_agg_sort_op(aggref->aggfnoid);
if (!OidIsValid(aggsortop))
    return false;       /* not a MIN/MAX-style aggregate */
/* otherwise, build a MinMaxAggInfo and register it as a MinMaxAggPath candidate */

Nowhere does this compare pg_proc.prorettype (the aggregate's declared result type) against the input argument type. The idea that SORTOP implies "input type equals result type" was only ever a convention — never enforced in code.

So when the planner encounters something like confused(int8) ... FINALFUNC = as_text ... SORTOP = '>' from Section 2, it will:

  1. Fetch a single extreme value from the index instead of scanning the whole table
  2. Never call FINALFUNC (as_text) — it uses the raw int8 read from the index as the result
  3. Pass that Datum back to the executor, which knows the aggregate returns text and dereferences it as a pointer

Reading a literal int8 value of 1 as a pointer dereferences address 0x1 and normally just crashes. But the attacker can put any 64-bit value (any address) they want into that integer slot — and going the other direction, writing a pointer out as an integer leaks a raw memory address. This is a textbook CWE-843 type confusion.

Diagram 1 walkthrough

  1. ① Normal vs. dangerous aggregate: the top-left code box shows an ordinary MIN/MAX-style setup where input, state, and result are all int8. The red text below is the exploit pattern: input is int8, but FINALFUNC converts to text.
  2. ② SORTOP's promise: SORTOP = '>' signals "this aggregate behaves like MAX and returns the same type as its input," which is exactly what lets the planner swap a full scan for an index lookup. The problem is fetch_agg_sort_op() never checks that this promise actually holds.
  3. ③ The missing check: the red line in the code box is exactly where "compare input type vs. result type" should be and isn't. can_minmax_aggs() builds a MinMaxAggPath as soon as aggsortop is merely valid.
  4. ④ Type confusion: the blue box (int8, passed by value) and red box (text, passed by reference) side by side show the fundamentally different passing conventions. The executor always dereferences a result declared text as a pointer, so even an ordinary integer gets treated as a memory address.
  5. ⑤ What the attacker does: an 8-step reconstruction based on Depthfirst's Nov 18 disclosure. Repeating int8 ↔ text and int8 ↔ bytea gives both read and write primitives, ultimately hijacking a function call via a forged expanded-object header to reach system(). Actual shellcode and payload constants were not published.

4. What it takes to attack: why "anyone" qualifies

What makes this vulnerability especially severe is how little privilege the attacker needs.

  • Login privilege: an ordinary application account is enough.
  • TEMPORARY privilege: PostgreSQL grants TEMPORARY privilege on a database to PUBLIC by default. Unless an administrator has specifically revoked it, every login role already has it.
  • Creating objects in pg_temp: with TEMPORARY privilege, a role can freely create tables, indexes, functions, and aggregates in its own temporary schema (pg_temp). That's everything the attack needs.

In other words, the attacker can complete the entire trigger inside their own session's temporary schema, without touching anyone else's data or server configuration.

CREATE TEMP TABLE t (v int8);
CREATE INDEX ON t (v);
INSERT INTO t VALUES (1);

CREATE FUNCTION pg_temp.keep_max(int8, int8) RETURNS int8 ...;
CREATE FUNCTION pg_temp.as_text(int8) RETURNS text ...;

CREATE AGGREGATE pg_temp.confused(int8) (
  SFUNC = pg_temp.keep_max,
  STYPE = int8,
  FINALFUNC = pg_temp.as_text,
  SORTOP = '>'
);

SELECT pg_temp.confused(v) FROM t;

Running this takes the index path and returns the raw int8 — skipping FINALFUNC — as if it were text. Repeating the same pattern with bytea↔int8 gives both "read a pointer as a number" and "write a number as a pointer," which leads to heap address leaks and arbitrary-address dereferences. Depthfirst describes using these primitives to locate code pointers in the postgres binary in heap memory (defeating ASLR), then planting a forged expanded-object header to hijack an indirect call — through the internal method table used by common functions like length() — eventually reaching system(). Function bodies and payload constants were not disclosed in the original writeup either.

5. The fix: add a type comparison to fetch_agg_sort_op()

The fix is to actually verify the promise in code. Right before returning, fetch_agg_sort_op() now looks up the function's real signature in pg_proc and compares the argument type against the return type.

@@ -511,5 +511,22 @@ fetch_agg_sort_op(Oid aggfnoid)
    aggsortop = aggform->aggsortop;
    ReleaseSysCache(aggTuple);

+   /*
+    * Check the aggregate's pg_proc entry to verify input type = result type;
+    * if not, report that there is no sortop.  This guards against incorrect
+    * usage of the SORTOP option.
+    */
+   if (OidIsValid(aggsortop))
+   {
+       Oid         rettype;
+       Oid        *argtypes;
+       int         nargs;
+
+       rettype = get_func_signature(aggfnoid, &argtypes, &nargs);
+       if (nargs != 1 || rettype != argtypes[0])
+           aggsortop = InvalidOid;
+       pfree(argtypes);
+   }
+
    return aggsortop;
 }

If there isn't exactly one argument, or the return type doesn't match that argument's type, aggsortop gets reset to InvalidOid. Then can_minmax_aggs() concludes "this isn't a MIN/MAX-style aggregate" and never builds a MinMaxAggPath — the aggregate runs through the normal SFUNC → FINALFUNC path instead. Existing aggregates with mismatched input/output types keep working, but they no longer take the dangerous index shortcut.

The master (future 19) branch goes a step further and rejects a type-mismatched SORTOP declaration outright at CREATE AGGREGATE time. The currently-released branches (14–18) take the more conservative route of blocking it only at planning time, since a production database might already have such an aggregate installed.

Diagram 2 walkthrough

  1. ① Attack flow: starting from any login role with TEMPORARY privilege, the chain runs through creating a pg_temp table and index, a type-mismatched aggregate, MinMaxAggPath selection, skipping FINALFUNC, dereferencing as text (type confusion), and finally heap leak / ASLR bypass / system() execution — seven steps, all inside the attacker's own temporary schema.
  2. ② Exposure conditions: privilege (login + TEMPORARY), the ability to create objects in a temp schema, an unpatched version, and a 64-bit build — all four must hold. Unlike CPU-feature-dependent bugs, this one doesn't care whether you're on x86-64 or ARM64.
  3. ③ The patch: fetch_agg_sort_op() now looks up the pg_proc signature and compares argument type to return type. A mismatch invalidates aggsortop, making can_minmax_aggs() return false. The master branch rejects it at creation time; release branches only block it at planning time to avoid breaking aggregates that already exist.
  4. ④ Response: patching is the priority. If that's not immediate, REVOKE TEMPORARY ON DATABASE ... FROM PUBLIC; removes the privilege the published attack chain depends on (though it's only a partial mitigation — roles with CREATE privilege, or superusers, can still do it). Detection means searching pg_stat_statements or query logs for SORTOP, CREATE AGGREGATE, and pg_temp. patterns.

6. Checking your exposure

Check the version

SELECT version();

Anything below the fixed version in the table above is affected.

Find login roles with TEMPORARY privilege

This privilege is granted per database, so run this against every database the server hosts.

SELECT r.rolname
FROM pg_roles r
WHERE r.rolcanlogin
  AND has_database_privilege(r.oid, current_database(), 'TEMPORARY');

Every role in the result can create everything the published attack chain needs (temp table, index, function, aggregate).

Find aggregates that are already dangerous

SELECT n.nspname, p.proname,
       format_type(p.prorettype, NULL) AS result_type,
       format_type(p.proargtypes[0], NULL) AS input_type
FROM pg_aggregate a
JOIN pg_proc p ON p.oid = a.aggfnoid
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE a.aggsortop <> 0
  AND p.pronargs = 1
  AND p.prorettype <> p.proargtypes[0];

Any rows returned mean an aggregate with SORTOP declared and mismatched input/output types is already installed. On a patched server the planner won't exploit it anymore, but it's a configuration that should never have existed, and it's worth investigating how it got there.

7. Mitigation

Patch (priority)

Install method Action
Debian/Ubuntu sudo apt update && sudo apt install --only-upgrade postgresql-18 (swap in your branch number)
RHEL/Fedora, PostgreSQL community packages sudo dnf update postgresql-server postgresql or the version-specific package (e.g. postgresql18-server)
Containers docker pull postgres:18.7 and recreate the container (pulling the image alone doesn't apply it)
Managed services (RDS, Aurora, Neon, Supabase, Cloud SQL, Azure Database for PostgreSQL, etc.) Apply the provider's released minor-version upgrade

After patching, restart the server and confirm with SHOW server_version;.

Stopgap mitigation if you can't patch immediately

REVOKE TEMPORARY ON DATABASE <database> FROM PUBLIC;

This removes the privilege the published attack chain relies on, raising the bar for a low-privilege attacker. It is not a full fix: any role with CREATE privilege on a schema can still build tables and aggregates, and superusers can do anything regardless. The underlying planner bug remains until you patch, so treat this revocation purely as risk reduction while you schedule the upgrade.

Detection

  • If query logging is on, search logs for temp-object and SORTOP aggregate creation:
  grep -Ei "create (temp|temporary) table|create aggregate|sortop|pg_temp\." /var/log/postgresql/postgresql-*.log
  • If pg_stat_statements is installed, search the same patterns via query:
  SELECT query
  FROM pg_stat_statements
  WHERE query ILIKE '%CREATE AGGREGATE%'
     OR query ILIKE '%SORTOP%'
     OR query ILIKE '%pg_temp.%';
  • Run the "find aggregates that are already dangerous" query above periodically across every database. Even once the planner stops exploiting it, it's a configuration that shouldn't exist in the first place.
  • Check the postgres service account for unexpected child processes, new files under /tmp, or suspicious outbound connections around the time of flagged queries.

A default PostgreSQL install doesn't log every query, so an absence of evidence in the logs is not evidence that nothing happened.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.