GDPR Compliance on Linux Servers: Complete Implementation Guide

Introduction

The General Data Protection Regulation (GDPR) represents the most comprehensive data protection legislation in modern history, fundamentally transforming how organizations handle personal data within the European Union and beyond. For system administrators and DevOps professionals managing Linux servers, GDPR compliance is not merely a legal checkbox but a comprehensive technical implementation that requires deep understanding of data flows, security measures, and privacy-by-design principles.

This comprehensive guide provides Linux system administrators with practical, command-line driven approaches to achieving and maintaining GDPR compliance on Linux servers. Whether you're managing web applications, databases, or entire infrastructure stacks, this guide covers the essential technical controls, documentation requirements, and auditing procedures necessary for GDPR compliance.

GDPR compliance on Linux servers encompasses multiple layers: data identification and classification, encryption at rest and in transit, access controls, audit logging, data retention policies, and incident response capabilities. Each of these components requires specific technical implementations, monitoring procedures, and documentation practices that we'll explore in depth throughout this guide.

Why GDPR Matters for Linux Server Administrators

GDPR applies to any organization that processes personal data of EU residents, regardless of where the organization is located. Personal data includes any information relating to an identified or identifiable natural person, including names, email addresses, IP addresses, location data, and online identifiers. For Linux servers processing such data, non-compliance can result in fines up to 20 million euros or 4% of annual global turnover, whichever is higher.

Beyond legal penalties, GDPR compliance provides significant technical and business benefits: improved data security posture, enhanced customer trust, reduced risk of data breaches, better data governance, and streamlined incident response procedures. The technical measures required for GDPR compliance often align with general security best practices, making compliance efforts a valuable investment in overall infrastructure security.

GDPR Principles Relevant to Linux Server Management

GDPR is built on seven fundamental principles that directly impact how we configure and manage Linux servers:

Lawfulness, Fairness, and Transparency: Data processing must have a legal basis, and data subjects must be informed about how their data is processed. For server administrators, this means implementing clear logging, documenting data flows, and ensuring transparency in system operations.

Purpose Limitation: Personal data must be collected for specified, explicit, and legitimate purposes. This principle drives requirements for data classification, separation of systems based on purpose, and prevention of data use beyond original intent.

Data Minimization: Only data that is necessary for the specified purpose should be collected. Server administrators must implement technical measures to prevent unnecessary data collection, such as log sanitization, selective data capture, and automatic data filtering.

Accuracy: Personal data must be accurate and kept up to date. This requires implementing data validation, update mechanisms, and correction procedures at the system level.

Storage Limitation: Personal data should be kept only as long as necessary. This drives implementation of automated data retention policies, log rotation, database archival procedures, and secure deletion mechanisms.

Integrity and Confidentiality: Personal data must be processed securely using appropriate technical measures. This encompasses encryption, access controls, network security, system hardening, and monitoring.

Accountability: Organizations must demonstrate compliance with GDPR principles. For Linux administrators, this means comprehensive audit logging, documentation of technical measures, regular compliance assessments, and evidence collection.

GDPR Compliance Requirements for Linux Servers

Data Protection Impact Assessment (DPIA)

Before implementing technical controls, organizations must conduct a Data Protection Impact Assessment (DPIA) for processing operations that pose high risks to individuals' rights and freedoms. While DPIA is primarily a legal and organizational process, Linux administrators play a crucial role in providing technical information needed for the assessment.

Technical Information Required for DPIA:

  1. System Architecture Documentation: Document all systems processing personal data, including servers, databases, applications, and third-party services.

  2. Data Flow Mapping: Identify how personal data moves through your infrastructure, including collection points, processing locations, storage systems, and external transfers.

  3. Security Measures Assessment: Document existing technical and organizational security measures, including encryption, access controls, monitoring, and backup procedures.

  4. Risk Identification: Identify potential security risks, including unauthorized access, data breaches, system failures, and insider threats.

To gather system architecture information for DPIA, use these commands:

# List all listening services and ports
sudo netstat -tulpn | grep LISTEN

# Identify running applications and their connections
sudo lsof -i -P -n

# Review installed packages that might process personal data
dpkg -l | grep -E "(web|database|mail|log)" # Debian/Ubuntu
rpm -qa | grep -E "(web|database|mail|log)" # RHEL/CentOS

# Check for active network connections
sudo ss -tunap

# Identify data storage locations
sudo find / -type d -name "*data*" -o -name "*logs*" 2>/dev/null | head -20

Legal Basis for Processing

GDPR requires a legal basis for processing personal data. The six legal bases are: consent, contract, legal obligation, vital interests, public task, and legitimate interests. For each data processing activity on your Linux servers, you must identify and document the legal basis.

Technical Implementation Considerations:

  • Consent Management: If relying on consent, implement mechanisms to record, store, and retrieve consent records, including timestamps, scope, and withdrawal capabilities.

  • Contract Processing: For data processed to fulfill contractual obligations, implement data segregation and retention policies aligned with contract lifecycles.

  • Legal Obligations: When processing is required by law, document the legal requirement and implement appropriate safeguards.

Data Subject Rights

GDPR grants individuals eight rights regarding their personal data. Linux server administrators must implement technical capabilities to support these rights:

1. Right of Access (Article 15): Data subjects can request copies of their personal data. You must implement search and export capabilities.

# Example: Search for user data across log files
grep -r "[email protected]" /var/log/ 2>/dev/null

# Search database for specific user data (example with MySQL)
mysql -u root -p -e "SELECT * FROM users WHERE email='[email protected]';" database_name

# Find files owned by or containing specific user data
sudo find /var/www -type f -exec grep -l "[email protected]" {} \;

2. Right to Rectification (Article 16): Data subjects can request correction of inaccurate data. Implement update procedures with audit trails.

3. Right to Erasure / "Right to be Forgotten" (Article 17): Data subjects can request deletion of their data under certain conditions. You must implement secure deletion procedures.

# Secure file deletion using shred
shred -vfz -n 10 /path/to/file/containing/personal/data.txt

# Secure deletion of database records (example)
# Always backup before deletion and log the action
mysql -u root -p -e "DELETE FROM users WHERE email='[email protected]' AND gdpr_deletion_requested=1;" database_name

# Find and securely delete files containing specific user data
find /var/backups -type f -name "*user_backup*" -exec shred -vfz -n 5 {} \;

# Overwrite free space to ensure deleted data cannot be recovered
sfill -v /mount/point

4. Right to Data Portability (Article 20): Data subjects can request their data in a structured, machine-readable format. Implement export procedures in common formats (JSON, CSV, XML).

# Export user data to JSON format
mysql -u root -p -e "SELECT * FROM users WHERE email='[email protected]';" database_name | python3 -c "import sys, json, csv; print(json.dumps(list(csv.DictReader(sys.stdin, delimiter='\t'))))" > user_data_export.json

# Export to CSV format
mysql -u root -p --batch -e "SELECT * FROM users WHERE email='[email protected]';" database_name | sed 's/\t/,/g' > user_data_export.csv

5. Right to Restriction of Processing (Article 18): Data subjects can request temporary restriction of processing. Implement flags or separate storage for restricted data.

6. Right to Object (Article 21): Data subjects can object to certain types of processing. Implement opt-out mechanisms and processing restrictions.

7. Rights Related to Automated Decision Making (Article 22): Data subjects have rights regarding automated decisions with legal or significant effects. Document automated processing and implement human review capabilities.

8. Right to Be Informed (Articles 13-14): Data subjects must be informed about data processing. While primarily a legal/UI concern, maintain clear documentation of all processing activities.

Implementation Steps

Step 1: Data Discovery and Classification

The foundation of GDPR compliance is knowing what personal data you have, where it's stored, and how it's processed. This requires systematic data discovery across all Linux servers.

Identifying Personal Data Repositories:

# Create a data inventory script
cat > /root/scripts/data_inventory.sh << 'EOF'
#!/bin/bash
# GDPR Data Inventory Script
# Identifies potential locations of personal data

echo "=== GDPR Data Inventory Report ==="
echo "Generated: $(date)"
echo "Hostname: $(hostname)"
echo ""

echo "=== Database Services ==="
systemctl list-units --type=service --state=running | grep -E "(mysql|mariadb|postgresql|mongodb)"

echo ""
echo "=== Web Application Directories ==="
find /var/www /usr/share/nginx /opt -type d -name "*user*" -o -name "*customer*" -o -name "*data*" 2>/dev/null

echo ""
echo "=== Log Files Potentially Containing Personal Data ==="
find /var/log -type f -size +10M 2>/dev/null | head -20

echo ""
echo "=== Backup Locations ==="
find / -type d -name "*backup*" -o -name "*bak*" 2>/dev/null | grep -v proc | head -20

echo ""
echo "=== Recently Modified Large Files ==="
find /home /var /opt -type f -size +50M -mtime -30 2>/dev/null | head -20

echo ""
echo "=== Email Storage ==="
find /var/mail /var/spool/mail /home -type d -name "Maildir" -o -name "mail" 2>/dev/null

echo ""
echo "=== Session Storage ==="
find /var/lib -type d -name "*session*" 2>/dev/null
ls -lh /tmp | grep sess 2>/dev/null

EOF

chmod +x /root/scripts/data_inventory.sh
/root/scripts/data_inventory.sh > /var/log/gdpr_data_inventory_$(date +%Y%m%d).log

Analyzing Application Logs for Personal Data:

# Scan web server logs for personal data patterns
# Email addresses
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" /var/log/apache2/access.log | wc -l

# IP addresses (already logged, but check for excessive logging)
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# Check for user identifiers in URLs (potential privacy issue)
grep -E "user_id=|userId=|email=" /var/log/nginx/access.log | head -10

# Identify authentication logs
grep -E "(authentication|login|password)" /var/log/auth.log | tail -20

Database Personal Data Audit:

# MySQL/MariaDB: Identify tables containing personal data
mysql -u root -p -e "
SELECT
    TABLE_SCHEMA,
    TABLE_NAME,
    COLUMN_NAME,
    COLUMN_TYPE
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMN_NAME REGEXP 'email|phone|address|name|ssn|dob|birth'
    AND TABLE_SCHEMA NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
ORDER BY
    TABLE_SCHEMA, TABLE_NAME;
" > /tmp/personal_data_columns.txt

# Count records in user tables
mysql -u root -p -e "
SELECT
    TABLE_NAME,
    TABLE_ROWS
FROM
    INFORMATION_SCHEMA.TABLES
WHERE
    TABLE_SCHEMA = 'your_database_name'
    AND TABLE_NAME REGEXP 'user|customer|contact|subscriber'
ORDER BY
    TABLE_ROWS DESC;
"

# PostgreSQL: Identify personal data columns
sudo -u postgres psql -c "
SELECT
    table_schema,
    table_name,
    column_name,
    data_type
FROM
    information_schema.columns
WHERE
    column_name ~* '(email|phone|address|name|ssn|dob|birth)'
    AND table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY
    table_schema, table_name;
" > /tmp/pg_personal_data_columns.txt

Step 2: Implementing Data Encryption

GDPR requires appropriate technical measures to protect personal data, with encryption being a primary control for both data at rest and in transit.

Disk Encryption with LUKS (for new installations or additional volumes):

# Check if LUKS is available
cryptsetup --version

# Encrypt a new partition or disk
# WARNING: This will destroy all data on the device
sudo cryptsetup luksFormat /dev/sdb1

# Open encrypted volume
sudo cryptsetup luksOpen /dev/sdb1 encrypted_volume

# Create filesystem
sudo mkfs.ext4 /dev/mapper/encrypted_volume

# Mount the encrypted volume
sudo mkdir -p /mnt/encrypted_data
sudo mount /dev/mapper/encrypted_volume /mnt/encrypted_data

# Add to /etc/crypttab for automatic mounting
echo "encrypted_volume /dev/sdb1 none luks" | sudo tee -a /etc/crypttab

# Add to /etc/fstab
echo "/dev/mapper/encrypted_volume /mnt/encrypted_data ext4 defaults 0 2" | sudo tee -a /etc/fstab

Database Encryption:

# MySQL/MariaDB: Enable encryption at rest
# Edit /etc/mysql/my.cnf or /etc/mysql/mariadb.conf.d/50-server.cnf

sudo tee -a /etc/mysql/mariadb.conf.d/50-server.cnf << 'EOF'

# Encryption at rest
[mysqld]
# Enable binary log encryption
encrypt_binlog = ON

# Enable InnoDB encryption
innodb_encrypt_tables = ON
innodb_encrypt_log = ON
innodb_encryption_threads = 4

# Encryption key management
plugin_load_add = file_key_management
file_key_management_filename = /etc/mysql/encryption/keyfile.enc
file_key_management_filekey = FILE:/etc/mysql/encryption/keyfile.key
file_key_management_encryption_algorithm = AES_CTR

EOF

# Create encryption keys directory
sudo mkdir -p /etc/mysql/encryption
sudo chmod 750 /etc/mysql/encryption

# Generate encryption keys (example - use proper key management in production)
sudo openssl rand -hex 32 > /etc/mysql/encryption/keyfile.key
sudo chmod 600 /etc/mysql/encryption/keyfile.key

# Restart MySQL
sudo systemctl restart mysql

# Verify encryption status
mysql -u root -p -e "SHOW VARIABLES LIKE '%encrypt%';"

PostgreSQL Transparent Data Encryption:

# PostgreSQL doesn't have built-in TDE, but you can use pgcrypto
sudo -u postgres psql -c "CREATE EXTENSION IF NOT EXISTS pgcrypto;"

# For full disk encryption, use LUKS at the OS level for the PostgreSQL data directory
# Example: Encrypt the PostgreSQL data directory volume

# Stop PostgreSQL
sudo systemctl stop postgresql

# Backup data
sudo rsync -av /var/lib/postgresql/ /backup/postgresql/

# Setup LUKS encryption (assuming new volume /dev/sdc1)
sudo cryptsetup luksFormat /dev/sdc1
sudo cryptsetup luksOpen /dev/sdc1 pg_encrypted
sudo mkfs.ext4 /dev/mapper/pg_encrypted
sudo mount /dev/mapper/pg_encrypted /var/lib/postgresql

# Restore data
sudo rsync -av /backup/postgresql/ /var/lib/postgresql/
sudo chown -R postgres:postgres /var/lib/postgresql

# Start PostgreSQL
sudo systemctl start postgresql

File-Level Encryption for Sensitive Data:

# Install encryption tools
sudo apt-get install -y gpg openssl # Debian/Ubuntu
sudo yum install -y gnupg openssl # RHEL/CentOS

# Encrypt individual files with GPG
gpg --symmetric --cipher-algo AES256 /path/to/sensitive/file.csv

# Decrypt when needed
gpg --decrypt file.csv.gpg > file.csv

# Encrypt with OpenSSL
openssl enc -aes-256-cbc -salt -in sensitive_file.txt -out sensitive_file.txt.enc -k "passphrase"

# Decrypt with OpenSSL
openssl enc -aes-256-cbc -d -in sensitive_file.txt.enc -out sensitive_file.txt -k "passphrase"

# Automated encryption script for backup files
cat > /root/scripts/encrypt_backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/var/backups/personal_data"
ENCRYPTED_DIR="/var/backups/encrypted"
GPG_RECIPIENT="[email protected]"

mkdir -p "$ENCRYPTED_DIR"

for file in "$BACKUP_DIR"/*.sql; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        gpg --encrypt --recipient "$GPG_RECIPIENT" --output "$ENCRYPTED_DIR/$filename.gpg" "$file"

        # Securely delete original
        shred -vfz -n 5 "$file"

        echo "Encrypted and removed: $file"
    fi
done
EOF

chmod +x /root/scripts/encrypt_backup.sh

Step 3: Access Control and Authentication

GDPR requires implementing appropriate access controls to ensure that only authorized personnel can access personal data. This involves principle of least privilege, role-based access control, and strong authentication.

User Access Auditing:

# List all users with system access
getent passwd | awk -F: '$3 >= 1000 {print $1, $3, $7}'

# Find users with sudo privileges
grep -rE "^%sudo|^%wheel" /etc/sudoers /etc/sudoers.d/ 2>/dev/null
sudo -l -U username

# List all SSH authorized keys
for user in $(getent passwd | awk -F: '$3 >= 1000 {print $1}'); do
    if [ -f "/home/$user/.ssh/authorized_keys" ]; then
        echo "=== User: $user ==="
        cat "/home/$user/.ssh/authorized_keys"
        echo ""
    fi
done

# Check for users with shell access
grep -v "/usr/sbin/nologin\|/bin/false" /etc/passwd | grep -v "^#"

Implementing Role-Based Access Control (RBAC):

# Create GDPR-specific user groups
sudo groupadd gdpr_data_admin
sudo groupadd gdpr_data_readonly
sudo groupadd gdpr_dpo

# Add users to appropriate groups
sudo usermod -aG gdpr_data_admin john
sudo usermod -aG gdpr_data_readonly support_team

# Set directory permissions for personal data
sudo chown -R root:gdpr_data_admin /opt/personal_data
sudo chmod 770 /opt/personal_data

# Set read-only access for audit purposes
sudo mkdir -p /opt/personal_data/readonly_audit
sudo chown -R root:gdpr_data_readonly /opt/personal_data/readonly_audit
sudo chmod 750 /opt/personal_data/readonly_audit

# Verify group memberships
groups username
getent group gdpr_data_admin

Database Access Controls:

# MySQL: Create GDPR-specific database users
mysql -u root -p << 'EOF'
-- Create dedicated users with limited privileges

-- DPO (Data Protection Officer) - read-only access for auditing
CREATE USER IF NOT EXISTS 'gdpr_dpo'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT ON *.* TO 'gdpr_dpo'@'localhost';

-- Data Administrator - full access to personal data
CREATE USER IF NOT EXISTS 'gdpr_admin'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON your_database.* TO 'gdpr_admin'@'localhost';

-- Application user - limited access
CREATE USER IF NOT EXISTS 'app_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE ON your_database.users TO 'app_user'@'localhost';
GRANT SELECT, INSERT, UPDATE ON your_database.orders TO 'app_user'@'localhost';

-- No DELETE permissions for application user to prevent accidental data loss

FLUSH PRIVILEGES;

-- Audit existing user privileges
SELECT user, host, Select_priv, Insert_priv, Update_priv, Delete_priv
FROM mysql.user
WHERE user NOT IN ('root', 'mysql.sys', 'mysql.session');

EOF

# PostgreSQL: GDPR-specific roles
sudo -u postgres psql << 'EOF'
-- Create roles
CREATE ROLE gdpr_dpo LOGIN PASSWORD 'secure_password';
CREATE ROLE gdpr_admin LOGIN PASSWORD 'secure_password';
CREATE ROLE gdpr_app LOGIN PASSWORD 'secure_password';

-- Grant read-only to DPO
GRANT CONNECT ON DATABASE your_database TO gdpr_dpo;
GRANT USAGE ON SCHEMA public TO gdpr_dpo;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO gdpr_dpo;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO gdpr_dpo;

-- Grant admin privileges
GRANT ALL PRIVILEGES ON DATABASE your_database TO gdpr_admin;

-- Limited application access
GRANT CONNECT ON DATABASE your_database TO gdpr_app;
GRANT SELECT, INSERT, UPDATE ON users TO gdpr_app;

-- Audit roles
\du
EOF

SSH Key-Based Authentication Enforcement:

# Disable password authentication for SSH
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config

# Enforce public key authentication
sudo sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config

# Disable root login
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config

# Restart SSH service
sudo systemctl restart sshd

# Verify configuration
sudo sshd -T | grep -E "(passwordauthentication|pubkeyauthentication|permitrootlogin)"

Step 4: Audit Logging and Monitoring

GDPR Article 30 requires maintaining records of processing activities. Comprehensive audit logging is essential for demonstrating compliance, investigating incidents, and detecting unauthorized access.

Configure Auditd for GDPR Compliance:

# Install auditd
sudo apt-get install -y auditd audispd-plugins # Debian/Ubuntu
sudo yum install -y audit audispd-plugins # RHEL/CentOS

# Start and enable auditd
sudo systemctl enable auditd
sudo systemctl start auditd

# Configure audit rules for GDPR
sudo tee -a /etc/audit/rules.d/gdpr.rules << 'EOF'
# GDPR Audit Rules

# Monitor personal data directory access
-w /opt/personal_data/ -p wa -k gdpr_data_access
-w /var/www/html/uploads/ -p wa -k gdpr_uploads

# Monitor database files
-w /var/lib/mysql/ -p wa -k gdpr_database_access
-w /var/lib/postgresql/ -p wa -k gdpr_pg_access

# Monitor user management
-w /etc/passwd -p wa -k gdpr_user_management
-w /etc/group -p wa -k gdpr_group_management
-w /etc/shadow -p wa -k gdpr_password_changes

# Monitor sudo usage
-w /etc/sudoers -p wa -k gdpr_sudo_changes
-w /etc/sudoers.d/ -p wa -k gdpr_sudo_changes

# Monitor SSH key changes
-w /home/*/.ssh/authorized_keys -p wa -k gdpr_ssh_keys
-w /root/.ssh/authorized_keys -p wa -k gdpr_ssh_keys

# Monitor backup operations
-w /var/backups/ -p wa -k gdpr_backups

# Monitor log deletions
-w /var/log/ -p wa -k gdpr_log_tampering

# Monitor encryption key access
-w /etc/mysql/encryption/ -p ra -k gdpr_encryption_keys

# System call auditing for file operations
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -k gdpr_file_deletion
-a always,exit -F arch=b64 -S open -S openat -F exit=-EACCES -k gdpr_access_denied
-a always,exit -F arch=b64 -S open -S openat -F exit=-EPERM -k gdpr_access_denied

# Make audit configuration immutable
-e 2
EOF

# Load audit rules
sudo augenrules --load

# Verify rules
sudo auditctl -l

# Check audit service status
sudo systemctl status auditd

Searching Audit Logs:

# Search for personal data access
sudo ausearch -k gdpr_data_access -i

# Search for failed access attempts
sudo ausearch -k gdpr_access_denied -i | tail -50

# Search for file deletions
sudo ausearch -k gdpr_file_deletion -i

# Generate audit report for specific time period
sudo ausearch -ts today -k gdpr_data_access --format csv > /tmp/gdpr_audit_$(date +%Y%m%d).csv

# Search for specific user activity
sudo ausearch -ua username -i

# Search for database access
sudo ausearch -k gdpr_database_access -i | tail -100

Application-Level Audit Logging:

# Create GDPR audit log structure
sudo mkdir -p /var/log/gdpr_audit
sudo chmod 700 /var/log/gdpr_audit

# Example audit logging script (to be called from applications)
cat > /usr/local/bin/gdpr_audit_log << 'EOF'
#!/bin/bash
# GDPR Audit Logging Script
# Usage: gdpr_audit_log "action" "user" "data_subject" "details"

LOG_FILE="/var/log/gdpr_audit/gdpr_actions.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
ACTION="$1"
USER="$2"
DATA_SUBJECT="$3"
DETAILS="$4"

echo "$TIMESTAMP|$ACTION|$USER|$DATA_SUBJECT|$DETAILS" >> "$LOG_FILE"
EOF

chmod +x /usr/local/bin/gdpr_audit_log

# Example usage from applications:
# gdpr_audit_log "DATA_ACCESS" "admin_user" "[email protected]" "Viewed user profile"
# gdpr_audit_log "DATA_EXPORT" "support_user" "customer123" "Exported data for GDPR request"
# gdpr_audit_log "DATA_DELETION" "dpo_user" "[email protected]" "Processed erasure request"

# Setup log rotation for GDPR audit logs
sudo tee /etc/logrotate.d/gdpr_audit << 'EOF'
/var/log/gdpr_audit/*.log {
    daily
    rotate 2555  # 7 years retention
    compress
    delaycompress
    notifempty
    create 0600 root root
    dateext
    dateformat -%Y%m%d
}
EOF

Database Query Logging:

# MySQL: Enable query logging for personal data access
sudo tee -a /etc/mysql/mariadb.conf.d/50-server.cnf << 'EOF'

# GDPR Query Logging
general_log = ON
general_log_file = /var/log/mysql/gdpr_queries.log
log_output = FILE

# Optionally log only queries affecting specific tables
# Note: This logs all queries, filter in analysis
EOF

sudo systemctl restart mysql

# PostgreSQL: Enable query logging
sudo -u postgres psql -c "ALTER SYSTEM SET log_destination = 'csvlog';"
sudo -u postgres psql -c "ALTER SYSTEM SET logging_collector = on;"
sudo -u postgres psql -c "ALTER SYSTEM SET log_directory = 'pg_log';"
sudo -u postgres psql -c "ALTER SYSTEM SET log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log';"
sudo -u postgres psql -c "ALTER SYSTEM SET log_statement = 'mod';" # Log all modifications
sudo -u postgres psql -c "ALTER SYSTEM SET log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h ';"

sudo systemctl restart postgresql

Step 5: Data Retention and Deletion Policies

GDPR requires that personal data be kept no longer than necessary. Implementing automated retention policies ensures compliance and reduces risk.

Implement Automated Data Retention:

# Create retention policy script
cat > /root/scripts/gdpr_retention_policy.sh << 'EOF'
#!/bin/bash
# GDPR Data Retention Policy Enforcement
# This script identifies and handles data past retention period

LOG_FILE="/var/log/gdpr_retention.log"
RETENTION_DAYS=1095  # 3 years default
ARCHIVE_DIR="/var/archives/gdpr"
DRY_RUN=false  # Set to true for testing

log_action() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Archive old logs
archive_old_logs() {
    log_action "Starting log archival process"

    find /var/log/application -name "*.log" -type f -mtime +$RETENTION_DAYS | while read file; do
        if [ "$DRY_RUN" = true ]; then
            log_action "DRY RUN: Would archive $file"
        else
            tar -czf "$ARCHIVE_DIR/$(basename $file)_$(date +%Y%m%d).tar.gz" "$file"
            shred -vfz -n 5 "$file"
            log_action "Archived and deleted: $file"
        fi
    done
}

# Clean old database records (example)
clean_old_database_records() {
    log_action "Starting database cleanup"

    CUTOFF_DATE=$(date -d "$RETENTION_DAYS days ago" '+%Y-%m-%d')

    if [ "$DRY_RUN" = true ]; then
        log_action "DRY RUN: Would delete records older than $CUTOFF_DATE"
        mysql -u root -p"$MYSQL_PASS" -e "
            SELECT COUNT(*) as 'Records to delete'
            FROM old_users
            WHERE last_login < '$CUTOFF_DATE'
            AND deletion_approved = 1;
        " your_database
    else
        # Backup before deletion
        mysqldump -u root -p"$MYSQL_PASS" your_database old_users \
            --where="last_login < '$CUTOFF_DATE'" > \
            "$ARCHIVE_DIR/deleted_users_$(date +%Y%m%d).sql"

        mysql -u root -p"$MYSQL_PASS" -e "
            DELETE FROM old_users
            WHERE last_login < '$CUTOFF_DATE'
            AND deletion_approved = 1;
        " your_database

        log_action "Deleted records older than $CUTOFF_DATE"
    fi
}

# Clean old backup files
clean_old_backups() {
    log_action "Starting backup cleanup"

    find /var/backups/user_data -name "*.sql.gz" -type f -mtime +$RETENTION_DAYS | while read file; do
        if [ "$DRY_RUN" = true ]; then
            log_action "DRY RUN: Would delete backup $file"
        else
            rm -f "$file"
            log_action "Deleted old backup: $file"
        fi
    done
}

# Main execution
mkdir -p "$ARCHIVE_DIR"
log_action "=== GDPR Retention Policy Run Started ==="
archive_old_logs
clean_old_database_records
clean_old_backups
log_action "=== GDPR Retention Policy Run Completed ==="

EOF

chmod +x /root/scripts/gdpr_retention_policy.sh

# Schedule retention policy enforcement (monthly)
sudo crontab -e
# Add: 0 2 1 * * /root/scripts/gdpr_retention_policy.sh

Secure Data Deletion Procedures:

# Create secure deletion script
cat > /usr/local/bin/gdpr_secure_delete << 'EOF'
#!/bin/bash
# GDPR Secure Deletion Script
# Usage: gdpr_secure_delete /path/to/file "reason" "data_subject_id"

if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <file_path> <reason> <data_subject_id>"
    exit 1
fi

FILE_PATH="$1"
REASON="$2"
DATA_SUBJECT="$3"
LOG_FILE="/var/log/gdpr_audit/deletions.log"

if [ ! -f "$FILE_PATH" ]; then
    echo "Error: File not found: $FILE_PATH"
    exit 1
fi

# Log deletion before proceeding
echo "$(date '+%Y-%m-%d %H:%M:%S')|DELETION|$(whoami)|$DATA_SUBJECT|$FILE_PATH|$REASON" >> "$LOG_FILE"

# Create checksum before deletion (for audit trail)
CHECKSUM=$(sha256sum "$FILE_PATH" | awk '{print $1}')
echo "$(date '+%Y-%m-%d %H:%M:%S')|CHECKSUM|$FILE_PATH|$CHECKSUM" >> "$LOG_FILE"

# Secure deletion
shred -vfz -n 10 "$FILE_PATH"

echo "$(date '+%Y-%m-%d %H:%M:%S')|DELETION_COMPLETE|$FILE_PATH" >> "$LOG_FILE"
echo "Secure deletion completed for: $FILE_PATH"

EOF

chmod +x /usr/local/bin/gdpr_secure_delete

# Example usage:
# gdpr_secure_delete /path/to/personal_data.csv "GDPR erasure request #12345" "[email protected]"

Step 6: Data Breach Detection and Response

GDPR requires organizations to detect and report personal data breaches within 72 hours. Implementing proactive monitoring and automated alerting is crucial.

Intrusion Detection Configuration:

# Install fail2ban for brute force detection
sudo apt-get install -y fail2ban # Debian/Ubuntu
sudo yum install -y fail2ban # RHEL/CentOS

# Configure fail2ban for GDPR-relevant services
sudo tee /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
destemail = [email protected]
sendername = GDPR Security Alert
action = %(action_mwl)s

[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3

[apache-auth]
enabled = true
port = http,https
logpath = /var/log/apache2/*error.log

[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log

[mysql-auth]
enabled = true
port = 3306
logpath = /var/log/mysql/error.log
maxretry = 3

EOF

sudo systemctl enable fail2ban
sudo systemctl restart fail2ban

# Monitor fail2ban status
sudo fail2ban-client status

Unauthorized Access Monitoring:

# Create security monitoring script
cat > /root/scripts/gdpr_security_monitor.sh << 'EOF'
#!/bin/bash
# GDPR Security Monitoring Script

ALERT_EMAIL="[email protected]"
LOG_FILE="/var/log/gdpr_security_monitor.log"

send_alert() {
    SUBJECT="$1"
    BODY="$2"
    echo "$BODY" | mail -s "$SUBJECT" "$ALERT_EMAIL"
    echo "$(date): ALERT SENT - $SUBJECT" >> "$LOG_FILE"
}

# Check for failed login attempts
FAILED_LOGINS=$(grep "Failed password" /var/log/auth.log | wc -l)
if [ "$FAILED_LOGINS" -gt 10 ]; then
    send_alert "GDPR Security Alert: High Failed Login Attempts" "Detected $FAILED_LOGINS failed login attempts. Potential breach attempt."
fi

# Check for unauthorized sudo usage
SUDO_FAILURES=$(grep "sudo.*FAILED" /var/log/auth.log | wc -l)
if [ "$SUDO_FAILURES" -gt 5 ]; then
    send_alert "GDPR Security Alert: Unauthorized Sudo Attempts" "Detected $SUDO_FAILURES failed sudo attempts."
fi

# Check for unexpected file access in personal data directories
UNEXPECTED_ACCESS=$(sudo ausearch -k gdpr_access_denied -ts today 2>/dev/null | wc -l)
if [ "$UNEXPECTED_ACCESS" -gt 0 ]; then
    send_alert "GDPR Security Alert: Unauthorized Data Access Attempts" "Detected $UNEXPECTED_ACCESS unauthorized access attempts to personal data."
fi

# Check for mass data exports (potential data exfiltration)
LARGE_EXPORTS=$(find /tmp -name "*.csv" -o -name "*.sql" -size +100M -mtime -1 2>/dev/null | wc -l)
if [ "$LARGE_EXPORTS" -gt 0 ]; then
    send_alert "GDPR Security Alert: Large Data Exports Detected" "Detected $LARGE_EXPORTS large data exports. Potential data exfiltration."
fi

# Check for unusual database queries
if [ -f /var/log/mysql/gdpr_queries.log ]; then
    BULK_SELECTS=$(grep -i "SELECT \*" /var/log/mysql/gdpr_queries.log | wc -l)
    if [ "$BULK_SELECTS" -gt 1000 ]; then
        send_alert "GDPR Security Alert: Unusual Database Activity" "Detected $BULK_SELECTS bulk SELECT queries. Potential data scraping."
    fi
fi

echo "$(date): Security monitoring check completed" >> "$LOG_FILE"

EOF

chmod +x /root/scripts/gdpr_security_monitor.sh

# Schedule security monitoring (every 15 minutes)
sudo crontab -e
# Add: */15 * * * * /root/scripts/gdpr_security_monitor.sh

File Integrity Monitoring:

# Install AIDE (Advanced Intrusion Detection Environment)
sudo apt-get install -y aide # Debian/Ubuntu
sudo yum install -y aide # RHEL/CentOS

# Configure AIDE for GDPR-critical directories
sudo tee -a /etc/aide/aide.conf << 'EOF'

# GDPR Critical Directories
/opt/personal_data R+b+sha256
/etc/mysql R+b+sha256
/var/www/html/user_uploads R+b+sha256
/root/scripts R+b+sha256

EOF

# Initialize AIDE database
sudo aideinit

# Check for changes
sudo aide --check

# Schedule daily integrity checks
echo "0 3 * * * /usr/bin/aide --check | mail -s 'AIDE Daily Report' [email protected]" | sudo crontab -

Auditing and Verification

Internal GDPR Compliance Audit

Regular internal audits ensure ongoing compliance and identify areas for improvement. Here's a comprehensive audit checklist with commands.

GDPR Compliance Audit Script:

cat > /root/scripts/gdpr_compliance_audit.sh << 'EOF'
#!/bin/bash
# GDPR Compliance Audit Script
# Generates a comprehensive compliance report

REPORT_FILE="/var/log/gdpr_audit/compliance_report_$(date +%Y%m%d).txt"
mkdir -p /var/log/gdpr_audit

exec > >(tee -a "$REPORT_FILE")
exec 2>&1

echo "========================================"
echo "GDPR COMPLIANCE AUDIT REPORT"
echo "Generated: $(date)"
echo "Hostname: $(hostname)"
echo "========================================"
echo ""

# 1. Encryption Status
echo "=== 1. ENCRYPTION STATUS ==="
echo "--- LUKS Encrypted Volumes ---"
lsblk -o NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT | grep -i crypt
echo ""
echo "--- MySQL Encryption Status ---"
mysql -u root -p -e "SHOW VARIABLES LIKE '%encrypt%';" 2>/dev/null || echo "Unable to check MySQL encryption"
echo ""
echo "--- SSL/TLS Certificates ---"
find /etc/ssl /etc/letsencrypt -name "*.crt" -o -name "*.pem" 2>/dev/null | head -10
echo ""

# 2. Access Controls
echo "=== 2. ACCESS CONTROLS ==="
echo "--- Users with Shell Access ---"
grep -v "/usr/sbin/nologin\|/bin/false" /etc/passwd | wc -l
echo ""
echo "--- Sudo Users ---"
getent group sudo wheel 2>/dev/null | cut -d: -f4
echo ""
echo "--- SSH Configuration ---"
grep -E "(PasswordAuthentication|PubkeyAuthentication|PermitRootLogin)" /etc/ssh/sshd_config
echo ""

# 3. Audit Logging
echo "=== 3. AUDIT LOGGING ==="
echo "--- Auditd Status ---"
systemctl is-active auditd
echo ""
echo "--- Active Audit Rules ---"
auditctl -l | wc -l
echo ""
echo "--- Recent Audit Events ---"
ausearch -k gdpr_data_access -ts today 2>/dev/null | wc -l
echo ""

# 4. Data Retention
echo "=== 4. DATA RETENTION ==="
echo "--- Old Log Files (>3 years) ---"
find /var/log -name "*.log" -mtime +1095 2>/dev/null | wc -l
echo ""
echo "--- Backup Files Age ---"
find /var/backups -type f -mtime +1095 2>/dev/null | wc -l
echo ""

# 5. Security Monitoring
echo "=== 5. SECURITY MONITORING ==="
echo "--- Fail2ban Status ---"
systemctl is-active fail2ban
fail2ban-client status 2>/dev/null | grep "Number of jail"
echo ""
echo "--- Recent Failed Login Attempts ---"
grep "Failed password" /var/log/auth.log 2>/dev/null | tail -10 | wc -l
echo ""

# 6. Data Discovery
echo "=== 6. DATA DISCOVERY ==="
echo "--- Databases Containing Personal Data ---"
mysql -u root -p -e "SELECT DISTINCT TABLE_SCHEMA FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME REGEXP 'email|phone|address' AND TABLE_SCHEMA NOT IN ('information_schema', 'mysql', 'performance_schema');" 2>/dev/null
echo ""

# 7. Patch Status
echo "=== 7. SYSTEM SECURITY UPDATES ==="
if command -v apt &> /dev/null; then
    apt list --upgradable 2>/dev/null | wc -l
elif command -v yum &> /dev/null; then
    yum check-update 2>/dev/null | wc -l
fi
echo ""

# 8. Network Security
echo "=== 8. NETWORK SECURITY ==="
echo "--- Open Ports ---"
ss -tulpn | grep LISTEN | wc -l
echo ""
echo "--- Firewall Status ---"
if command -v ufw &> /dev/null; then
    ufw status
elif command -v firewall-cmd &> /dev/null; then
    firewall-cmd --state
else
    iptables -L -n | head -10
fi
echo ""

# 9. Documentation Status
echo "=== 9. DOCUMENTATION ==="
echo "--- GDPR Documentation Files ---"
find /root/gdpr_docs -type f 2>/dev/null | wc -l
echo ""

# 10. Incident Response Readiness
echo "=== 10. INCIDENT RESPONSE ==="
echo "--- Security Monitoring Scripts ---"
ls -l /root/scripts/gdpr_*.sh 2>/dev/null | wc -l
echo ""
echo "--- Alert Configuration ---"
grep -r "ALERT\|security@" /root/scripts/*.sh 2>/dev/null | wc -l
echo ""

echo "========================================"
echo "AUDIT COMPLETED: $(date)"
echo "Report saved to: $REPORT_FILE"
echo "========================================"

EOF

chmod +x /root/scripts/gdpr_compliance_audit.sh

# Run the audit
/root/scripts/gdpr_compliance_audit.sh

External Audit Preparation

When preparing for external audits or Data Protection Authority (DPA) inspections, you need to provide comprehensive evidence of compliance.

Evidence Collection Script:

cat > /root/scripts/gdpr_evidence_collection.sh << 'EOF'
#!/bin/bash
# GDPR Evidence Collection for External Audit
# Creates a comprehensive evidence package

EVIDENCE_DIR="/tmp/gdpr_evidence_$(date +%Y%m%d)"
mkdir -p "$EVIDENCE_DIR"/{configs,logs,reports,documentation}

echo "Collecting GDPR compliance evidence..."

# 1. System Configuration
echo "Collecting system configurations..."
cp /etc/ssh/sshd_config "$EVIDENCE_DIR/configs/"
cp /etc/mysql/mariadb.conf.d/50-server.cnf "$EVIDENCE_DIR/configs/" 2>/dev/null
cp /etc/audit/rules.d/gdpr.rules "$EVIDENCE_DIR/configs/" 2>/dev/null
cp /etc/fail2ban/jail.local "$EVIDENCE_DIR/configs/" 2>/dev/null

# 2. Audit Logs (last 30 days, anonymized)
echo "Collecting audit logs..."
ausearch -k gdpr_data_access -ts recent | head -1000 > "$EVIDENCE_DIR/logs/audit_data_access.log"
ausearch -k gdpr_file_deletion -ts recent | head -1000 > "$EVIDENCE_DIR/logs/audit_deletions.log"
tail -1000 /var/log/gdpr_audit/gdpr_actions.log > "$EVIDENCE_DIR/logs/gdpr_actions.log" 2>/dev/null

# 3. Security Reports
echo "Generating security reports..."
/root/scripts/gdpr_compliance_audit.sh > "$EVIDENCE_DIR/reports/compliance_audit.txt"
lynis audit system --quick > "$EVIDENCE_DIR/reports/lynis_security_audit.txt" 2>/dev/null

# 4. Access Control Reports
echo "Collecting access control information..."
getent passwd | awk -F: '$3 >= 1000 {print $1}' > "$EVIDENCE_DIR/reports/system_users.txt"
for user in $(cat "$EVIDENCE_DIR/reports/system_users.txt"); do
    groups "$user" >> "$EVIDENCE_DIR/reports/user_groups.txt"
done

# 5. Data Retention Evidence
echo "Documenting data retention policies..."
cat /root/scripts/gdpr_retention_policy.sh > "$EVIDENCE_DIR/documentation/retention_policy.sh"
tail -100 /var/log/gdpr_retention.log > "$EVIDENCE_DIR/logs/retention_enforcement.log" 2>/dev/null

# 6. Encryption Evidence
echo "Documenting encryption status..."
lsblk -o NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT > "$EVIDENCE_DIR/reports/disk_encryption.txt"
mysql -u root -p -e "SHOW VARIABLES LIKE '%encrypt%';" > "$EVIDENCE_DIR/reports/mysql_encryption.txt" 2>/dev/null

# 7. Create summary report
cat > "$EVIDENCE_DIR/SUMMARY.txt" << SUMMARY
GDPR Compliance Evidence Package
Generated: $(date)
Hostname: $(hostname)
Collected by: $(whoami)

Contents:
- configs/: System configuration files demonstrating security controls
- logs/: Anonymized audit logs showing monitoring and access tracking
- reports/: Compliance audit results and security assessments
- documentation/: Policy scripts and procedures

This evidence package demonstrates technical compliance measures
implemented on this Linux server in accordance with GDPR requirements.

SUMMARY

# Create archive
echo "Creating evidence archive..."
tar -czf "/root/gdpr_evidence_$(date +%Y%m%d).tar.gz" -C /tmp "gdpr_evidence_$(date +%Y%m%d)"

echo "Evidence collection completed!"
echo "Archive location: /root/gdpr_evidence_$(date +%Y%m%d).tar.gz"
echo "Please encrypt this archive before transmission to auditors."

# Cleanup
rm -rf "$EVIDENCE_DIR"

EOF

chmod +x /root/scripts/gdpr_evidence_collection.sh

Documentation Requirements

GDPR requires extensive documentation of processing activities, technical measures, and compliance procedures. Here are templates and scripts for maintaining required documentation.

Record of Processing Activities (ROPA)

Automated ROPA Generator:

cat > /root/scripts/generate_ropa.sh << 'EOF'
#!/bin/bash
# Generate Record of Processing Activities

ROPA_FILE="/root/gdpr_docs/ROPA_$(date +%Y%m%d).md"
mkdir -p /root/gdpr_docs

cat > "$ROPA_FILE" << 'ROPA'
# Record of Processing Activities (ROPA)
Generated: $(date)
Server: $(hostname)

## Processing Activity 1: User Account Management

**Purpose**: Maintain user accounts for application access
**Legal Basis**: Contract performance
**Categories of Data Subjects**: Application users, customers
**Categories of Personal Data**:
- Identity data (name, username)
- Contact data (email, phone)
- Account data (registration date, last login)

**Recipients**: Internal technical team only
**Transfers to Third Countries**: None
**Retention Period**: 3 years after account closure
**Technical and Organizational Measures**:
- Data encryption at rest (LUKS)
- Access control (RBAC with dedicated groups)
- Audit logging (auditd)
- Regular backups (encrypted)
- Secure deletion procedures

**Storage Location**: /var/lib/mysql/application_db/users table
**Responsible Person**: System Administrator

---

## Processing Activity 2: Application Logs

**Purpose**: System monitoring, troubleshooting, security monitoring
**Legal Basis**: Legitimate interest
**Categories of Data Subjects**: All users accessing the system
**Categories of Personal Data**:
- IP addresses
- Access timestamps
- User agent strings
- Authentication events

**Recipients**: Technical team, security team
**Transfers to Third Countries**: None
**Retention Period**: 90 days (standard logs), 7 years (security logs)
**Technical and Organizational Measures**:
- Log rotation with logrotate
- Access restricted to authorized personnel only
- Encrypted backup storage
- Automated retention policy enforcement

**Storage Location**: /var/log/application/, /var/log/nginx/
**Responsible Person**: System Administrator

---

## Processing Activity 3: Database Backups

**Purpose**: Disaster recovery, business continuity
**Legal Basis**: Legitimate interest
**Categories of Data Subjects**: All application users
**Categories of Personal Data**: All data contained in production databases
**Recipients**: Backup administrators only
**Transfers to Third Countries**: None
**Retention Period**: 30 days (daily backups), 1 year (monthly backups)
**Technical and Organizational Measures**:
- Encrypted backups (GPG encryption)
- Secure off-site storage
- Access control (restricted directory permissions)
- Regular backup testing
- Automated deletion of expired backups

**Storage Location**: /var/backups/encrypted/
**Responsible Person**: Backup Administrator

---

ROPA

echo "ROPA generated: $ROPA_FILE"

EOF

chmod +x /root/scripts/generate_ropa.sh
/root/scripts/generate_ropa.sh

Data Processing Agreement (DPA) Checklist

When using third-party services or processors, GDPR requires Data Processing Agreements. Use this checklist to verify technical compliance:

cat > /root/gdpr_docs/DPA_Technical_Checklist.md << 'EOF'
# Data Processing Agreement Technical Checklist

## For Each Third-Party Service/Processor

### 1. Data Transfer Verification
- [ ] Identify all data sent to third-party (types, volume, frequency)
- [ ] Verify legal basis for transfer
- [ ] Confirm third-party's data processing agreement signed
- [ ] Document Standard Contractual Clauses (SCCs) if applicable

**Commands to identify external connections**:
```bash
# List all external network connections
sudo netstat -tupn | grep ESTABLISHED | grep -v "127.0.0.1\|::1"

# Identify services connecting to external APIs
sudo lsof -i -P -n | grep ESTABLISHED

# Check application configs for third-party integrations
grep -r "api\|endpoint\|external" /etc/nginx /etc/apache2 /var/www

2. Encryption in Transit

  • All connections to third-parties use TLS 1.2 or higher
  • Certificate validation enabled
  • No data sent over unencrypted channels

Verification commands:

# Test TLS connection to third-party
openssl s_client -connect api.thirdparty.com:443 -tls1_2

# Check nginx/apache SSL configuration
grep -r "ssl_protocols" /etc/nginx /etc/apache2

3. Access Controls for Third-Party Access

  • Third-party has minimum necessary access only
  • Dedicated service accounts for third-party access
  • Access logged and monitored

4. Data Minimization

  • Only necessary data sent to third-party
  • Unnecessary fields filtered/removed before transmission
  • Data sanitization applied where appropriate

5. Processor Security Assessment

  • Third-party security certifications verified (ISO 27001, SOC 2)
  • Sub-processor list obtained and approved
  • Breach notification procedures agreed

6. Audit Rights

  • Right to audit third-party's processing verified
  • Access to third-party logs/reports established
  • Compliance verification procedures documented

EOF


### Privacy Impact Assessment (PIA) Technical Components

```bash
cat > /root/gdpr_docs/PIA_Technical_Template.md << 'EOF'
# Privacy Impact Assessment - Technical Components

## System Overview
**System Name**: [Application/Service Name]
**Data Processed**: [Types of personal data]
**Processing Purpose**: [Primary purpose]
**Assessment Date**: $(date)

## Technical Risk Assessment

### 1. Data Collection
**Risk**: Excessive data collection
**Mitigation**:
- [ ] Form validation limits data collected
- [ ] No optional fields pre-checked
- [ ] Clear purpose stated for each data field

**Technical Evidence**:
```bash
# Review form fields in application code
grep -r "input\|form" /var/www/html/application/forms/

2. Data Storage

Risk: Insecure storage of personal data Mitigation:

  • Database encryption at rest enabled
  • File system encryption for sensitive data
  • Secure backup encryption

Technical Evidence:

# Verify encryption status
lsblk -o NAME,TYPE,FSTYPE,MOUNTPOINT | grep crypt
mysql -e "SHOW VARIABLES LIKE 'innodb_encrypt%';"

3. Data Access

Risk: Unauthorized access to personal data Mitigation:

  • Role-based access control implemented
  • Multi-factor authentication for administrative access
  • Access logging enabled

Technical Evidence:

# Review access controls
ls -la /opt/personal_data/
getent group gdpr_data_admin

4. Data Transmission

Risk: Interception of data in transit Mitigation:

  • TLS 1.2+ enforced for all connections
  • HTTPS redirect in place
  • HSTS header configured

Technical Evidence:

# Check SSL/TLS configuration
testssl.sh --fast https://yourdomain.com
curl -I https://yourdomain.com | grep -i strict

5. Data Retention

Risk: Excessive data retention Mitigation:

  • Automated retention policy enforced
  • Regular cleanup of old data
  • Secure deletion procedures

Technical Evidence:

# Review retention policy script
cat /root/scripts/gdpr_retention_policy.sh
# Check last execution
ls -l /var/log/gdpr_retention.log

6. Breach Detection

Risk: Delayed breach detection Mitigation:

  • Real-time monitoring and alerting
  • Intrusion detection system deployed
  • Log analysis automated

Technical Evidence:

# Verify monitoring systems
systemctl status fail2ban
ps aux | grep monitor

7. Data Subject Rights

Risk: Inability to fulfill data subject requests Mitigation:

  • Data search procedures implemented
  • Export functionality available
  • Secure deletion tools deployed

Technical Evidence:

# Test data search capability
/usr/local/bin/gdpr_data_search [email protected] --dry-run

Overall Risk Rating

  • Low Risk: Basic personal data, strong controls
  • Medium Risk: Sensitive data or moderate controls
  • High Risk: Special category data or weak controls

Required Actions

  1. [Action item with responsible person and deadline]
  2. [Action item with responsible person and deadline]

Approval

Assessed by: [Name] Date: $(date) Next Review: [Date]

EOF


## Maintenance and Continuous Compliance

GDPR compliance is not a one-time project but an ongoing process requiring regular maintenance, updates, and reviews.

### Monthly Compliance Tasks

```bash
# Create monthly compliance task script
cat > /root/scripts/gdpr_monthly_tasks.sh << 'EOF'
#!/bin/bash
# GDPR Monthly Compliance Tasks

REPORT_FILE="/var/log/gdpr_audit/monthly_tasks_$(date +%Y%m).txt"

exec > >(tee -a "$REPORT_FILE")
exec 2>&1

echo "========================================"
echo "GDPR MONTHLY COMPLIANCE TASKS"
echo "Date: $(date)"
echo "========================================"
echo ""

# Task 1: Review access logs for anomalies
echo "Task 1: Access Log Review"
echo "Checking for unusual access patterns..."
UNUSUAL_ACCESS=$(ausearch -k gdpr_access_denied -ts this-month | wc -l)
echo "Denied access attempts this month: $UNUSUAL_ACCESS"
if [ "$UNUSUAL_ACCESS" -gt 50 ]; then
    echo "WARNING: High number of denied access attempts detected!"
fi
echo ""

# Task 2: Verify encryption status
echo "Task 2: Encryption Status Verification"
echo "Checking encrypted volumes..."
lsblk -o NAME,TYPE,FSTYPE,MOUNTPOINT | grep crypt | wc -l
echo "Checking database encryption..."
mysql -u root -p -e "SHOW VARIABLES LIKE 'innodb_encrypt_tables';" 2>/dev/null
echo ""

# Task 3: Review user access
echo "Task 3: User Access Review"
echo "Users with system access:"
getent passwd | awk -F: '$3 >= 1000 {print $1}' | wc -l
echo "Users with sudo privileges:"
grep -rE "^%sudo|^%wheel" /etc/sudoers /etc/sudoers.d/ 2>/dev/null | wc -l
echo "Review these users to ensure only authorized personnel have access."
echo ""

# Task 4: Data retention compliance check
echo "Task 4: Data Retention Compliance"
echo "Files exceeding retention period (>3 years):"
find /var/log -name "*.log" -mtime +1095 2>/dev/null | wc -l
echo "These should be archived or securely deleted."
echo ""

# Task 5: Backup verification
echo "Task 5: Backup Verification"
echo "Recent backup files:"
find /var/backups -name "*.tar.gz" -o -name "*.sql.gz" -mtime -31 2>/dev/null | wc -l
echo "Testing latest backup integrity..."
# Add backup restoration test here
echo ""

# Task 6: Security update status
echo "Task 6: Security Updates"
echo "Pending security updates:"
if command -v apt &> /dev/null; then
    apt list --upgradable 2>/dev/null | grep -i security | wc -l
elif command -v yum &> /dev/null; then
    yum check-update --security 2>/dev/null | wc -l
fi
echo ""

# Task 7: Incident review
echo "Task 7: Security Incident Review"
echo "Fail2ban bans this month:"
fail2ban-client status sshd 2>/dev/null | grep "Currently banned" || echo "Fail2ban not configured"
echo ""

# Task 8: Documentation update check
echo "Task 8: Documentation Currency"
echo "Last ROPA update:"
ls -l /root/gdpr_docs/ROPA_*.md 2>/dev/null | tail -1 | awk '{print $6, $7, $8}'
echo "Documentation should be reviewed and updated if any processing activities have changed."
echo ""

echo "========================================"
echo "MONTHLY TASKS COMPLETED"
echo "Report saved to: $REPORT_FILE"
echo "========================================"

EOF

chmod +x /root/scripts/gdpr_monthly_tasks.sh

# Schedule monthly execution
echo "0 9 1 * * /root/scripts/gdpr_monthly_tasks.sh | mail -s 'GDPR Monthly Tasks Report' [email protected]" | sudo crontab -

Quarterly Compliance Review

# Create quarterly compliance review script
cat > /root/scripts/gdpr_quarterly_review.sh << 'EOF'
#!/bin/bash
# GDPR Quarterly Compliance Review

REPORT_DIR="/var/log/gdpr_audit/quarterly_$(date +%Y_Q%q)"
mkdir -p "$REPORT_DIR"

echo "Generating quarterly GDPR compliance review..."

# Generate comprehensive reports
/root/scripts/gdpr_compliance_audit.sh > "$REPORT_DIR/compliance_audit.txt"
/root/scripts/gdpr_evidence_collection.sh
/root/scripts/generate_ropa.sh

# Additional quarterly checks
cat > "$REPORT_DIR/quarterly_checklist.txt" << 'CHECKLIST'
GDPR Quarterly Compliance Checklist
Generated: $(date)

MANAGEMENT REVIEW
[ ] Review all data processing activities - any changes?
[ ] Review third-party processors - any new vendors?
[ ] Review data breach log - any incidents this quarter?
[ ] Review data subject requests - response times acceptable?
[ ] Review staff training records - all staff trained?

TECHNICAL REVIEW
[ ] Run full compliance audit - any issues identified?
[ ] Test backup restoration - successful?
[ ] Review access control lists - any unauthorized access?
[ ] Check encryption status - all systems encrypted?
[ ] Review audit logs - any anomalies?
[ ] Test incident response procedures - are they current?
[ ] Update documentation - all changes captured?

POLICY REVIEW
[ ] Review data retention policy - still appropriate?
[ ] Review security policy - any updates needed?
[ ] Review privacy policy - aligned with practices?
[ ] Review DPAs with processors - all current?

ACTION ITEMS FROM THIS REVIEW
1.
2.
3.

NEXT REVIEW DATE: [Add 3 months]

CHECKLIST

echo "Quarterly review materials generated in: $REPORT_DIR"
echo "Please complete the checklist and document any required actions."

EOF

chmod +x /root/scripts/gdpr_quarterly_review.sh

Annual Compliance Certification

# Create annual compliance certification script
cat > /root/scripts/gdpr_annual_certification.sh << 'EOF'
#!/bin/bash
# GDPR Annual Compliance Certification

CERT_DIR="/root/gdpr_docs/annual_certification_$(date +%Y)"
mkdir -p "$CERT_DIR"

echo "Generating annual GDPR compliance certification package..."

# 1. Full compliance audit
echo "Running comprehensive compliance audit..."
/root/scripts/gdpr_compliance_audit.sh > "$CERT_DIR/full_compliance_audit.txt"

# 2. Generate annual reports
echo "Collecting annual statistics..."

cat > "$CERT_DIR/annual_report.txt" << REPORT
GDPR ANNUAL COMPLIANCE REPORT
Year: $(date +%Y)
Server: $(hostname)

=== PROCESSING ACTIVITIES ===
$(cat /root/gdpr_docs/ROPA_*.md | grep "## Processing Activity" | wc -l) documented processing activities

=== DATA SUBJECT REQUESTS ===
Access requests: $(grep "DATA_ACCESS" /var/log/gdpr_audit/gdpr_actions.log 2>/dev/null | wc -l)
Erasure requests: $(grep "DATA_DELETION" /var/log/gdpr_audit/gdpr_actions.log 2>/dev/null | wc -l)
Export requests: $(grep "DATA_EXPORT" /var/log/gdpr_audit/gdpr_actions.log 2>/dev/null | wc -l)

Average response time: [Manual calculation required]

=== SECURITY INCIDENTS ===
Detected incidents: $(grep "ALERT" /var/log/gdpr_security_monitor.log 2>/dev/null | wc -l)
Data breaches: [Manual verification required]
Breaches reported to DPA: [Manual verification required]

=== TECHNICAL MEASURES ===
Encryption: $(lsblk | grep crypt | wc -l) encrypted volumes
Audit rules: $(auditctl -l | wc -l) active rules
Access controls: $(getent group | grep gdpr | wc -l) GDPR-specific groups
Monitoring: Active

=== TRAINING ===
Staff trained on GDPR: [Manual verification required]
Last training date: [Manual input required]

=== PROCESSOR MANAGEMENT ===
Active data processors: [Manual count required]
DPAs signed: [Manual verification required]
Processor audits completed: [Manual verification required]

=== COMPLIANCE STATUS ===
Overall assessment: [COMPLIANT / NON-COMPLIANT / PARTIALLY COMPLIANT]

Key strengths:
- [List key compliance strengths]

Areas for improvement:
- [List areas needing attention]

Actions planned for next year:
- [List planned improvements]

CERTIFICATION
I certify that this report accurately represents the GDPR compliance status
of this system as of $(date).

Name: [To be completed by DPO]
Signature: _______________
Date: $(date)

REPORT

# 3. Collect evidence
echo "Collecting supporting evidence..."
cp /var/log/gdpr_audit/compliance_report_*.txt "$CERT_DIR/" 2>/dev/null
cp /root/gdpr_docs/ROPA_*.md "$CERT_DIR/" 2>/dev/null
cp /root/gdpr_docs/DPA_*.md "$CERT_DIR/" 2>/dev/null

# 4. Create certification package
echo "Creating certification archive..."
tar -czf "/root/gdpr_annual_certification_$(date +%Y).tar.gz" -C /root "gdpr_docs/annual_certification_$(date +%Y)"

echo "Annual certification package completed!"
echo "Location: /root/gdpr_annual_certification_$(date +%Y).tar.gz"
echo "Please review, complete manual sections, and obtain DPO signature."

EOF

chmod +x /root/scripts/gdpr_annual_certification.sh

Conclusion

GDPR compliance on Linux servers requires a comprehensive, multi-layered approach combining technical controls, organizational processes, and continuous monitoring. This guide has provided you with practical, command-line driven implementations of essential GDPR requirements, from data discovery and encryption to access controls, audit logging, and incident response.

Key Takeaways

1. Compliance is Continuous: GDPR is not a one-time project. Regular auditing, monitoring, and updates are essential to maintain compliance as systems, data, and regulations evolve.

2. Documentation is Critical: Comprehensive documentation of processing activities, technical measures, and compliance efforts is not just a legal requirement but essential evidence of your accountability under GDPR.

3. Automation is Your Ally: Automated scripts for retention policies, monitoring, auditing, and reporting reduce human error and ensure consistent application of compliance measures.

4. Encryption is Fundamental: Both data at rest and in transit must be encrypted. Use LUKS for disk encryption, enable database encryption features, and ensure all network communications use TLS 1.2 or higher.

5. Access Control is Non-Negotiable: Implement principle of least privilege, use role-based access controls, enforce strong authentication, and regularly review access permissions.

6. Audit Everything: Comprehensive audit logging with auditd, application logs, database query logs, and security monitoring provides the evidence needed to demonstrate compliance and detect breaches.

7. Be Prepared for Breaches: Despite best efforts, breaches can occur. Having detection mechanisms, response procedures, and notification processes in place is essential for GDPR compliance.

Next Steps

  1. Immediate Actions:

    • Run the data discovery script to identify all personal data on your servers
    • Implement encryption for any unencrypted personal data
    • Configure auditd with GDPR-specific rules
    • Set up automated monitoring and alerting
  2. Short-term Actions (1-3 months):

    • Complete documentation of all processing activities (ROPA)
    • Implement automated retention policies
    • Conduct internal compliance audit
    • Train staff on GDPR technical requirements
  3. Long-term Actions:

    • Schedule regular compliance reviews (monthly, quarterly, annual)
    • Continuously improve security posture
    • Stay updated on GDPR guidance and enforcement actions
    • Consider professional GDPR audit or certification

Additional Resources

  • GDPR Official Text: EUR-Lex - GDPR
  • European Data Protection Board (EDPB) Guidelines: edpb.europa.eu
  • ICO GDPR Guidance: ico.org.uk/gdpr
  • NIST Cybersecurity Framework: Complementary security guidance
  • CIS Benchmarks: Linux hardening guidelines that support GDPR technical measures

Final Thoughts

GDPR compliance represents a significant but worthwhile investment in data protection and security. The technical measures required by GDPR align closely with general security best practices, meaning your compliance efforts simultaneously improve your overall security posture. By implementing the procedures and scripts in this guide, you'll not only achieve GDPR compliance but also build a more secure, auditable, and trustworthy infrastructure.

Remember that GDPR compliance is as much about culture and processes as it is about technology. Technical controls must be accompanied by organizational commitment, staff training, clear policies, and continuous improvement. As a Linux system administrator, you play a crucial role in protecting personal data and ensuring your organization meets its legal obligations under GDPR.

Stay vigilant, keep learning, and maintain the principle that privacy and data protection are fundamental rights worth protecting through excellent technical implementation and operational discipline.