Lab 18: Database Security

Time: 40 minutes | Level: Practitioner | DB: MySQL 8.0 + PostgreSQL 15

Database security encompasses authentication (who you are), authorization (what you can do), and data protection (row-level isolation, encryption). Misconfigured databases are the #1 source of data breaches.


Step 1 — MySQL: CREATE USER and Password Policies

-- Create users with strong passwords
CREATE USER 'app_user'@'%'        IDENTIFIED BY 'AppPass123!';
CREATE USER 'readonly_user'@'%'   IDENTIFIED BY 'ReadOnly123!';
CREATE USER 'report_user'@'localhost' IDENTIFIED BY 'Report123!';

-- Require SSL connection
CREATE USER 'secure_user'@'%'
  IDENTIFIED BY 'SecurePass123!'
  REQUIRE SSL;

-- Password policy: expire after 90 days
CREATE USER 'audit_user'@'%'
  IDENTIFIED BY 'AuditPass123!'
  PASSWORD EXPIRE INTERVAL 90 DAY;

-- View users
SELECT user, host, plugin, account_locked, password_expired
FROM mysql.user
WHERE user NOT IN ('root','mysql.sys','mysql.infoschema','mysql.session');

Step 2 — MySQL: GRANT and REVOKE

📸 Verified Output:


Step 3 — MySQL 8: Roles

💡 MySQL 8 roles work like "permission templates" — change the role and all role members immediately get updated permissions. No need to re-grant each user individually.


Step 4 — PostgreSQL: CREATE ROLE and GRANT

📸 Verified Output:


Step 5 — PostgreSQL: Row-Level Security (RLS)

RLS filters rows at the database level — users can only see/modify rows they're permitted to.

📸 Verified Output:


Step 6 — PostgreSQL: Column-Level Security


Step 7 — pg_hba.conf and SSL Concepts

pg_hba.conf (PostgreSQL Host-Based Authentication) controls who can connect:

Authentication methods:

Method
Description

trust

No password (dev only!)

password

Plaintext (never use)

md5

MD5 hash (legacy)

scram-sha-256

Modern secure (recommended)

peer

OS username must match

cert

TLS client certificate


Step 8 — Capstone: Secure Multi-Tenant Database


Summary

Feature
MySQL
PostgreSQL

Create user

CREATE USER 'u'@'h' IDENTIFIED BY 'p'

CREATE USER u WITH PASSWORD 'p'

Grant table

GRANT SELECT ON db.tbl TO u@h

GRANT SELECT ON tbl TO role

Grant DB

GRANT ALL ON db.* TO u@h

GRANT CONNECT ON DATABASE db TO u

Roles

MySQL 8+: CREATE ROLE r

CREATE ROLE r (native)

Column grants

GRANT SELECT (col1,col2) ON tbl

GRANT SELECT (col) ON tbl

Row-level security

Not built-in (use views)

ALTER TABLE t ENABLE ROW LEVEL SECURITY

View grants

SHOW GRANTS FOR u@h

\dp or pg_roles + information_schema

Auth config

mysql.user table

pg_hba.conf file

Last updated