Testing PostgreSQL Definer Functions for Search Path Shadowing

Testing PostgreSQL Definer Functions for Search Path Shadowing

Testing PostgreSQL Definer Functions for Search Path Shadowing

An application account may be allowed to call a function that returns a balance without being able to read the quota table directly—a common least-privilege design. But if the function runs with its owner’s privileges and resolves table names through a schema writable by the caller, a same-name test table can change the result. Verifying account isolation on a dedicated database server therefore requires checking both “who can call the function” and “what it actually reads when called.”

1. Isolate the Test Environment and Roles

The following experiment applies to PostgreSQL on Debian 12. Use a separate, empty database and an administrator connection, and run the blocks in sequence within a single interactive psql session. The administrator must be able to create roles and switch roles. Role names are shared across the entire database instance, so check that these names are not already in use before proceeding. Do not create deliberately unsafe functions in a production database.

The experiment uses two non-login roles: cv_owner owns the protected data, while cv_reader can only call the function but also owns a writable schema. That schema represents a reporting staging area or a space for application-created objects; it does not imply that production environments must provide such permissions.

\set ON_ERROR_STOP on
BEGIN;
CREATE ROLE cv_owner NOLOGIN;
CREATE ROLE cv_reader NOLOGIN;
CREATE SCHEMA cv_guard AUTHORIZATION cv_owner;
CREATE SCHEMA cv_untrusted AUTHORIZATION cv_reader;
REVOKE ALL ON SCHEMA cv_guard FROM PUBLIC;
GRANT USAGE ON SCHEMA cv_guard TO cv_reader;
COMMIT;

NOLOGIN only prevents direct login. It does not prevent an administrator from switching to the role, nor does it prevent role members from inheriting its privileges. A production review must check login-role memberships rather than treating a role attribute as complete proof of isolation.

SECURITY DEFINER lends the function owner’s execution privileges; it does not make object names inside the function trustworthy. Whenever a writable schema enters the resolution path, check for object-shadowing risks.

2. Reproduce a Same-Name Table Changing the Result

First, act as the owner to create the real quota table and a deliberately flawed function. The table contains a balance of 10. The function references quota without a schema qualifier, and its search path places the caller-writable schema first.

Function creation and revocation of the default execution grant occur in the same transaction, avoiding a brief window of access for all roles after commit. Only the designated role can call the test function, but that restriction does not fix object resolution.

BEGIN;
SET LOCAL ROLE cv_owner;
CREATE TABLE cv_guard.quota (
    account_id integer PRIMARY KEY,
    remaining integer NOT NULL
);
INSERT INTO cv_guard.quota VALUES (1, 10);

CREATE FUNCTION cv_guard.read_quota()
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = cv_untrusted, cv_guard, pg_temp
AS $$
BEGIN
    RETURN (
        SELECT remaining FROM quota WHERE account_id = 1
    );
END;
$$;

REVOKE ALL ON FUNCTION cv_guard.read_quota() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION cv_guard.read_quota() TO cv_reader;
COMMIT;

Next, switch to the caller role, create a same-name table, and allow the function owner to read it. This grant is part of the attack conditions: if the owner cannot read the spoofed table, the call may produce a permission error rather than return spoofed data.

SET ROLE cv_reader;
CREATE TABLE cv_untrusted.quota (
    account_id integer PRIMARY KEY,
    remaining integer NOT NULL
);
INSERT INTO cv_untrusted.quota VALUES (1, 999);
GRANT SELECT ON cv_untrusted.quota TO cv_owner;
SELECT cv_guard.read_quota();
RESET ROLE;

The expected result is 999, not the 10 stored in the real table. Make the first call to the test function only after creating the spoofed table, so that a plan cached by an earlier execution does not interfere with reproduction. This result proves that the returned value depends on an incorrect object-resolution order; it does not mean the real quota table has been modified.

3. Qualify Objects and Fix the Search Path

The fix uses two layers of protection: explicitly reference the application table as cv_guard.quota, and restrict the function’s search path to the system catalog, the trusted schema, and the temporary schema in last place. The caller must not have CREATE privileges on the trusted schema, or the assumption that it is trusted no longer holds.

BEGIN;
SET LOCAL ROLE cv_owner;
CREATE OR REPLACE FUNCTION cv_guard.read_quota()
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, cv_guard, pg_temp
AS $$
BEGIN
    RETURN (
        SELECT remaining
        FROM cv_guard.quota
        WHERE account_id = 1
    );
END;
$$;

REVOKE ALL ON FUNCTION cv_guard.read_quota() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION cv_guard.read_quota() TO cv_reader;
COMMIT;

SET ROLE cv_reader;
SELECT cv_guard.read_quota();
RESET ROLE;

The expected result is now 10. There is no need to delete the spoofed table; keeping it demonstrates that the fix withstands the original attack conditions. Explicitly listing pg_temp last matters: if omitted, the temporary schema may be searched first when resolving relation and type names.

Schema qualification is not automatic protection for dynamic SQL, either. If the function concatenates a caller-supplied table name into a query, separately restrict which objects may be selected. Use parameter binding for values, and do not accept arbitrary SQL fragments as names.

4. Test Both Successful Access and Denial

Inspect the Effective Definition

Checking the deployment script alone is not enough. An administrator should inspect the function properties currently in effect in the database to confirm its owner, privilege-elevation flag, and function-level configuration.

SELECT
    p.oid::regprocedure AS function_name,
    pg_get_userbyid(p.proowner) AS owner_name,
    p.prosecdef,
    p.proconfig,
    p.proacl
FROM pg_proc AS p
JOIN pg_namespace AS n ON n.oid = p.pronamespace
WHERE n.nspname = 'cv_guard'
  AND p.proname = 'read_quota';

prosecdef should be true, the owner should be cv_owner, and the configuration should include the fixed search path. Overloaded functions receive grants separately by argument signature; checking just one record by function name is insufficient.

Verify the Permission Boundaries

SELECT
    has_schema_privilege('cv_reader', 'cv_guard', 'CREATE')
        AS can_create,
    has_table_privilege('cv_reader', 'cv_guard.quota', 'SELECT')
        AS can_read_table,
    has_function_privilege(
        'cv_reader', 'cv_guard.read_quota()', 'EXECUTE'
    ) AS can_call;

The expected results are false, false, and true, in that order. Then, as cv_reader, separately attempt to query the real table directly and create a table in the trusted schema. Both operations should be denied. Do not include these expected-failure statements in an automated script intended to complete successfully: ON_ERROR_STOP will halt subsequent execution. Run RESET ROLE immediately after completing these checks.

Also establish a test connection using a role without function execution privileges and confirm that the call fails. Getting the correct balance through an administrator connection alone does not prove that the application role’s permission boundaries hold.

5. Preserve Evidence and Clean Up Test Objects

The validation record should include, at minimum, the full function definition, its owner, its effective configuration, the three privilege checks, and the return values before and after the fix. Post-deployment verification should reconnect using the actual login role to cover role inheritance and the identity used by the connection pool; do not rely solely on the experimental results obtained with SET ROLE.

BEGIN;
DROP SCHEMA cv_untrusted CASCADE;
DROP SCHEMA cv_guard CASCADE;
DROP ROLE cv_reader;
DROP ROLE cv_owner;
COMMIT;

This cleanup is only for the isolated experiment described here. Confirm object ownership before running it. If the roles have other dependencies, investigate their origin first rather than using bulk revocation commands to forcibly clear production grants.

The final acceptance criteria are: the function reads the real table while the same-name object still exists; the caller cannot read the table directly or modify the trusted schema; and unauthorized roles cannot call the function. Only when all three are demonstrated does the function provide a constrained capability rather than a permission bypass hidden behind a database interface.

Frequently asked questions

Does SECURITY DEFINER automatically provide a safe search path?

No. It changes the identity used for permission checks, not the safety of object resolution. Set the function search_path explicitly and schema-qualify business tables.

Why explicitly put pg_temp last?

When omitted, the temporary schema can be searched first for relation and type names. Listing it after trusted schemas prevents temporary tables from taking precedence over trusted tables.

Does revoking EXECUTE from PUBLIC block explicitly authorized roles?

No. Selected roles can receive EXECUTE separately. They also need USAGE on the function schema, and inherited privileges or other access paths must be checked.

EPYC 7543P Dedicated Server

From $444/month; total due = monthly rate × number of months. No discounts, setup fees, or contracts.

Choose a dedicated server configuration based on workload and budget

Check memory options, disk layout, and sustained bandwidth, then select the operating system and billing term. Plan images and off-site backups separately.