Security & Access Control

The database is usually where an organization's most valuable data ends up, which makes it the most valuable target. Database security rests on four questions: who are you (authentication), what may you do (authorization), what did you do (auditing), and how are the keys protected (secrets handling). Examples use PostgreSQL; every major engine offers equivalent controls. For host and network hardening, see the TechOps lesson Security Hardening.

Know the Threats

Most database breaches do not involve exotic exploits. They come from a database reachable from the internet, a shared superuser password found in a repository, an application vulnerable to SQL injection, or a backup copied somewhere unprotected. Defend in layers, so that one failure does not expose everything.

Reduce the Attack Surface

  • Never expose the database port to the public internet. Place it on a private network and reach it through the application, a VPN or a bastion host.
  • Restrict which addresses may connect at the network level and again in the database's own client rules.
  • Remove unused extensions, sample databases and default accounts; keep the engine patched to a supported minor version.
  • Encrypt connections with TLS and verify the server certificate, so credentials and data are not readable on the network.

Authentication

Authentication proves the identity of whoever connects. Every person and every application should have its own identity, so access can be granted, audited and revoked individually.

Client Authentication Rules

PostgreSQL decides how each connection must authenticate from pg_hba.conf, read top to bottom; the first matching line wins. Require TLS for remote connections and use scram-sha-256, the default password method since PostgreSQL 14. Never use trust outside a disposable local sandbox.

# TYPE    DATABASE  USER       ADDRESS          METHOD
local     all       postgres                    peer            # OS user must match
hostssl   shop      app_shop   10.0.20.0/24     scram-sha-256   # app servers, TLS only
hostssl   all       +dba       10.0.99.0/24     scram-sha-256   # members of role "dba"
host      all       all        0.0.0.0/0        reject          # everything else

On the client side, connect with sslmode=verify-full, which checks both the certificate chain and that the host name matches; weaker modes encrypt traffic but can still be intercepted by an impostor server.

Use Central Identities Where Possible

For people, prefer the organization's identity provider over database-local passwords: PostgreSQL supports LDAP, Kerberos/GSSAPI and certificate authentication, and managed cloud databases offer IAM-based, short-lived tokens. When someone leaves, disabling one central account then removes their database access too.

Authorization

Authorization decides what an authenticated identity may do. The guiding rule is least privilege: grant each identity only what its job requires, and nothing by default.

Roles and Privileges

In PostgreSQL, users and groups are both roles. Grant privileges to group roles that describe a job, then grant those roles to login roles. Applications should never connect as the table owner or as a superuser:

-- Group roles describe access levels; they cannot log in.
CREATE ROLE shop_read  NOLOGIN;
CREATE ROLE shop_write NOLOGIN;

GRANT USAGE ON SCHEMA sales TO shop_read, shop_write;
GRANT SELECT ON ALL TABLES IN SCHEMA sales TO shop_read;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA sales TO shop_write;

-- Tables created later by the migration owner get the same grants automatically.
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA sales
    GRANT SELECT ON TABLES TO shop_read;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA sales
    GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_write;

-- Login roles: one per application or person.
CREATE ROLE app_shop LOGIN IN ROLE shop_write;
CREATE ROLE report_bot LOGIN IN ROLE shop_read CONNECTION LIMIT 5;

Separate three kinds of identity: an owner role used only by migrations, application roles with DML rights, and human roles that are read-only by default and elevated temporarily when a change is approved. Since PostgreSQL 15, ordinary users can no longer create objects in the public schema by default; on older versions, run REVOKE CREATE ON SCHEMA public FROM PUBLIC.

Row-Level Security

Sometimes privileges must depend on the row, not just the table — for example, a multi-tenant application where each tenant may see only its own orders. Row-level security (RLS) adds a filter the database applies to every query:

ALTER TABLE sales.customer_order ENABLE ROW LEVEL SECURITY;

-- Each session declares its tenant; the policy filters every read and write.
CREATE POLICY tenant_isolation ON sales.customer_order
    USING      (tenant_id = current_setting('app.tenant_id')::bigint)
    WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);

-- In the application, at the start of each transaction:
-- SET LOCAL app.tenant_id = '42';

Table owners and superusers bypass RLS unless the table also has FORCE ROW LEVEL SECURITY, so test policies while connected as the application role. Oracle offers comparable features as Virtual Private Database.

Prevent SQL Injection

SQL injection happens when user input is concatenated into SQL text, letting an attacker change the statement itself. The fix is not escaping; it is parameters: send the SQL and the values separately, so values can never be parsed as code.

# Vulnerable: input such as "1 OR 1=1" changes the query's meaning.
cur.execute(f"SELECT * FROM sales.customer WHERE id = {user_input}")

# Safe: the driver sends the value separately as a bound parameter (psycopg).
cur.execute("SELECT * FROM sales.customer WHERE id = %s", (user_input,))

Least privilege limits the damage when injection slips through: an application role without DROP or access to other schemas cannot be used to drop tables or read unrelated data.

Auditing

An audit trail answers who did what, when, from where. It is required by many regulations and is indispensable after an incident. Logs that are never reviewed are only half the control: decide which events trigger an alert.

Log Connections and Changes

# postgresql.conf: a practical baseline
log_connections    = on
log_disconnections = on
log_statement      = 'ddl'                   # every schema change, with its author
log_line_prefix    = '%m [%p] %q%u@%d %r '   # time, pid, user@database, client address

Avoid log_statement = 'all' in production: it is expensive and writes sensitive values into log files. For detailed, structured audit records — for example, all reads of a table holding personal data — use the pgAudit extension, and ship the logs to a separate system that database administrators cannot alter.

Review Privileges Regularly

Privileges accumulate. Schedule a periodic review of who can log in and who holds powerful attributes:

-- Roles that can log in, with their dangerous attributes and group memberships.
SELECT r.rolname,
       r.rolsuper, r.rolcreaterole, r.rolcreatedb, r.rolbypassrls,
       r.rolvaliduntil,
       array(SELECT g.rolname
               FROM pg_auth_members m
               JOIN pg_roles g ON g.oid = m.roleid
              WHERE m.member = r.oid) AS member_of
  FROM pg_roles r
 WHERE r.rolcanlogin
 ORDER BY r.rolsuper DESC, r.rolname;

Secrets Handling

A database is only as secure as the place where its passwords are kept. Credentials committed to a repository are routinely found by automated scanners within minutes of a push.

Store and Inject Credentials

  • Keep credentials in a secret manager (HashiCorp Vault, a cloud provider's secrets service, or the orchestrator's secret store) and inject them into the application at runtime through environment variables or mounted files.
  • Never put passwords in source code, container images, connection strings in logs, or tickets. For personal command-line use, PostgreSQL clients read a ~/.pgpass file that must be readable only by its owner.
  • Prefer short-lived, automatically issued credentials (for example, Vault's database secrets engine or cloud IAM tokens) over long-lived static passwords.

Rotate Credentials and Encrypt Data

Rotate credentials on a schedule and immediately when exposure is suspected. Support two valid passwords or two roles during a rotation so the application can switch without downtime. Protect data at rest with disk or tablespace encryption, and remember that backups contain the same data as the live database: encrypt them and restrict who can read them, as described in Backup & Recovery.

Practice Lab

Use a local PostgreSQL instance where you control pg_hba.conf.

Build a Least-Privilege Role Model

  1. Create an owner role, a read-only group, a read-write group, one application login and one analyst login.
  2. Connect as each login and prove what it can and cannot do: the analyst cannot update, the application cannot drop a table.
  3. Create a new table as the owner and confirm that default privileges gave both groups the expected access.

Test Your Defenses

  1. Enable row-level security on a two-tenant table and prove that the application role sees only one tenant's rows.
  2. Write a deliberately vulnerable query function, exploit it with an injected condition, then fix it with parameters.
  3. Turn on connection and DDL logging, perform a schema change, and find the log line that identifies who made it.