This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Security and Compliance

Authentication, authorization, encryption, audit, and compliance baseline for database and infrastructure security.

Pigsty’s security goals are the CIA triad:

  • Confidentiality: prevent unauthorized access and leakage
  • Integrity: prevent tampering or silent corruption
  • Availability: prevent outages from failures

Pigsty’s security philosophy:

  • Secure by default: out-of-the-box baseline with minimal config and broad coverage.
  • Defense in depth: layered protections so one breach does not collapse the system.
  • Least privilege: roles and privileges enforce least-privilege by default.
  • Compliance-ready: security capabilities plus process can meet audits.

Default Security Baseline (What Problems It Solves)

Security OptionDefaultProblems Solved
Password encryptionpg_pwd_enc: scram-sha-256Prevent weak hashes and plaintext leakage
Data checksumspg_checksum: trueDetect silent data corruption
HBA layeringAdmin from internet must use sslPrevent plaintext access from the public network
Local CAca_create: trueUnified certificate trust chain
Backup & recoverypgbackrest_enabled: truePrevent data loss from mistakes
Nginx HTTPSnginx_sslmode: enablePrevent plaintext web ingress
MinIO HTTPSminio_https: truePrevent backup traffic snooping
OS baselineSELinux permissiveBaseline for enforcing mode

Defaults prioritize usability and scalability. Production should be hardened to meet compliance needs.


Hardening Roadmap

Pigsty provides the security hardening template conf/ha/safe.yml, which upgrades the baseline to a higher security level:

  • Enforce SSL and certificate auth
  • Password strength and expiration policies
  • Connection and disconnection logs
  • Firewall and SELinux hardening

This Chapter

SectionDescriptionCore Question
Defense in DepthSeven-layer security model and baselineHow does the security system land end to end?
AuthenticationHBA rules, password policy, certificate authHow do we verify identities?
Access ControlRole system, permission model, database isolationHow do we control privileges?
Encrypted CommunicationTLS, local CA, certificate managementHow do we protect transport and certs?
Data SecurityChecksums, backup, encryption, recoveryHow do we keep data intact and recoverable?
Compliance ChecklistMLPS Level 3 and SOC2 mappingHow do we meet compliance requirements?

1 - Seven-Layer Security Model

Pigsty defense-in-depth model with layered security baselines from physical to user.

Security is not a wall, but a city. Pigsty adopts a defense-in-depth strategy and builds multiple protections across seven layers. Even if one layer is breached, other layers still protect the system.

This layered approach addresses three core risks:

  • Perimeter breach: reduce the chance that one breach compromises everything.
  • Internal abuse: even if an internal account is compromised, least privilege limits damage.
  • Unpredictable failures: hardware, software, and human errors all get multi-layer fallbacks.

Overview


L1 Physical and Media Security

When the physical layer falls, the only defense is the data itself.

Problems solved

  • Silent data corruption from hardware faults
  • Data leakage from stolen media

Pigsty support

  • Data checksums: default pg_checksum: true, detects corruption from bad blocks/memory errors.
  • Optional transparent encryption: pg_tde and similar extensions encrypt data at rest.

L2 Network Security

Control who can reach services to reduce attack surface.

Problems solved

  • Unauthorized network access
  • Plaintext traffic sniffing/tampering

Pigsty support

  • Firewall zones: node_firewall_mode can enable zone, trust intranet, restrict public.
  • Listen hardening: pg_listen limits bind addresses to avoid full exposure.
  • TLS: HBA supports ssl/cert for encryption and identity checks.

L3 Perimeter Security

A unified ingress is the basis for audit, control, and blocking.

Problems solved

  • Multiple entry points are hard to manage
  • External systems lack a unified hardening point

Pigsty support

  • HAProxy ingress: unified DB traffic entry for blocking/limiting/failover.
  • Nginx gateway: unified HTTPS ingress for infrastructure services (nginx_sslmode).
  • Centralized credentials: HAProxy and Grafana admin passwords are declared in config.

L4 Host Security

The foundation of DB security: least privilege, isolation, and hardening.

Problems solved

  • Host compromise leads to total loss
  • Admin privileges spread too widely

Pigsty support

  • SELinux mode: node_selinux_mode can switch to enforcing.
  • Least-privilege admin: node_admin_sudo supports limit to restrict sudo commands.
  • Sensitive file permissions: CA private key directory 0700, private key files 0600.

L5 Application Security

Authentication is the first gate for DB security.

Problems solved

  • Weak passwords or plaintext auth leak accounts
  • Misconfigured rules allow privilege escalation

Pigsty support

  • HBA layering: rules by source and role; internet admin must use ssl.
  • SCRAM password hash: pg_pwd_enc: scram-sha-256 by default.
  • Password strength checks: passwordcheck/credcheck optional.
  • Certificate auth: auth: cert supports client certs.

L6 Data Security

Ensure data is available, recoverable, and accountable.

Problems solved

  • Human errors and logic mistakes
  • Data tampering or deletion after intrusion

Pigsty support

  • pgBackRest backup: enabled by default, local and MinIO repos.
  • Backup encryption: MinIO supports AES-256-CBC (cipher_type).
  • PITR recovery: restore to any time point with WAL archive.
  • Audit logs: templates enable DDL/connection/slow query logs, optional pgaudit.

L7 User Security

Least privilege is not a slogan, it is default behavior.

Problems solved

  • Business accounts have excessive permissions
  • Databases can “pierce” each other

Pigsty support

  • Four-tier RBAC: dbrole_readonly/readwrite/admin/offline.
  • Default privileges: objects automatically get correct grants.
  • Database isolation: revokeconn: true blocks cross-DB access.
  • Public privilege tightening: revoke CREATE on public schema.

Security Hardening Path

Pigsty provides a security hardening template: conf/ha/safe.yml. It bundles common hardening items:

  • Enforce SSL and certificate auth
  • Password strength and expiration policies
  • Connection and disconnection logs
  • Firewall and SELinux hardening

This path is a quick upgrade from default to compliance-ready.


Next

2 - Authentication

HBA rules, password policy, and certificate auth - who can connect and how to prove identity.

Authentication answers three core questions:

  • Who you are: is the identity unique and recognizable?
  • How you prove it: are passwords/certs strong enough?
  • Where you come from: is the source controlled?

Pigsty uses HBA rules + password/certificates for authentication, with SCRAM as the default password hash.


Authentication Flow

flowchart LR
  C[Client] --> HBA[HBA Rules]
  HBA --> A1[Password SCRAM]
  HBA --> A2[Certificate Auth]
  HBA --> A3[Local ident/peer]
  A1 --> RBAC[Roles and Privileges]
  A2 --> RBAC
  A3 --> RBAC

HBA decides “who can come from where”, and the auth method decides “how identity is proven”.


HBA Layering Model

Pigsty default HBA rules are layered:

  • Local uses ident/peer, the safest.
  • Intranet uses scram password auth.
  • Internet admin must use ssl.

This solves “same user, different auth strength by source”.

Key capabilities of HBA rules

  • Order first: supports order sorting, smaller number means higher priority.
  • Address aliases: local / localhost / intra / world, etc.
  • Role conditions: primary/replica/offline for fine-grained control.

Password Authentication

Default password hash:

pg_pwd_enc: scram-sha-256

Problems solved

  • Plaintext password storage risk
  • Weak hashes cracked offline

Compatibility

For legacy clients you can use md5, but security is reduced.


Password Strength and Rotation

Pigsty can enable password strength checking extensions:

pg_libs: '$libdir/passwordcheck, pg_stat_statements, auto_explain'
pg_extensions: [ passwordcheck, credcheck ]

Use expire_in to control account expiry:

pg_users:
  - { name: dbuser_app, password: 'StrongPwd', expire_in: 365 }

Problems solved

  • Weak or reused passwords
  • Long-lived accounts without rotation

Certificate Authentication

Certificates mitigate the risk of “password phishing or copying”.

  • HBA auth: cert requires client certs.
  • Certificate CN usually matches the database username.
  • Pigsty ships cert.yml to issue client certificates.

PgBouncer Authentication

PgBouncer uses separate HBA rules and TLS settings:

pgbouncer_sslmode: disable   # default off, set to require/verify-full
pgb_default_hba_rules: [...] # separate rules

This solves the problem of “pool entry and database entry being out of sync”.


Default Accounts and Risks

UserDefault PasswordRisk
dbuser_dbaDBUser.DBAadmin account default password
dbuser_monitorDBUser.Monitormonitor account can be abused
replicatorDBUser.Replicatorreplication account abuse can leak data

Default passwords must be changed in production.


Security Recommendations

  • Use ssl/cert on all public entry points.
  • Use scram for intranet users, avoid md5.
  • Enable passwordcheck to enforce complexity.
  • Rotate passwords regularly (expire_in).

Next

3 - Access Control

Pigsty provides an out-of-the-box role and privilege model that enforces least privilege.

Access control answers two core questions:

  • What you can do: boundaries for read/write/DDL
  • What data you can access: isolation across databases and schemas

Pigsty enforces least privilege with RBAC roles + default privileges.


Four-Tier Role Model

flowchart TB
    subgraph Admin["dbrole_admin (Admin)"]
        A1["Can run DDL / CREATE / ALTER"]
        A2["Inherits dbrole_readwrite"]
    end
    subgraph RW["dbrole_readwrite (Read-Write)"]
        RW1["Can INSERT/UPDATE/DELETE"]
        RW2["Inherits dbrole_readonly"]
    end
    subgraph RO["dbrole_readonly (Read-Only)"]
        RO1["Can SELECT all tables"]
    end
    subgraph Offline["dbrole_offline (Offline)"]
        OFF1["Only for offline instances"]
    end

    Admin --> RW --> RO

Problems solved

  • Production accounts have excessive permissions
  • DDL and DML are not separated, increasing risk

Default Roles and System Users

Pigsty provides four roles and four system users (from default source values):

Role/UserAttributesInherits/RolesDescription
dbrole_readonlyNOLOGIN-global read-only access
dbrole_offlineNOLOGIN-restricted read-only (offline instances)
dbrole_readwriteNOLOGINdbrole_readonlyglobal read-write access
dbrole_adminNOLOGINpg_monitor, dbrole_readwriteadmin / object creation
postgresSUPERUSER-system superuser
replicatorREPLICATIONpg_monitor, dbrole_readonlyreplication user
dbuser_dbaSUPERUSERdbrole_adminadmin user
dbuser_monitor-pg_monitor, dbrole_readonlymonitor user

This default role set covers most use cases.


Default Privilege Policy

Pigsty writes default privileges (pg_default_privileges) during initialization so new objects automatically get reasonable permissions.

Problems solved

  • New objects lack grants and apps fail
  • Accidental grants to PUBLIC expose the whole DB

Approach

  • Read-only role: SELECT/EXECUTE
  • Read-write role: INSERT/UPDATE/DELETE
  • Admin role: DDL privileges

Object Ownership and DDL Convention

Default privileges only apply to objects created by admin roles.

That means:

  • Run DDL as dbuser_dba / postgres
  • Or business admins SET ROLE dbrole_admin before DDL

Otherwise, new objects fall outside the default privilege system and break least privilege.


Database Isolation

Database-level isolation uses revokeconn:

pg_databases:
  - { name: appdb, owner: dbuser_app, revokeconn: true }

Problems solved

  • One account can “pierce” all databases
  • Multi-tenant DBs lack boundaries

Public Privilege Tightening

Pigsty revokes CREATE on the public schema during init:

REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Problems solved

  • Unauthorized users create objects
  • “Shadow tables/functions” security risks

Offline Role Usage

dbrole_offline can only access offline instances (pg_role=offline or pg_offline_query=true).

Problems solved

  • ETL/analysis affects production performance
  • Personal accounts run risky queries on primary

Best Practices

  • Use dbrole_readwrite or dbrole_readonly for business accounts.
  • Run production DDL via admin roles.
  • Enable revokeconn for multi-tenant isolation.
  • Use dbrole_offline for reporting/ETL.

Next

4 - Encrypted Communication and Local CA

Pigsty includes a self-signed CA to issue TLS certificates and encrypt network traffic.

Encrypted communication solves three problems:

  • Eavesdropping: prevent plaintext traffic sniffing
  • Tampering: prevent MITM modification
  • Impersonation: prevent fake servers/clients

Pigsty uses a local CA + TLS to provide a unified trust root for databases and infrastructure components.


Role of the Local CA

Pigsty generates a self-signed CA on the admin node by default:

files/pki/ca/ca.key   # CA private key (must be protected)
files/pki/ca/ca.crt   # CA root certificate (distributable)

Default values in source:

  • ca_create: true: auto-generate if CA not found.
  • ca_cn: pigsty-ca: CA certificate CN fixed to pigsty-ca.
  • Root cert validity about 100 years (self-signed).
  • Server/client cert validity cert_validity: 7300d (20 years).

Certificate Coverage

The local CA issues certs for multiple components with a unified trust chain:

ComponentPurposeTypical Path
PostgreSQL / PgBouncerconnection encryption/pg/cert/
PatroniAPI communication/pg/cert/
etcdDCS encryption/etc/etcd/
MinIOobject storage HTTPS~minio/.minio/certs/
Nginxweb ingress HTTPS/etc/nginx/conf.d/cert/

Problem solved: different components issuing their own certs create fragmented trust; a unified CA enables one distribution, many uses.


Trust Distribution

Pigsty distributes ca.crt to all nodes and adds it to system trust:

  • Cert path: /etc/pki/ca.crt
  • EL family: /etc/pki/ca-trust/source/anchors/
  • Debian/Ubuntu: /usr/local/share/ca-certificates/

This allows system clients to trust Pigsty-issued certificates automatically.


Using an External CA

If you already have an enterprise CA, replace:

files/pki/ca/ca.key
files/pki/ca/ca.crt

Recommended:

ca_create: false

Problem solved: prevents accidental generation of a new self-signed CA and trust chain confusion.


Client Certificate Authentication

Certificate auth can replace or enhance password auth:

  • Avoid password phishing or leakage
  • Certificates can bind device and account

Pigsty ships cert.yml to issue client certificates:

./cert.yml -e cn=dbuser_dba
./cert.yml -e cn=dbuser_monitor

Generated by default at:

files/pki/misc/<cn>.key
files/pki/misc/<cn>.crt

Key Protection and Rotation

  • CA private key is 0600 by default and stored in a 0700 directory.
  • If the CA private key leaks, regenerate the CA and re-issue all certs.
  • Rotate certificates after major upgrades or key incidents.

Next

5 - Data Security

Data integrity, backup and recovery, encryption and audit.

Data security focuses on three things: integrity, recoverability, confidentiality. Pigsty enables key capabilities by default and supports further hardening.


Data Integrity

Problems solved

  • Silent corruption from bad disks or memory errors
  • Accidental writes causing data pollution

Pigsty support

  • Data checksums: default pg_checksum: true, enables data-checksums at init.
  • Replica fallback: recover bad blocks from replicas (with HA).

Recoverability (Backup and PITR)

Problems solved

  • Accidental deletion or modification
  • Disaster-level data loss

Pigsty support

  • pgBackRest enabled by default: pgbackrest_enabled: true.
  • Local repository: keeps 2 full backups by default.
  • Remote repository: MinIO support, object storage and multi-replica.
  • PITR: recover to any point in time with WAL archive.

Data Confidentiality

Problems solved

  • Backup theft leading to data leakage
  • Media theft leaking plaintext data

Pigsty support

  • Backup encryption: MinIO repo supports AES-256-CBC (cipher_type).
  • Transparent encryption (optional): pg_tde and similar extensions for at-rest encryption.
  • Key isolation: keep cipher_pass separate from CA private keys.

Audit and Traceability

Problems solved

  • No accountability or audit trail
  • Compliance audits lack evidence

Pigsty support

  • Log collection: templates enable logging_collector by default.
  • DDL audit: log_statement: ddl.
  • Slow queries: log_min_duration_statement.
  • Connection logs: log_connections (PG18+).
  • Audit extensions: pgaudit, pgauditlogtofile optional.

Hardening Recommendations

  • Enforce encryption and dedicated keys for remote backups.
  • Drill PITR regularly and verify the recovery chain.
  • Enable pgaudit for critical workloads.
  • Pair with High Availability for “backup + replica” double safety.

Next

6 - Compliance Checklist

Map Pigsty security capabilities and evidence preparation using SOC2 and MLPS Level 3.

Compliance is not a switch, but a combination of configuration + process + evidence:

  • Configuration: are security capabilities enabled (HBA/TLS/audit/backup)?
  • Process: access management, change control, backup drills
  • Evidence: logs, config snapshots, backup reports, monitoring alerts

This page uses SOC2 and MLPS Level 3 as entry points to map Pigsty’s security capabilities and compliance evidence.


Default Credentials Checklist (Must Change)

From source defaults:

ComponentDefault UsernameDefault Password
PostgreSQL Admindbuser_dbaDBUser.DBA
PostgreSQL Monitordbuser_monitorDBUser.Monitor
PostgreSQL ReplicationreplicatorDBUser.Replicator
Patroni APIpostgresPatroni.API
HAProxy Adminadminpigsty
Grafana Adminadminpigsty
MinIO RootminioadminS3User.MinIO
etcd RootrootEtcd.Root

Must change all defaults in production.


Evidence TypeDescriptionPigsty Support
Config snapshotsHBA, roles, TLS, backup policypigsty.yml / inventory config
Access controlroles and privilegespg_default_roles / pg_default_privileges
Connection auditconnect/disconnect/DDLlog_connections / log_statement
Backup reportsfull backup and restore recordspgBackRest logs and jobs
Monitoring alertsabnormal eventsPrometheus + Grafana
Certificate managementCA/cert distribution recordsfiles/pki/ / /etc/pki/ca.crt

SOC2 Perspective (Example Mapping)

SOC2 focuses on security, availability, confidentiality. Below is a conceptual mapping of common controls:

Control (SOC2)ProblemPigsty CapabilityProcess Needed
CC6 Logical access controlUnauthorized accessHBA + RBAC + default privilegesAccess approval and periodic audit
CC6 Auth strengthWeak/reused passwordsSCRAM + passwordcheckPassword rotation policy
CC6 Transport encryptionPlaintext transportTLS/CA, ssl/certEnforced TLS policy
CC7 MonitoringIncidents unnoticedPrometheus/GrafanaAlert handling process
CC7 Audit trailNo accountabilityconnection/DDL/slow query logs, pgauditLog retention and review
CC9 Business continuityData not recoverablepgBackRest + PITRRegular recovery drills

This is a conceptual mapping. SOC2 requires organizational policies and audit evidence.


MLPS Level 3 (GB/T 22239-2019) Mapping

MLPS Level 3 focuses on identity, access control, audit, data security, communication security, host security, and network boundary. Below is a mapping of key controls:

ControlProblemPigsty CapabilityConfig/Process Needed
Identity uniquenessShared accountsUnique users + SCRAMAccount management process
Password complexityWeak passwordspasswordcheck/credcheckEnable extensions
Password rotationLong-term riskexpire_inRotation policy
Access controlPrivilege abuseRBAC + default privilegesAccess approvals
Least privilegePrivilege sprawlFour-tier role modelAccount tiering
Transport confidentialityPlaintext leakageTLS/CA, HBA ssl/certEnforce TLS
Security auditNo accountabilityconnection/DDL/slow query logs + pgauditLog retention
Data integritySilent corruptionpg_checksum: true-
Backup and recoveryData losspgBackRest + PITRDrills and acceptance
Host securityHost compromiseSELinux/firewallHardening policy
Boundary securityExposed entryHAProxy/Nginx unified ingressNetwork segmentation
Security management systemLack of process-Policies and approvals

Tip: MLPS Level 3 is not only technical; it requires strong operations processes.


Compliance Hardening Snippets

# Enforce SSL / certificates
pg_hba_rules:
  - { user: '+dbrole_readonly', db: all, addr: intra, auth: ssl }
  - { user: dbuser_dba, db: all, addr: world, auth: cert }

# Password strength
pg_libs: '$libdir/passwordcheck, pg_stat_statements, auto_explain'
pg_extensions: [ passwordcheck, credcheck ]

# PgBouncer / Patroni TLS
pgbouncer_sslmode: require
patroni_ssl_enabled: true

# OS security
node_firewall_mode: zone
node_selinux_mode: enforcing

Compliance Checklist

Before Deployment

  • Network segmentation and trusted CIDRs defined
  • Certificate policy decided (self-signed / enterprise CA)
  • Account and privilege tiering plan confirmed

After Deployment (Must)

  • Change all default passwords
  • Verify HBA rules meet expectations
  • Enable and verify TLS
  • Configure audit and log retention policies

Periodic Maintenance

  • Permission audit and account cleanup
  • Certificate rotation
  • Backup and recovery drills

Next