Database Security

Unit 5CLO01

In 2023, data breaches exposed over 3 billion records globally. Equifax breach, Capital One breach, Marriott breach—the list goes on. Database security isn't optional; it's essential. A single SQL injection or weak access control can expose millions of customer records, leading to financial losses, legal consequences, and destroyed trust.

The Basics

Database security protects against unauthorized access, data breaches, and malicious attacks through multiple layers of defense.

Security Objectives (CIA Triad):

  1. Confidentiality: Only authorized users access data
    Prevent: Unauthorized disclosure, eavesdropping

  2. Integrity: Data accuracy and consistency
    Prevent: Unauthorized modification, corruption

  3. Availability: Authorized users can access when needed
    Prevent: DoS attacks, system failures

Security Layers:

  1. Network Security: Firewalls, VPNs, encryption
  2. OS Security: User accounts, file permissions
  3. Database Security: Authentication, authorization, auditing
  4. Application Security: Input validation, secure coding

Key Threats:

  • SQL Injection: Malicious SQL in user input
  • Unauthorized Access: Weak passwords, stolen credentials
  • Privilege Escalation: Gaining higher access than authorized
  • Insider Threats: Malicious employees
  • Data Leakage: Unencrypted data transmission
  • DoS/DDoS: Overwhelming system with requests

Technical Details

AUTHENTICATION:

Verifying user identity

Methods:

  1. Password-Based:

    • Most common
    • Store hashed passwords (SHA-256, bcrypt)
    • Never store plaintext
    • Salting prevents rainbow table attacks
  2. Multi-Factor Authentication (MFA):

    • Something you know (password)
    • Something you have (token, phone)
    • Something you are (biometric)
  3. Certificate-Based:

    • Digital certificates (X.509)
    • Public key infrastructure (PKI)
  4. OAuth/SAML:

    • Federated authentication
    • Single Sign-On (SSO)

AUTHORIZATION & ACCESS CONTROL:

Determining what authenticated users can do

  1. DISCRETIONARY ACCESS CONTROL (DAC):

Owner controls access to resources

SQL Commands:
GRANT SELECT, INSERT ON Employees TO user1;
GRANT ALL PRIVILEGES ON DATABASE company TO admin;
REVOKE DELETE ON Orders FROM user2;

GRANT Options:

  • SELECT: Read data
  • INSERT: Add new data
  • UPDATE: Modify existing data
  • DELETE: Remove data
  • EXECUTE: Run stored procedures

WITH GRANT OPTION: User can grant permissions to others
GRANT SELECT ON Employees TO user1 WITH GRANT OPTION;

Problems with DAC:

  • Permissions can spread uncontrollably
  • No central policy enforcement
  • Vulnerable to Trojan horse attacks
  1. MANDATORY ACCESS CONTROL (MAC):

System enforces access policy based on security labels

Concepts:

  • Security Clearance: User's level (Top Secret, Secret, Unclassified)
  • Security Classification: Data's level
  • Bell-LaPadula Model:
    • No Read Up: Can't read higher classification
    • No Write Down: Can't write to lower classification
    • Prevents information leakage

Example:
User with SECRET clearance:

  • Can read: UNCLASSIFIED, SECRET
  • Cannot read: TOP SECRET
  • Can write: SECRET, TOP SECRET
  • Cannot write: UNCLASSIFIED (prevents leaking)

Used in: Military, government systems

  1. ROLE-BASED ACCESS CONTROL (RBAC):

RBAC Model

Permissions assigned to roles, users assigned to roles

Advantages:

  • Easier management (modify role, not individual users)
  • Principle of least privilege
  • Separation of duties

SQL Implementation:

CREATE ROLE hr_manager;
GRANT SELECT, UPDATE ON Employees TO hr_manager;
GRANT SELECT ON Salaries TO hr_manager;

CREATE ROLE accountant;
GRANT SELECT ON Salaries TO accountant;
GRANT INSERT, UPDATE ON Expenses TO accountant;

GRANT hr_manager TO alice;
GRANT accountant TO bob;

Role Hierarchies:
CREATE ROLE manager;
GRANT hr_manager TO manager; -- Manager inherits HR permissions

SQL INJECTION:

Attack Mechanism:
User input interpreted as SQL code

Vulnerable Code (Python):
username = request.form['username']
password = request.form['password']
query = f"SELECT * FROM Users WHERE username='{username}' AND password='{password}'"
execute(query)

Attack Input:
username: admin' --
password: anything

Resulting Query:
SELECT * FROM Users WHERE username='admin' -- ' AND password='anything'
(-- comments out rest, bypasses password check)

Worse Attack (Union-based):
username: ' UNION SELECT * FROM CreditCards --

Resulting Query:
SELECT * FROM Users WHERE username='' UNION SELECT * FROM CreditCards -- '
(Returns credit card data!)

Prevention:

  1. Parameterized Queries (Prepared Statements):

Secure Code (Python):
query = "SELECT * FROM Users WHERE username=? AND password=?"
execute(query, (username, password))

Database treats ? as data, not code

  1. Stored Procedures:
    CREATE PROCEDURE AuthenticateUser(@username NVARCHAR(50), @password NVARCHAR(50))
    AS
    BEGIN
    SELECT * FROM Users WHERE username=@username AND password=@password;
    END;

CALL AuthenticateUser('admin', 'pass123');

  1. Input Validation:
  • Whitelist allowed characters
  • Reject suspicious input ('; --, UNION, etc.)
  • Escape special characters
  1. Least Privilege:
  • Application database account has minimal permissions
  • No DROP, CREATE permissions
  1. Web Application Firewall (WAF):
  • Detects and blocks SQL injection patterns

ENCRYPTION:

  1. Data at Rest:

    • Encrypt database files
    • Transparent Data Encryption (TDE)
    • Column-level encryption for sensitive fields
  2. Data in Transit:

    • SSL/TLS for connections
    • HTTPS for web applications
  3. Key Management:

    • Secure key storage (HSM, Key Vault)
    • Key rotation policies

AUDITING:

Track who accessed what, when

Audit Log Contents:

  • User ID
  • Timestamp
  • Action (SELECT, INSERT, UPDATE, DELETE)
  • Table/row accessed
  • Success/failure
  • Source IP

SQL Server Audit:
CREATE SERVER AUDIT CompanyAudit
TO FILE (FILEPATH = 'C:\Audits')
WITH (ON_FAILURE = CONTINUE);

CREATE DATABASE AUDIT SPECIFICATION SalaryAudit
FOR SERVER AUDIT CompanyAudit
ADD (SELECT, UPDATE ON Salaries BY public);

Benefits:

  • Detect unauthorized access
  • Forensics after breach
  • Compliance (GDPR, HIPAA, SOX)

Examples

Example 1: SQL Injection Attack & Prevention

Vulnerable Login (PHP):
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);

Attack:
Username: admin' OR '1'='1
Password: anything

Query becomes:
SELECT * FROM users WHERE username='admin' OR '1'='1' AND password='anything'
(Always true, logs in as admin!)

Secure Version (Prepared Statement):
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

Example 2: RBAC Implementation

-- Create roles
CREATE ROLE sales_rep;
CREATE ROLE sales_manager;
CREATE ROLE admin;

-- Grant permissions to roles
GRANT SELECT ON Customers TO sales_rep;
GRANT SELECT, INSERT ON Orders TO sales_rep;

GRANT SELECT ON Customers TO sales_manager;
GRANT SELECT, INSERT, UPDATE ON Orders TO sales_manager;
GRANT SELECT ON SalesReport TO sales_manager;

GRANT ALL PRIVILEGES ON DATABASE company TO admin;

-- Assign users to roles
GRANT sales_rep TO john, mary;
GRANT sales_manager TO alice;
GRANT admin TO bob;

-- Role hierarchy (manager inherits rep permissions)
GRANT sales_rep TO sales_manager;

Example 3: Encryption

-- Column-level encryption (SQL Server)
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'StrongPassword123!';

CREATE CERTIFICATE SSNCert
WITH SUBJECT = 'SSN Encryption Certificate';

CREATE SYMMETRIC KEY SSNKey
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE SSNCert;

-- Encrypt data
OPEN SYMMETRIC KEY SSNKey
DECRYPTION BY CERTIFICATE SSNCert;

INSERT INTO Employees (Name, SSN_Encrypted)
VALUES ('John Doe', EncryptByKey(Key_GUID('SSNKey'), '123-45-6789'));

CLOSE SYMMETRIC KEY SSNKey;

-- Decrypt data
OPEN SYMMETRIC KEY SSNKey
DECRYPTION BY CERTIFICATE SSNCert;

SELECT Name, CONVERT(VARCHAR, DecryptByKey(SSN_Encrypted)) AS SSN
FROM Employees;

CLOSE SYMMETRIC KEY SSNKey;

Example 4: Auditing

-- Enable auditing for sensitive table (PostgreSQL)
CREATE TABLE audit_log (
audit_id SERIAL PRIMARY KEY,
table_name VARCHAR(50),
action VARCHAR(10),
user_name VARCHAR(50),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
old_data JSON,
new_data JSON
);

-- Trigger to log changes
CREATE OR REPLACE FUNCTION log_salary_changes()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
INSERT INTO audit_log (table_name, action, user_name, old_data, new_data)
VALUES ('Salaries', 'UPDATE', current_user,
row_to_json(OLD), row_to_json(NEW));
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER salary_audit
AFTER UPDATE ON Salaries
FOR EACH ROW EXECUTE FUNCTION log_salary_changes();

Real-World Use

Best Practices:

  1. Defense in Depth:

    • Multiple security layers
    • Firewall + Authentication + Authorization + Encryption + Auditing
    • If one fails, others still protect
  2. Principle of Least Privilege:

    • Grant minimum necessary permissions
    • Application account: Only needed tables
    • Read-only users: No write permissions
  3. Input Validation:

    • Validate all user input
    • Use parameterized queries
    • Whitelist, not blacklist
  4. Regular Security Audits:

    • Review user permissions
    • Check audit logs for anomalies
    • Penetration testing
  5. Encryption:

    • Encrypt sensitive data at rest
    • Use SSL/TLS for connections
    • Secure key management
  6. Patch Management:

    • Keep database software updated
    • Apply security patches promptly
  7. Monitoring & Alerting:

    • Monitor failed login attempts
    • Alert on unusual access patterns
    • Real-time intrusion detection

Compliance Standards:

  • GDPR: EU data protection
  • HIPAA: Healthcare data (US)
  • PCI DSS: Credit card data
  • SOX: Financial reporting

Real-World Scenarios:

  • Healthcare: Encrypt patient records, audit all access
  • Banking: MFA, transaction auditing, encryption
  • E-commerce: PCI DSS compliance, secure payment data
  • Government: MAC for classified data

For exams

Important Questions:

  1. Explain the CIA triad in database security
  2. Compare DAC, MAC, and RBAC with examples
  3. What is SQL injection? How to prevent it?
  4. Show SQL injection attack and secure code
  5. Explain role-based access control with SQL examples
  6. What is the difference between authentication and authorization?
  7. Why use parameterized queries instead of string concatenation?
  8. Explain encryption at rest vs encryption in transit
  9. What is database auditing? Why is it important?
  10. Explain multi-factor authentication
  11. What is the principle of least privilege?
  12. How does GRANT and REVOKE work in SQL?

Key points

Key Principles:

• Security requires multiple layers: authentication, authorization, encryption, auditing
• SQL injection is preventable: use parameterized queries, never concatenate SQL
• RBAC simplifies permission management: assign permissions to roles, not individuals
• Principle of least privilege: grant minimum necessary permissions
• Encryption protects data at rest and in transit
• Auditing provides accountability and forensics
• Defense in depth: multiple security layers provide redundancy
• Security is ongoing: monitor, patch, audit regularly