Implementing Database Security

1. Creating Database Users and Roles

CommandEffect
CREATE ROLE name LOGIN PASSWORD '...'Create user
CREATE ROLE app_read NOINHERITGroup role
GRANT app_read TO aliceAdd user to role
REVOKE ... FROM ...Remove privileges
DROP ROLEDelete (must reassign owned objects)

2. Granting and Revoking Permissions

PrivilegeScope
SELECT / INSERT / UPDATE / DELETETables / views
REFERENCESCreate FK pointing to
TRIGGERCreate trigger
EXECUTEFunctions / procedures
USAGESchemas, sequences
ALL PRIVILEGESEverything (avoid in prod)
WITH GRANT OPTIONAllow regrant

3. Implementing Row-Level Security

Example: Postgres RLS

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id')::BIGINT);
GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app_role;
FeatureDetail
USING clauseRead filter
WITH CHECKWrite filter
FORCE ROW LEVEL SECURITYApply to table owner too
BypassBYPASSRLS role attribute

4. Implementing Column-Level Security

ApproachDetail
GRANT on specific colsGRANT SELECT(name, email) ON users TO ...
ViewsProject allowed cols only
Data masking (SQL Server, Oracle)Built-in static/dynamic masking
EncryptionApp-side encrypt sensitive cols

5. Using Database Encryption

LayerMechanism
In-transitTLS (require, verify-full)
At-rest (disk)LUKS, EBS encryption, TDE
TDETransparent Data Encryption (Oracle/SQL Server)
Column-level (DB)pgcrypto, Always Encrypted
App-levelAES-GCM with envelope keys (KMS)

6. Implementing SQL Injection Prevention

DefenseDetail
Parameterized queriesAlways — never concatenate user input
ORM / query builderTreats inputs as data
Least privilegeApp role can't DROP/ALTER
Stored proceduresDefined query shape
Input validationAllow-list for identifiers (table/col names)
WAFSecond line of defense
Warning: Dynamic SQL is the #1 source of SQLi. If you must build queries dynamically, validate identifiers against an allow-list and bind values as parameters.

7. Auditing Database Access

ToolDB
pgaudit extensionPostgres
Audit log pluginMySQL Enterprise
SQL Server AuditBuilt-in
Unified AuditOracle 12c+
Ship logsSIEM (Splunk, ELK)

8. Managing Database Authentication

MethodDetail
Password (SCRAM-SHA-256)Default modern method (PG 14+)
Certificate (mTLS)Strongest; key rotation needed
LDAP / Kerberos / SAMLEnterprise SSO integration
IAM tokens (RDS/Aurora)Short-lived AWS-signed tokens
OAuth (some managed DBs)App identity federation

9. Implementing Principle of Least Privilege

PracticeDetail
App role ≠ ownerApp can't change schema
Separate rolesread-only / read-write / migration
Default DENYGrant only what's needed
Revoke from PUBLICDon't rely on default grants
Time-bound rolesJust-in-time elevation

10. Securing Database Connections

SettingDetail
sslmode=verify-fullHostname + CA check
VPC / private subnetNo public access
IP allow-list / SGRestrict source
SSH tunnel / bastionOperator access path
Rotate keysAutomated, < 90 day cadence