From e1456ea1da5b513c064859cdbeecb2fbab399af3 Mon Sep 17 00:00:00 2001 From: piano35-edb <160748516+piano35-edb@users.noreply.github.com> Date: Tue, 22 Oct 2024 19:05:04 -0500 Subject: [PATCH] add pg security 101,201,301 --- .../securing-postgresql/101/index.mdx | 136 ++++++++++++++- .../securing-postgresql/201/index.mdx | 161 ++++++++++++++++- .../securing-postgresql/301/index.mdx | 163 +++++++++++++++++- 3 files changed, 457 insertions(+), 3 deletions(-) diff --git a/advocacy_docs/security/securing-postgresql/101/index.mdx b/advocacy_docs/security/securing-postgresql/101/index.mdx index 3d04c501b58..a4890128f08 100644 --- a/advocacy_docs/security/securing-postgresql/101/index.mdx +++ b/advocacy_docs/security/securing-postgresql/101/index.mdx @@ -4,4 +4,138 @@ navTitle: Security 101 description: The essentials of PostgreSQL security for those new to securing their database. --- -TBD +The following are basic practices for securing your PostgreSQL installation. + +## Install the latest version + +- **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). + +- **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/). + +## Use strong authentication methods + +PostgreSQL supports several authentication methods. Always use the most secure option available. + +- **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`. + +- **LDAP/Kerberos/SSO.** Integrate centralized authentication systems like LDAP, Kerberos, or single sign-on (SSO) for enhanced security. + +## Limit access with pg_hba.conf + +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: + +- **Restrict host connections.** Allow only trusted hosts. + +- **Use CIDR notation.** Limit access to specific IP ranges in `pg_hba.conf`. Example: + +```bash +host all all 192.168.1.0/24 scram-sha-256 +``` +- **Use local method.** For connections from the same machine, use Unix domain sockets with peer authentication, limiting connections to system users. + +## Enforce SSL/TLS connections + +Encrypt traffic between the client and PostgreSQL server using SSL. This practice can prevent sensitive data (like passwords and query results) from being intercepted. + +- **Enable SSL.** Ensure that `ssl = on` in `postgresql.conf`. + +- **Use valid SSL certificates.** Use certificates for secure communication (self-signed or CA-signed). + +- **Force SSL.** Ensure all connections use SSL via `pg_hba.conf`. Example: + +```bash +hostssl all all 0.0.0.0/0 scram-sha-256 +``` + +## Use role-based access control (RBAC) + +PostgreSQL implements a robust role-based access control system. Some key practices include: + +- **Principle of least privilege.** Grant roles the minimum permissions necessary. + +- **Separate roles for users/applications.** Avoid using superuser accounts or the default postgres role for daily operations. + +- **Use GRANT/REVOKE.** Assign specific privileges to roles. Example: + +```sql +GRANT SELECT, INSERT ON my_table TO my_user; +``` + +## Use encrypted passwords + +Make sure that passwords are stored using secure hashing methods (scram-sha-256 in modern PostgreSQL versions). + +- **Enable scram-sha-256.** Configure PostgreSQL to store passwords securely by setting `password_encryption = 'scram-sha-256'` in your `postgresql.conf` file: + +```bash +password_encryption = 'scram-sha-256' +``` + +## Audit and monitor database activity + +Enable logging and auditing to keep track of database activity. + +- **Enable logging.** Log all user connections and queries. + +- **Track role changes.** Regularly audit role modifications and permissions to detect unauthorized changes. + +- **Use pgAudit.** Third-party tools like pgAudit can enable detailed audit logging. + +- **Enable connection and query logs.** Capture login attempts, successful connections, and queries executed using settings in `postgresql.conf`: + +```bash +log_connections = on +log_disconnections = on +log_statement = 'all' +``` + +## Regular backups and secure backup storage + +Backups are crucial, but they must also be secured. Be sure to: + +- **Use encrypted backups.** Encrypt database backups to reduce the chance of unauthorized access. + +- **Restrict backup access.** Allow only authorized personnel to access, view, or restore backups. + +- **Test restores.** Regularly test backups to ensure they're complete and can be restored properly without any data integrity issues. + +## Disable unnecessary features + +Reduce your attack surface by disabling unused features: + +- **Remove unused extensions.** Disable any extensions that aren't actively used. + +- **Disable trust authentication.** Ensure `trust` authentication isn't used in production as it allows users to log in without a password. + +- **Disable untrusted languages.** Prevent the use of languages that allow arbitrary code execution, such as PL/Python. + +## Vulnerability scanning and penetration testing + +- **Regularly scan for vulnerabilities.** Use security scanners to find vulnerabilities. + +- **Penetration resting.** Test the security of your PostgreSQL instance. You may need to hire security professionals to test your database security periodically. + +## Network security controls + +Strengthen PostgreSQL’s security by securing the network it operates in. + +- **Set firewall rules.** Restrict database access to necessary ports. + +- **Limit network exposure.** Use VPNs or internal networks for database access. Avoid exposing PostgreSQL directly to the internet. + +- **Use intrusion detection.** Use IDS tools to monitor for suspicious activity. + +## Regularly review user permissions + +- **Develop a review cadence.** Regularly review user and role permissions to ensure no unnecessary privileges were granted. + +- **Remove unnecessary privileges.** Periodically review and revoke unnecessary privileges. Remove access immediately when a user no longer needs it. + +## Secure OS and file permissions + +PostgreSQL runs on an operating system that also needs to be secured. + +- **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. + +- **Harden the OS.** Apply operating system hardening practices, including disabling unnecessary services and ensuring regular OS updates. + diff --git a/advocacy_docs/security/securing-postgresql/201/index.mdx b/advocacy_docs/security/securing-postgresql/201/index.mdx index 75856a51c16..623341ac2dd 100644 --- a/advocacy_docs/security/securing-postgresql/201/index.mdx +++ b/advocacy_docs/security/securing-postgresql/201/index.mdx @@ -4,4 +4,163 @@ navTitle: Security 201 description: Building on the basics, this guide covers more advanced topics in PostgreSQL security. --- -TBD +After you've mastered the basics of securing your PostgreSQL database, you can dive deeper into intermediate topics. + +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. + +Keep evolving your security posture by staying updated on emerging threats and security features in new PostgreSQL releases. + +## Advanced role management and privileges + +Effective management of roles and privileges is essential for maintaining a secure PostgreSQL environment. + +- **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. + +- **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: + +```sql +CREATE ROLE read_only NOINHERIT; +GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only; +``` + +- **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: + +```sql +CREATE ROLE base_role; +CREATE ROLE admin_role INHERIT base_role; +``` + +- **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: + +```sql +REVOKE ALL ON DATABASE mydb FROM PUBLIC; +REVOKE ALL ON SCHEMA public FROM PUBLIC; +``` + +## Fine-grained access control with row-level security + +- **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. + + Enforce RLS policies on sensitive tables. To activate RLS for a table, you first need to enable it: + +```sql +ALTER TABLE employees ENABLE ROW LEVEL SECURITY; +``` + +- **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: + +```sql +CREATE POLICY employee_policy ON employees +FOR SELECT +USING (employee_id = current_user); +``` + +### Database encryption + +Encryption is critical for protecting data at rest and in transit. Intermediate PostgreSQL setups often leverage encryption to secure sensitive information. + +- **Encrypt sensitive columns.** Use pgcrypto to encrypt sensitive data at the column level. While PostgreSQL doesn’t natively support column-level encryption, +you can use client-side encryption libraries such as pgcrypto to encrypt and decrypt data. For example: + +```sql +SELECT pgp_sym_encrypt('secret data', 'encryption key'); +``` + Ensure that encryption keys are stored securely outside the database, such as in AWS KMS, HashiCorp Vault, or other secure key management systems. + +- **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. + +## pg_hba.conf advanced configurations + +The `pg_hba.conf` file controls access to PostgreSQL at the network level. Intermediate configurations involve more complex filtering and control mechanisms. + +- **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: + +```bash +host all postgres 10.0.0.0/8 scram-sha-256 +``` + +- **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: + +```bash +host all read_only_user 0.0.0.0/0 scram-sha-256 +host all read_write_user 10.0.0.0/8 scram-sha-256 +``` + +## Database auditing and logging + +Auditing is essential for identifying abnormal behavior and unauthorized access. It also helps in compliance with security standards like PCI-DSS and GDPR. + +- **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: + +```sql +CREATE EXTENSION pgaudit; +``` + + To configure pgaudit to log SELECT statements: + +```bash +pgaudit.log = 'read' +``` + +- **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. +Enable specific logging for failed login attempts or DDL changes: + +```bash +log_connections = on +log_disconnections = on +log_statement = 'ddl' +``` + +For more information on pgAudit, see the [pgAudit documentation](https://www.pgaudit.org). + +## Monitoring and alerting + +Intermediate PostgreSQL security requires robust monitoring and alerting. Several tools and configurations can help with this: + +- **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. + +- **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. + +- **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: + +```bash +log_min_error_statement = 'ERROR' +log_min_duration_statement = 1000 +``` + +## Database hardening + +Hardening your PostgreSQL server is an intermediate security practice that reduces the attack surface by removing or disabling unnecessary features. + +- **Remove unused extensions.** Extensions can increase the attack surface of PostgreSQL. Disable or remove any extensions you don't actively use. For example: + +```sql +DROP EXTENSION IF EXISTS plperl; +``` + +- **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: + +```bash +chmod 700 /var/lib/postgresql/data +``` + +## Securing PostgreSQL on cloud providers + +Cloud environments introduce additional layers of complexity. The following can help secure your PostgreSQL instances in the cloud: + +- **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. + +- **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. + +- **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: + +```bash +aws rds generate-db-auth-token --hostname --port 5432 --region --username +``` + +## Implementing multi-factor authentication (MFA) + +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. + +- **External identity providers.** For added security, integrate MFA with identity providers such as Okta, Google Identity, Azure AD, or AWS IAM. + diff --git a/advocacy_docs/security/securing-postgresql/301/index.mdx b/advocacy_docs/security/securing-postgresql/301/index.mdx index b0a112576dd..22583e57a41 100644 --- a/advocacy_docs/security/securing-postgresql/301/index.mdx +++ b/advocacy_docs/security/securing-postgresql/301/index.mdx @@ -4,4 +4,165 @@ navTitle: Security 301 description: Your guide to Compliance, certifications, auditing and other higher-level issues. --- -TBD +As security requirements increase in complexity, it’s critical to move beyond basic and intermediate configurations. +Advanced security in PostgreSQL focuses on hardening systems to meet strict compliance standards, such as Security Technical Implementation Guides (STIGs), GDPR, PCI-DSS, HIPAA, and FISMA. +Use the following advanced strategies to secure PostgreSQL in high-stakes environments. + +## Security Technical Implementation Guides (STIGs) + +STIGs are configuration standards developed by the Defense Information Systems Agency (DISA) to ensure that IT systems meet strict security controls. PostgreSQL has its own specific STIGs, which must be followed when the database is used in government or defense environments. + +- **Install PostgreSQL STIG.** Ensure that your PostgreSQL installation meets the guidelines of the PostgreSQL STIG. This includes hardening configurations, removing unnecessary features, and enforcing security controls. + +- **Audit STIG compliance.** The stig-postgresql project provides automated scripts to check for STIG compliance. Use pgstigcheck or other security auditing tools to verify your PostgreSQL configurations against STIG guidelines. + +- **Implement STIG hardening.** Follow STIG guidelines for logging, encryption, and auditing role changes. + +- **Log all activity.** STIGs mandate strict logging of user activity. Configure PostgreSQL to log all SQL commands—even reads—to ensure traceability. + +```bash +log_statement = 'all' +log_connections = on +log_disconnections = on +``` + +- **Encrypt data at rest.** Encrypt the data directory and backups as per STIG requirements. Use encryption standards that follow industry best practices, such as AES-256 encryption. + +- **Audit role changes and privileges.** Regularly audit role changes and privilege escalations, logging all role modifications and access control changes: + +```bash +log_statement = 'ddl' +``` + +## Compliance requirements + +For information on EDB data privacy and compliance policies, see the [EDB Trust Center](https://trust.enterprisedb.com). + +### General Data Protection Regulation (GDPR) + +The European Union’s GDPR focuses on protecting the privacy and security of personal data. PostgreSQL must be configured to ensure data privacy, security, and accountability. + +- **Data minimization and encryption.** Ensure that only essential data is collected and stored. Implement both column-level encryption for sensitive data and full-disk encryption for databases. +pgcrypto allows you to encrypt/decrypt sensitive columns: + +```sql +SELECT pgp_sym_encrypt('personal data', 'encryption_key'); +``` + +- **Right to erasure.** Implement functionality to allow for complete and secure deletion of user data upon request. For a compliant data deletion process, ensure that records are fully purged, including from backup systems, to comply with GDPR's "Right to be Forgotten." + +- **Data breach notifications.** In the event of a data breach, GDPR mandates prompt notification. PostgreSQL logging, auditing, and alerting help to detect breaches immediately. + +### Payment Card Industry Data Security Standard (PCI-DSS) + +PCI-DSS ensures the secure handling of payment card information. PostgreSQL must be hardened to prevent unauthorized access to sensitive cardholder data. + +- **Encryption.** PCI-DSS mandates encryption of cardholder data both in transit and at rest. Use scram-sha-256 for encrypting connections and client-side encryption for cardholder data. + +- **Segregation of duties.** Ensure that users accessing the database are restricted to specific tasks and can't access cardholder data unnecessarily. You can do this using PostgreSQL’s role-based access control (RBAC). + + Use RBAC to separate administrative and data access functions. For example: + +```sql +CREATE ROLE cardholder_data_access; +GRANT SELECT ON card_data TO cardholder_data_access; +``` + +- **Detailed logging.** PCI-DSS requires detailed logging of all access to cardholder data. Use pgaudit to track reads, writes, and role changes to sensitive data. + +### Health Insurance Portability and Accountability Act (HIPAA) + +HIPAA governs the protection of healthcare data in the United States. PostgreSQL installations dealing with protected health information (PHI) must meet stringent confidentiality, integrity, and availability requirements. + +- **Encrypt PHI.** All PHI must be encrypted at rest and in transit. Use pgcrypto or external encryption tools to secure PHI in PostgreSQL. + +- **Access control.** Implement strong authentication and authorization. Ensure that users and roles are defined clearly, and use multi-factor authentication (MFA) for administrative access. + +- **Audit trails.** HIPAA requires tracking and logging any access to PHI. You can configure PostgreSQL’s logging system and pgaudit to log these actions. For example: + +```bash +log_statement = 'all' +log_min_duration_statement = 1000 +``` + +## PostgreSQL in FISMA-compliant environments + +The Federal Information Security Management Act (FISMA) establishes security requirements for federal IT systems. To be used in FISMA environments, PostgreSQL must comply with the NIST SP 800-53 framework. + +- **FIPS-140-2 encryption.** Ensure PostgreSQL uses FIPS-compliant encryption algorithms for secure communication. PostgreSQL can be integrated with OpenSSL configured for FIPS mode, or you can use external encryption tools. + +- **Multi-factor authentication (MFA).** Use MFA for administrative access to the database. Integration with external identity providers (for example, Okta, AWS IAM) can help enforce MFA policies for critical roles. + +- **Incident response.** Configure PostgreSQL to detect and respond to security incidents. All security-related events must be logged, and systems must have defined incident response plans. + +## Advanced encryption practices + +Encryption is a cornerstone of advanced database security. Beyond basic encryption of data in transit and at rest, advanced encryption practices include key management and more sophisticated data protection strategies. + +### Key management + +- **External key management.** Rather than storing encryption keys within the database or filesystem, use external systems like AWS KMS, HashiCorp Vault, or Azure Key Vault to manage encryption keys. For example: + +```bash +aws kms encrypt --key-id alias/myKey --plaintext fileb://myfile +``` + +- **Key rotation.** To limit the potential damage from key compromise, regularly rotate encryption keys. Ensure PostgreSQL encryption supports key rotation without downtime. + +### Transparent data encryption (TDE) + +TDE encrypts the entire database at the file level. While not natively supported in PostgreSQL, tools like pgcrypto and external software can implement TDE. + +- **Use pgTDE.** You can use the pgTDE extension to encrypt entire databases or specific tablespaces. Data is encrypted transparently as it's written to disk. + +## Data masking and tokenization + +Data masking and tokenization protect sensitive data by obfuscating it when it isn't needed. This is especially useful in test or staging environments, where real data might be exposed. + +- **Dynamic data masking.** PostgreSQL doesn't natively support data masking, but you can implement it using views to hide sensitive data: + +```sql +CREATE VIEW masked_view AS +SELECT id, '****' AS credit_card FROM customers; +``` + +- **Tokenization.** Use external tokenization services to replace sensitive data like credit card numbers or social security numbers with tokens. These tokens can be used for processing without exposing the real data. + +## Advanced logging and monitoring + +Advanced PostgreSQL setups require more detailed logging and monitoring, especially in environments subject to compliance audits or high-level threat detection. + +### pgaudit configuration + +- **Log DDL, DML, and role changes.** Configure pgaudit to log detailed events, including access to sensitive tables, role changes, and permission escalations: + +```bash +pgaudit.log = 'ddl, role, read, write' +``` + +### Integration with SIEM systems + +For real-time monitoring and alerting on suspicious activity, integrate PostgreSQL logs into security information and event management (SIEM) systems, such as Splunk, ELK Stack, or AWS CloudWatch. + +- **Log integration.** Ship PostgreSQL logs to a SIEM system for real-time monitoring and alerting on suspicious activity: + +```bash +log_destination = 'stderr' +logging_collector = on +log_directory = '/var/log/postgresql' +``` + +- **Custom alerts.** Set up custom alerts in your SIEM system to notify administrators of anomalous activities like repeated failed login attempts or unauthorized role changes. + +## Database hardening automation + +Automating database hardening ensures consistency and repeatability in applying security configurations. Use tools like Ansible, Terraform, or Chef to enforce PostgreSQL hardening at scale. + +- **Automation with Ansible/Terraform.** Use Terraform or Ansible scripts to enforce role-based access controls consistently across environments. For example: + +```bash +ansible-playbook -i inventory.yml playbook.yml +``` + +- **STIG compliance automation.** Use automation scripts to ensure all PostgreSQL servers comply with STIGs or other regulatory guidelines. Run compliance checks regularly to detect deviations. +