Skip to content

Commit e1456ea

Browse files
committed
add pg security 101,201,301
1 parent b7be262 commit e1456ea

File tree

3 files changed

+457
-3
lines changed

3 files changed

+457
-3
lines changed

advocacy_docs/security/securing-postgresql/101/index.mdx

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,138 @@ navTitle: Security 101
44
description: The essentials of PostgreSQL security for those new to securing their database.
55
---
66

7-
TBD
7+
The following are basic practices for securing your PostgreSQL installation.
8+
9+
## Install the latest version
10+
11+
- **Always use the most recent version.** Regularly update PostgreSQL to the latest stable release. For EDB releases, see the [EDB repositories](https://www.enterprisedb.com/repos-downloads).
12+
13+
- **Apply security patches.** Ensure security patches are applied promptly. For EDB security vulnerabilities and advisories, see the [EDB Vulnerability disclosure policy](https://www.enterprisedb.com/docs/security/vulnerability-disclosure-policy/).
14+
15+
## Use strong authentication methods
16+
17+
PostgreSQL supports several authentication methods. Always use the most secure option available.
18+
19+
- **Password authentication.** Ensure that all users authenticate with strong passwords. Because it provides stronger hashing, use `scram-sha-256` for password hashing instead of `md5`.
20+
21+
- **LDAP/Kerberos/SSO.** Integrate centralized authentication systems like LDAP, Kerberos, or single sign-on (SSO) for enhanced security.
22+
23+
## Limit access with pg_hba.conf
24+
25+
PostgreSQL’s host-based access control file (`pg_hba.conf`) is your first line of defense for controlling who can connect to the database. To ensure security:
26+
27+
- **Restrict host connections.** Allow only trusted hosts.
28+
29+
- **Use CIDR notation.** Limit access to specific IP ranges in `pg_hba.conf`. Example:
30+
31+
```bash
32+
host all all 192.168.1.0/24 scram-sha-256
33+
```
34+
- **Use local method.** For connections from the same machine, use Unix domain sockets with peer authentication, limiting connections to system users.
35+
36+
## Enforce SSL/TLS connections
37+
38+
Encrypt traffic between the client and PostgreSQL server using SSL. This practice can prevent sensitive data (like passwords and query results) from being intercepted.
39+
40+
- **Enable SSL.** Ensure that `ssl = on` in `postgresql.conf`.
41+
42+
- **Use valid SSL certificates.** Use certificates for secure communication (self-signed or CA-signed).
43+
44+
- **Force SSL.** Ensure all connections use SSL via `pg_hba.conf`. Example:
45+
46+
```bash
47+
hostssl all all 0.0.0.0/0 scram-sha-256
48+
```
49+
50+
## Use role-based access control (RBAC)
51+
52+
PostgreSQL implements a robust role-based access control system. Some key practices include:
53+
54+
- **Principle of least privilege.** Grant roles the minimum permissions necessary.
55+
56+
- **Separate roles for users/applications.** Avoid using superuser accounts or the default postgres role for daily operations.
57+
58+
- **Use GRANT/REVOKE.** Assign specific privileges to roles. Example:
59+
60+
```sql
61+
GRANT SELECT, INSERT ON my_table TO my_user;
62+
```
63+
64+
## Use encrypted passwords
65+
66+
Make sure that passwords are stored using secure hashing methods (scram-sha-256 in modern PostgreSQL versions).
67+
68+
- **Enable scram-sha-256.** Configure PostgreSQL to store passwords securely by setting `password_encryption = 'scram-sha-256'` in your `postgresql.conf` file:
69+
70+
```bash
71+
password_encryption = 'scram-sha-256'
72+
```
73+
74+
## Audit and monitor database activity
75+
76+
Enable logging and auditing to keep track of database activity.
77+
78+
- **Enable logging.** Log all user connections and queries.
79+
80+
- **Track role changes.** Regularly audit role modifications and permissions to detect unauthorized changes.
81+
82+
- **Use pgAudit.** Third-party tools like pgAudit can enable detailed audit logging.
83+
84+
- **Enable connection and query logs.** Capture login attempts, successful connections, and queries executed using settings in `postgresql.conf`:
85+
86+
```bash
87+
log_connections = on
88+
log_disconnections = on
89+
log_statement = 'all'
90+
```
91+
92+
## Regular backups and secure backup storage
93+
94+
Backups are crucial, but they must also be secured. Be sure to:
95+
96+
- **Use encrypted backups.** Encrypt database backups to reduce the chance of unauthorized access.
97+
98+
- **Restrict backup access.** Allow only authorized personnel to access, view, or restore backups.
99+
100+
- **Test restores.** Regularly test backups to ensure they're complete and can be restored properly without any data integrity issues.
101+
102+
## Disable unnecessary features
103+
104+
Reduce your attack surface by disabling unused features:
105+
106+
- **Remove unused extensions.** Disable any extensions that aren't actively used.
107+
108+
- **Disable trust authentication.** Ensure `trust` authentication isn't used in production as it allows users to log in without a password.
109+
110+
- **Disable untrusted languages.** Prevent the use of languages that allow arbitrary code execution, such as PL/Python.
111+
112+
## Vulnerability scanning and penetration testing
113+
114+
- **Regularly scan for vulnerabilities.** Use security scanners to find vulnerabilities.
115+
116+
- **Penetration resting.** Test the security of your PostgreSQL instance. You may need to hire security professionals to test your database security periodically.
117+
118+
## Network security controls
119+
120+
Strengthen PostgreSQL’s security by securing the network it operates in.
121+
122+
- **Set firewall rules.** Restrict database access to necessary ports.
123+
124+
- **Limit network exposure.** Use VPNs or internal networks for database access. Avoid exposing PostgreSQL directly to the internet.
125+
126+
- **Use intrusion detection.** Use IDS tools to monitor for suspicious activity.
127+
128+
## Regularly review user permissions
129+
130+
- **Develop a review cadence.** Regularly review user and role permissions to ensure no unnecessary privileges were granted.
131+
132+
- **Remove unnecessary privileges.** Periodically review and revoke unnecessary privileges. Remove access immediately when a user no longer needs it.
133+
134+
## Secure OS and file permissions
135+
136+
PostgreSQL runs on an operating system that also needs to be secured.
137+
138+
- **Restrict file access.** Ensure that only the PostgreSQL service user can access critical files such as the data directory and logs. Set restrictive permissions (700) on the data directory.
139+
140+
- **Harden the OS.** Apply operating system hardening practices, including disabling unnecessary services and ensuring regular OS updates.
141+

advocacy_docs/security/securing-postgresql/201/index.mdx

Lines changed: 160 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,163 @@ navTitle: Security 201
44
description: Building on the basics, this guide covers more advanced topics in PostgreSQL security.
55
---
66

7-
TBD
7+
After you've mastered the basics of securing your PostgreSQL database, you can dive deeper into intermediate topics.
8+
9+
These intermediate security techniques help to further safeguard your data, improve auditability, and reduce risks associated with more sophisticated attacks. By focusing on enhanced role management, encryption, fine-grained access control, auditing, and cloud-specific configurations, you can build a robust defense for your databases.
10+
11+
Keep evolving your security posture by staying updated on emerging threats and security features in new PostgreSQL releases.
12+
13+
## Advanced role management and privileges
14+
15+
Effective management of roles and privileges is essential for maintaining a secure PostgreSQL environment.
16+
17+
- **Avoid using superuser roles.** Limit superuser privileges to only the most essential operations. Always create distinct, minimally privileged roles for day-to-day database tasks.
18+
19+
- **Create custom roles.** Create task-specific roles for finer privilege management. Rather than using a single, all-encompassing role, create custom roles for different functions like read-only, read-write, and admin tasks. This practice limits the scope of potential security breaches. For example:
20+
21+
```sql
22+
CREATE ROLE read_only NOINHERIT;
23+
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only;
24+
```
25+
26+
- **Establish role inheritance.** Use role inheritance to streamline privilege assignments and create hierarchies of roles that simplify privilege management. A parent role can be granted a specific set of privileges, which can then be inherited by child roles:
27+
28+
```sql
29+
CREATE ROLE base_role;
30+
CREATE ROLE admin_role INHERIT base_role;
31+
```
32+
33+
- **Revoke public privileges.** Remove default permissions from the public role. By default, new databases and tables grant certain privileges to the public role. Best practice is to revoke these:
34+
35+
```sql
36+
REVOKE ALL ON DATABASE mydb FROM PUBLIC;
37+
REVOKE ALL ON SCHEMA public FROM PUBLIC;
38+
```
39+
40+
## Fine-grained access control with row-level security
41+
42+
- **Enable row-level security.** Row-level security (RLS) provides fine-grained control over who can access specific rows in a table. This type of security is essential when different users need access to different subsets of data.
43+
44+
Enforce RLS policies on sensitive tables. To activate RLS for a table, you first need to enable it:
45+
46+
```sql
47+
ALTER TABLE employees ENABLE ROW LEVEL SECURITY;
48+
```
49+
50+
- **Define security policies.** Once RLS is enabled, you can create policies to specify which users can access or modify rows in the table. For example:
51+
52+
```sql
53+
CREATE POLICY employee_policy ON employees
54+
FOR SELECT
55+
USING (employee_id = current_user);
56+
```
57+
58+
### Database encryption
59+
60+
Encryption is critical for protecting data at rest and in transit. Intermediate PostgreSQL setups often leverage encryption to secure sensitive information.
61+
62+
- **Encrypt sensitive columns.** Use pgcrypto to encrypt sensitive data at the column level. While PostgreSQL doesn’t natively support column-level encryption,
63+
you can use client-side encryption libraries such as pgcrypto to encrypt and decrypt data. For example:
64+
65+
```sql
66+
SELECT pgp_sym_encrypt('secret data', 'encryption key');
67+
```
68+
Ensure that encryption keys are stored securely outside the database, such as in AWS KMS, HashiCorp Vault, or other secure key management systems.
69+
70+
- **Use full disk encryption.** If column-level encryption isn't feasible, use full-disk encryption to secure the data directory. Encrypting the entire disk ensures that sensitive data is protected in the event of unauthorized physical access to the database server.
71+
72+
## pg_hba.conf advanced configurations
73+
74+
The `pg_hba.conf` file controls access to PostgreSQL at the network level. Intermediate configurations involve more complex filtering and control mechanisms.
75+
76+
- **Set granular network restrictions.** Configure specific IP ranges or hosts for different roles. Define access based on user, database, or IP address to create fine-grained network policies. For example, restrict administrative access to a specific IP range:
77+
78+
```bash
79+
host all postgres 10.0.0.0/8 scram-sha-256
80+
```
81+
82+
- **Separate roles by network.** Allow different roles based on their origin IP. You can create roles that have different levels of access based on their network of origin. For instance, you can create read-only users on a public network and read-write users on a private network:
83+
84+
```bash
85+
host all read_only_user 0.0.0.0/0 scram-sha-256
86+
host all read_write_user 10.0.0.0/8 scram-sha-256
87+
```
88+
89+
## Database auditing and logging
90+
91+
Auditing is essential for identifying abnormal behavior and unauthorized access. It also helps in compliance with security standards like PCI-DSS and GDPR.
92+
93+
- **Enable pgaudit.** Use pgaudit for detailed logging of database activity. This extension provides detailed logging of SQL statements at various levels (DDL, DML, and more). To install and configure it:
94+
95+
```sql
96+
CREATE EXTENSION pgaudit;
97+
```
98+
99+
To configure pgaudit to log SELECT statements:
100+
101+
```bash
102+
pgaudit.log = 'read'
103+
```
104+
105+
- **Configure fine-grained logging.** Customize logging configurations to capture DDL, DML, and more. PostgreSQL offers several levels of logging, but for performance reasons, fine-tune it.
106+
Enable specific logging for failed login attempts or DDL changes:
107+
108+
```bash
109+
log_connections = on
110+
log_disconnections = on
111+
log_statement = 'ddl'
112+
```
113+
114+
For more information on pgAudit, see the [pgAudit documentation](https://www.pgaudit.org).
115+
116+
## Monitoring and alerting
117+
118+
Intermediate PostgreSQL security requires robust monitoring and alerting. Several tools and configurations can help with this:
119+
120+
- **PostgreSQL monitoring tools.** Tools like pg_stat_statements, pgBadger, or third-party tools such as Prometheus and Grafana, provide insights into database activity and performance metrics.
121+
122+
- **CloudWatch for AWS Aurora.** For AWS Aurora PostgreSQL users, leverage CloudWatch to monitor database performance metrics and set up alarms for unusual patterns in CPU, memory, or I/O usage.
123+
124+
- **Alerts for suspicious activity.** Configure alerts for specific actions and abnormal behaviors, such as multiple failed login attempts, database role changes, or connections from unknown IP addresses. For example:
125+
126+
```bash
127+
log_min_error_statement = 'ERROR'
128+
log_min_duration_statement = 1000
129+
```
130+
131+
## Database hardening
132+
133+
Hardening your PostgreSQL server is an intermediate security practice that reduces the attack surface by removing or disabling unnecessary features.
134+
135+
- **Remove unused extensions.** Extensions can increase the attack surface of PostgreSQL. Disable or remove any extensions you don't actively use. For example:
136+
137+
```sql
138+
DROP EXTENSION IF EXISTS plperl;
139+
```
140+
141+
- **Lock down data directory.** Ensure that the PostgreSQL data directory is accessible only by the PostgreSQL user. Use file system permissions (chmod 700) to lock down access:
142+
143+
```bash
144+
chmod 700 /var/lib/postgresql/data
145+
```
146+
147+
## Securing PostgreSQL on cloud providers
148+
149+
Cloud environments introduce additional layers of complexity. The following can help secure your PostgreSQL instances in the cloud:
150+
151+
- **AWS RDS encryption.** Use AWS RDS's built-in encryption for data at rest with KMS-managed keys. You can easily enable it while creating an RDS instance.
152+
153+
- **Network access restrictions.** Use cloud-level security groups or firewalls to restrict access to the PostgreSQL instance. Allow only trusted IPs or VPCs to connect to the database.
154+
155+
- **IAM authentication.** Use AWS IAM roles and policies to manage access to PostgreSQL instances. IAM authentication provides an extra layer of security, reducing the need for password management:
156+
157+
```bash
158+
aws rds generate-db-auth-token --hostname <endpoint> --port 5432 --region <region> --username <db-user>
159+
```
160+
161+
## Implementing multi-factor authentication (MFA)
162+
163+
Using MFA for database access further secures your system by requiring users to provide a second factor beyond a password. You can integrate PostgreSQL with an external identity provider (IdP) that supports MFA.
164+
165+
- **External identity providers.** For added security, integrate MFA with identity providers such as Okta, Google Identity, Azure AD, or AWS IAM.
166+

0 commit comments

Comments
 (0)