Encryption and GPG
Chapter 36: Encryption and GPG
Section titled “Chapter 36: Encryption and GPG”Overview
Section titled “Overview”Encryption is the cornerstone of Linux system security. This chapter covers symmetric and asymmetric encryption, GPG key management, disk encryption with LUKS, filesystem-level encryption, and practical production implementations. Mastery of these topics is essential for DevOps and SRE roles securing sensitive data.
Why This Matters in DevOps/SRE
Section titled “Why This Matters in DevOps/SRE”Encryption is fundamental for data protection and compliance:
Encryption for DevOps/SRE+------------------------------------------------------------------+| || Data Protection: || +----------------------------------------------------------+ || | LUKS → Full disk encryption for servers | || | GPG → Sign/verify packages, encrypt secrets | || | TLS → Secure network communication | || | Vault → Secrets management for applications | || +----------------------------------------------------------+ || || Compliance: || +----------------------------------------------------------+ || | PCI-DSS → Encryption at rest required | || | GDPR → Personal data must be encrypted | || | HIPAA → PHI must be encrypted | || +----------------------------------------------------------+ || || DevOps Practices: || +----------------------------------------------------------+ || | SOPS → Encrypted secrets in Git | || | Vault → Dynamic secrets for apps | || | TLS certificates → Automated renewal | || | GPG signing → Verify package integrity | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Practical Impact:
- Protect data at rest on servers and laptops
- Secure secrets management in CI/CD pipelines
- Meet compliance requirements (PCI-DSS, GDPR, HIPAA)
- Verify package integrity and authenticity
36.1 Encryption Fundamentals
Section titled “36.1 Encryption Fundamentals”Types of Encryption
Section titled “Types of Encryption”┌─────────────────────────────────────────────────────────────────────────┐│ ENCRYPTION TYPES │├─────────────────────────────────────────────────────────────────────────┤│ ││ SYMMETRIC ASYMMETRIC ││ ┌─────────┐ ┌─────────┐ ┌─────────┐ ││ │ AES │ │ RSA │ │ ECC │ ││ │ 256 │ │ 4096-bit│ │ 384-bit│ ││ └────┬────┘ └────┬────┘ └────┬────┘ ││ │ │ │ ││ └───────────┬────────────┴───────────────┘ ││ │ ││ ┌───────▼───────┐ ││ │ Same Key │ Fast, for bulk data ││ │ Encrypt/ │ (files, disks) ││ │ Decrypt │ ││ └─────────────┘ ││ ││ HYBRID (Common Practice) ││ ┌─────────────────────────────────────────────────────────┐ ││ │ 1. Generate random symmetric key (AES) │ ││ │ 2. Encrypt data with symmetric key (fast) │ ││ │ 3. Encrypt symmetric key with recipient's public key │ ││ │ 4. Send both encrypted key + encrypted data │ ││ └─────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────┘Key Sizes and Strength
Section titled “Key Sizes and Strength”| Algorithm | Key Size | Use Case | Security Level |
|---|---|---|---|
| AES-128 | 128-bit | Legacy systems | Adequate |
| AES-256 | 256-bit | Standard | Very Strong |
| RSA-2048 | 2048-bit | Signatures, key exchange | Standard |
| RSA-4096 | 4096-bit | High security | Very Strong |
| ECC-256 | 256-bit | Mobile/embedded | Equivalent to RSA-3072 |
| ChaCha20 | 256-bit | Modern, TLS | Very Strong |
36.2 GPG (GNU Privacy Guard)
Section titled “36.2 GPG (GNU Privacy Guard)”GPG Architecture
Section titled “GPG Architecture”┌─────────────────────────────────────────────────────────────────────────┐│ GPG ECOSYSTEM │├─────────────────────────────────────────────────────────────────────────┤│ ││ KEY GENERATION ││ ┌────────────────────────────────────────────────────────────┐ ││ │ ┌──────────────┐ ┌──────────────┐ │ ││ │ │ Master Key │ │ Subkeys │ │ ││ │ │ (Certification) │ (Signing/ │ │ ││ │ │ - Sign other keys │ Encryption/ │ │ ││ │ │ - Create subkeys │ Authentication│ │ ││ │ └──────────────┘ └──────────────┘ │ ││ └────────────────────────────────────────────────────────────┘ ││ ││ KEYRING STRUCTURE ││ ~/.gnupg/ ││ ├── pubring.kbx (Public keys + signatures) ││ ├── pubring.gpg (Legacy public keyring) ││ ├── secring.gpg (Secret keys - DEPRECATED) ││ ├── private-keys-v1.d/ (Secret key stubs for gpg-agent) ││ ├── gpg.conf (Options) ││ ├── gpg-agent.conf (Agent options) ││ └── trustdb.gpg (Ownertrust values) ││ ││ OPERATIONS ││ ┌────────────────────────────────────────────────────────────┐ ││ │ ENCRYPT DECRYPT │ ││ │ ┌─────────┐ ┌─────────┐ │ ││ │ │Message │ │ Encrypted│ │ ││ │ │ File │──►Encrypt──► │ Data │──►Decrypt──►Message │ ││ │ └─────────┘ with RSA └─────────┘ with RSA └─────────┘ ││ │ │ (needs private key) ││ │ │ │ ││ │ ┌────▼────┐ ┌────▼────┐ │ ││ │ │Public │ │Private │ │ ││ │ │Key of │ │Key of │ │ ││ │ │Receiver │ │Receiver │ │ ││ │ └─────────┘ └─────────┘ │ ││ └────────────────────────────────────────────────────────────┘ ││ ││ SIGNING VERIFICATION ││ ┌────────────────────────────────────────────────────────────┐ ││ │ SIGN VERIFY │ ││ │ ┌─────────┐ ┌─────────┐ │ ││ │ │Message/ │──►Sign──► │Signature│──►Verify──► Valid/Invalid│ ││ │ │ File │ with RSA │ (.sig) │ with public key │ ││ │ └─────────┘ Private └─────────┘ │ ││ └────────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────┘Key Generation Best Practices
Section titled “Key Generation Best Practices”# ============================================================# PRODUCTION KEY GENERATION - Step by Step# ============================================================
# Step 1: Configure GPG for better securitymkdir -p ~/.gnupgchmod 700 ~/.gnupg
cat > ~/.gnupg/gpg.conf << 'EOF'# Use modern algorithmsdefault-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES168BZIP2 ZLIB ZIP Uncompressed
# Modern keyserverkeyserver hkps://keyserver.ubuntu.com
# Security optionsno-ttyno-emit-versionno-comments
# Fast options (if needed for automation)# use-agentEOF
cat > ~/.gnupg/gpg-agent.conf << 'EOF'default-cache-ttl 600max-cache-ttl 3600allow-loopback-pinentryEOF
# Step 2: Generate master key (Certification only)gpg --full-generate-key# Select:# 1. RSA and RSA (default)# 2. 4096 bits# 3. Key does not expire (or set reasonable expiry)# 4. Your name# 5. Your email# 6. Passphrase (use a strong, unique password)
# Step 3: Add subkeys for daily usegpg --edit-key your@email.com
# In gpg> interactive mode:# addkey# 4. RSA (sign only) - 4096 bits# Save# addkey# 5. RSA (encrypt only) - 4096 bits# Save# addkey# 6. Authentication - 4096 bits# Save# quit
# Step 4: Backup your keys (CRITICAL!)# Export master key (keep secure!)gpg --armor --export-secret-keys your@email.com > master-key-backup.ascgpg --armor --export-secret-subkeys your@email.com > subkeys-backup.asc
# Store these securely (encrypted USB, secure location)# DELETE the secret keys from your machine after backup!
# Step 5: Export public key for distributiongpg --armor --export your@email.com > public-key.ascgpg --send-keys your@email.com # Upload to keyserverKey Management Operations
Section titled “Key Management Operations”# ============================================================# KEY MANAGEMENT COMMANDS# ============================================================
# List keysgpg --list-keys # Public keysgpg --list-secret-keys # Private keysgpg --list-signatures # Signatures on keysgpg --fingerprint your@email.com # Fingerprint (short form)
# Keyserver operationsgpg --keyserver keyserver.ubuntu.com --search-keys "search term"gpg --keyserver keyserver.ubuntu.com --recv-key KEYIDgpg --keyserver keyserver.ubuntu.com --send-key KEYIDgpg --refresh-keys # Update all keys from keyserver
# Key editinggpg --edit-key your@email.com# Commands: list, uid, key, addkey, delkey, revuid, sign, check, quit
# Change passphrasegpg --change-passphrase your@email.com
# Expire keygpg --edit-key your@email.com# gpg> expire# gpg> save
# Sign a key (establishing trust)gpg --sign-key other@email.com # Sign with your keygpg --lsign-key other@email.com # Local signature (not exported)
# Export/Importgpg --armor --export your@email.com > public.ascgpg --armor --export-secret-keys your@email.com > private.ascgpg --import keyfile.ascgpg --import --import-filter import-clean-sigs keyfile.asc
# Delete keysgpg --delete-secret-keys your@email.com # First delete secretgpg --delete-keys your@email.com # Then publicFile Encryption/Decryption
Section titled “File Encryption/Decryption”# ============================================================# FILE ENCRYPTION - Multiple Methods# ============================================================
# Method 1: Encrypt for specific recipientgpg -e -r recipient@email.com file.txt# Output: file.txt.gpg
# Method 2: Encrypt with compressiongpg -z 9 -e -r recipient@email.com largefile.tar# -z 9 = maximum compression
# Method 3: Encrypt with symmetric cipher (password-based)gpg -c sensitive.doc# Prompts for passphrase# Output: sensitive.doc.gpg
# Method 4: Encrypt + sign (both encryption and authenticity)gpg -e -s -u sender@email.com -r recipient@email.com message.txt
# Method 5: ASCII armor output (for email/text)gpg -a -e -r recipient@email.com file.txt# Output: file.txt.asc (ASCII format)
# Decryptiongpg -d file.txt.gpg # Decrypt to stdoutgpg -d -o output.txt file.txt.gpg # Decrypt to filegpg file.txt.gpg # Interactive decryption
# Symmetric decryptiongpg -d symmetric.gpg
# Batch decryption (for scripts)echo "passphrase" | gpg --batch --yes --passphrase-fd 0 -d file.gpgDigital Signatures
Section titled “Digital Signatures”# ============================================================# SIGNING AND VERIFICATION# ============================================================
# Binary signature (creates .sig file)gpg --sign document.pdf# Output: document.pdf.sig
# Clear text signature (for email - visible signature)gpg --clearsign message.txt# Output: message.txt.asc# Contains the message + signature in ASCII
# Detached signature (separate signature file)gpg --armor --detach-sign document.pdf# Output: document.pdf.asc# Use when you don't want to modify original file
# Sign with specific keygpg -u sender@email.com --sign document.txt
# Multiple signaturesgpg --sign --local-user key1@email.com \ --sign --local-user key2@email.com document.txt
# Verificationgpg --verify file.txt.sig # Verify binary signaturegpg --verify file.txt.asc # Verify ASCII/armored signaturegpg --verify document.pdf.asc document.pdf # Verify detached signature
# Verbose verification (shows key details)gpg --verify --verbose file.txt.ascWeb of Trust
Section titled “Web of Trust”┌─────────────────────────────────────────────────────────────────────────┐│ WEB OF TRUST │├─────────────────────────────────────────────────────────────────────────┤│ ││ Trust Levels: ││ ┌─────────────────────────────────────────────────────────────┐ ││ │ ultimate (u) - You trust this key completely │ ││ │ (usually your own keys) │ ││ │ full (f) - You trust this key fully │ ││ │ marginal (m) - You trust this key somewhat │ ││ │ never (n) - You do not trust this key │ ││ │ unknown (o) - No trust decision made │ ││ └─────────────────────────────────────────────────────────────┘ ││ ││ Trust Path Example: ││ ││ [YOU] ││ │ ││ │ signs ││ ▼ ││ ┌─────────────┐ signs ┌─────────────┐ ││ │ Friend A │ ───────────────► │ Friend B │ ││ │ (full) │ │ (marginal) │ ││ └─────────────┘ └─────────────┘ ││ │ ││ signs │ ││ ▼ ││ ┌─────────────┐ ││ │ Target │ ││ │ Key │ ││ └─────────────┘ ││ ││ You trust Target if: ││ - At least one path with "full" trust, OR ││ - At least 3 paths with "marginal" trust ││ │└─────────────────────────────────────────────────────────────────────────┘
# Trust management commandsgpg --edit-key your@email.com# gpg> trust# Select trust level (1-5)# gpg> quitGPG Agent and Caching
Section titled “GPG Agent and Caching”# ============================================================# GPG-AGENT CONFIGURATION# ============================================================
# Configuration file: ~/.gnupg/gpg-agent.conf
cat > ~/.gnupg/gpg-agent.conf << 'EOF'# Cache TTL settingsdefault-cache-ttl 3600 # Default: 600 secondsmax-cache-ttl 86400 # Maximum: 1 day
# PIN entrypinentry-program /usr/bin/pinentry-gnome3allow-loopback-pinentry
# Agent lifecycle# gpg-agent --daemon # Start agent# gpgconf --kill gpg-agent # Stop agent
# Check agent statusgpg-connect-agent /byegpg-agent --homedir ~/.gnupg --daemon
# Reload agentgpg-connect-agent RELOADAGENT /bye36.3 LUKS (Linux Unified Key Setup)
Section titled “36.3 LUKS (Linux Unified Key Setup)”LUKS Architecture
Section titled “LUKS Architecture”┌─────────────────────────────────────────────────────────────────────────┐│ LUKS DISK ENCRYPTION │├─────────────────────────────────────────────────────────────────────────┤│ ││ Physical Disk Layout: ││ ┌──────────────────────────────────────────────────────────────┐ ││ │ LUKS Header (1-2MB) │ Encrypted Data │ ││ │ ┌──────────────────┐ │ ┌─────────────────────────────┐ │ ││ │ │ Magic String │ │ │ │ │ ││ │ │ (LUKS version) │ │ │ dm-crypt / dm-luks │ │ ││ │ │ Key Slots (8) │ │ │ (AES-XTS, plain/luks2) │ │ ││ │ │ - PBKDF2 params │ │ │ │ │ ││ │ │ - Salt │ │ │ (Encrypted User Data) │ │ ││ │ │ - Key Material │ │ │ │ │ ││ │ └──────────────────┘ │ └─────────────────────────────┘ │ ││ └──────────────────────────────────────────────────────────────┘ ││ ││ Key Slots (8 maximum): ││ ┌─────────────────────────────────────────────────────────────┐ ││ │ Slot 0 │ Slot 1 │ Slot 2 │ Slot 3 │ Slot 4 │ Slot 5 │ Slot 6 │Slot 7││ │Active │Active │ Empty │ Empty │ Empty │ Empty │ Empty │Empty ││ └─────────────────────────────────────────────────────────────┘ ││ Each slot can hold a different passphrase ││ Allows: key rotation, multiple users, backup passphrases ││ ││ Encryption Workflow: ││ ┌─────────────────────────────────────────────────────────────┐ ││ │ 1. PBKDF2 derives key from passphrase + salt │ ││ │ 2. Master Key (stored in header) decrypted temporarily │ ││ │ 3. Master Key used to encrypt/decrypt disk data │ ││ │ 4. Master Key held in kernel keyring (not in header) │ ││ └─────────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────┘LUKS Operations
Section titled “LUKS Operations”# ============================================================# LUKS DISK ENCRYPTION - Complete Guide# ============================================================
# Prerequisitessudo apt install cryptsetup # Debian/Ubuntusudo yum install cryptsetup # RHEL/CentOS
# Step 1: Prepare the devicelsblk # List block devicessudo parted /dev/sdb # Partition if neededsudo mkfs.ext4 /dev/sdb1 # Create filesystem first# OR create partition: sudo parted /dev/sdb mklabel gpt mkpart primary 0% 100%
# Step 2: Initialize LUKS containersudo cryptsetup luksFormat /dev/sdb1
# WARNING: This ERASES all data!# Enter YES (uppercase)# Enter and confirm passphrase (use strong passphrase!)
# With custom options:sudo cryptsetup luksFormat --type luks2 \ --cipher aes-xts-plain64 \ --key-size 512 \ --hash sha512 \ --iter-time 5000 \ --pbkdf argon2id \ /dev/sdb1
# LUKS2 is the default since cryptsetup 2.1.0# Argon2id is recommended (memory-hard, GPU resistant)
# Step 3: Open the containersudo cryptsetup luksOpen /dev/sdb1 secure_volume# Creates device mapper: /dev/mapper/secure_volume
# Step 4: Create filesystemsudo mkfs.ext4 /dev/mapper/secure_volume
# Step 5: Mount and usesudo mkdir /mnt/encryptedsudo mount /dev/mapper/secure_volume /mnt/encrypted
# Write some test dataecho "Sensitive data" | sudo tee /mnt/encrypted/secret.txt
# Step 6: Unmount and closesudo umount /dev/mapper/secure_volumesudo cryptsetup luksClose secure_volume
# ============================================================# LUKS MANAGEMENT# ============================================================
# View LUKS header infosudo cryptsetup luksDump /dev/sdb1# Shows: version, cipher, key size, UUID, key slots, etc.
# Add a new passphrasesudo cryptsetup luksAddKey /dev/sdb1# Prompts for existing passphrase, then new passphrase
# Remove a passphrasesudo cryptsetup luksRemoveKey /dev/sdb1# Must have at least one remaining passphrase!
# Change passphrasesudo cryptsetup luksChangeKey /dev/sdb1# Can also change specific slot: luksChangeKey -S 0 /dev/sdb1
# Add key to specific slotsudo cryptsetup luksAddKey -S 1 /dev/sdb1
# Remove key from specific slotsudo cryptsetup luksRemoveKey -S 1 /dev/sdb1
# Check which slots are usedsudo cryptsetup luksDump /dev/sdb1 | grep -A 10 "Key Slots"
# Backup LUKS header (CRITICAL for recovery!)sudo cryptsetup luksHeaderBackup /dev/sdb1 --header-backup-file luks_header.img# Store securely - with this, attacker can try to crack your passphrase
# Restore LUKS headersudo cryptsetup luksHeaderRestore /dev/sdb1 --header-backup-file luks_header.img
# Resume suspended container (after system sleep)sudo cryptsetup luksResume /dev/mapper/secure_volumeLUKS with Keyfile
Section titled “LUKS with Keyfile”# ============================================================# AUTOMOUNT WITH KEYFILE (For servers/automation)# ============================================================
# Method 1: Create random keyfilesudo dd if=/dev/urandom of=/root/luks.key bs=4096 count=1sudo chmod 600 /root/luks.key
# Add keyfile to LUKS slotsudo cryptsetup luksAddKey /dev/sdb1 /root/luks.key
# Method 2: Add keyfile to specific slotsudo cryptsetup luksAddKey -S 2 /dev/sdb1 /root/luks.key
# Method 3: Configure /etc/crypttab (auto-unlock at boot)# /etc/crypttab:# secure_volume /dev/sdb1 /root/luks.key luks,discard
# Method 4: Using systemd (modern approach)# /etc/systemd/system/mnt-secure.mount[Unit]Description=Encrypted Secure Volume
[Mount]What=/dev/mapper/secure_volumeWhere=/mnt/secureType=ext4Options=defaults
# /etc/fstab:# /dev/mapper/secure_volume /mnt/secure ext4 defaults 0 2
# Create systemd service to unlock at boot# /etc/systemd/system/luks-unlock.service[Unit]Description=Unlock LUKS volumeRequires=systemd-remount-fs.serviceAfter=systemd-remount-fs.service
[Service]Type=oneshotExecStart=/usr/bin/cryptsetup luksOpen /dev/sdb1 secure_volumeExecStart=/usr/bin/mount /dev/mapper/secure_volume /mnt/secureRemainAfterExit=yes
[Install]WantedBy=multi-user.target
# Enable: sudo systemctl enable luks-unlock.serviceLUKS Performance Tuning
Section titled “LUKS Performance Tuning”# ============================================================# LUKS PERFORMANCE OPTIMIZATION# ============================================================
# Benchmark encryption optionssudo cryptsetup benchmark
# Example output:# KDF, 5 iterations, 64 memory, threads: 4# PBKDF2-sha256 362k# PBKDF2-sha512 337k# argon2id 170k (memory-hard, slower but more secure)
# Recommended options for new containers:sudo cryptsetup luksFormat --type luks2 \ --cipher aes-xts-plain64 \ # XTS mode for disk encryption --key-size 512 \ # 512-bit = 256-bit effective --hash sha512 \ # For key derivation --iter-time 5000 \ # ms for PBKDF2 (adjust for security) --pbkdf argon2id \ # Better than PBKDF2 /dev/sdb1
# For older systems (LUKS1):sudo cryptsetup luksFormat --type luks1 \ --cipher aes-xts-plain64 \ --key-size 512 \ --hash sha512 \ --iter-time 3000 \ --pbkdf pbkdf2 \ /dev/sdb1
# Check if hardware encryption is availablecat /proc/crypto | grep -i aesls /dev/crypto # Should exist if available
# Check CPU for AES-NI supportgrep -o aes /proc/cpuinfo | head -1# Or: lscpu | grep -i aesLUKS Emergency Recovery
Section titled “LUKS Emergency Recovery”# ============================================================# EMERGENCY RECOVERY PROCEDURES# ============================================================
# Scenario 1: System won't boot - LUKS password not accepted# Boot from rescue media, then:
# Check if LUKS container is accessiblesudo cryptsetup luksDump /dev/sdX1
# If header corrupted, restore from backupsudo cryptsetup luksHeaderRestore /dev/sdX1 --header-backup-file /path/to/backup.img
# Scenario 2: Forgotten passphrase - but you have backup# If you have another working slot:sudo cryptsetup luksOpen /dev/sdX1 recovery
# Scenario 3: Header completely corrupted# Without backup, data is LOST - this is why backups are critical!# Only cryptographically secure erasure can recover
# Scenario 4: Suspended container won't resume# After system crash/suspendsudo dmsetup remove /dev/mapper/secure_volumesudo cryptsetup luksOpen /dev/sdX1 secure_volume
# Scenario 5: Check LUKS integritysudo cryptsetup luksDump /dev/sdX1# Check "Failed authentication counter" - too many failures = lockout
# Emergency: Wipe LUKS container completelysudo cryptsetup luksErase /dev/sdX1# Or: sudo wipefs -a /dev/sdX136.4 Filesystem-Level Encryption
Section titled “36.4 Filesystem-Level Encryption”eCryptfs
Section titled “eCryptfs”# ============================================================# ECryptfs - Stacked Filesystem Encryption# ============================================================
# Installsudo apt install ecryptfs-utils
# Create encrypted directorymkdir -p ~/Privatesudo mount -t ecryptfs ~/Private ~/Private# Select: passphrase, aes, plain, no signature, no encryption of filenames
# Using the automated toolecryptfs-setup-private# Creates ~/.Private and ~/Private# ~/.Private contains encrypted data# ~/Private is the decrypted view when mounted
# Mount manually with optionssudo mount -t ecryptfs \ -o key=passphrase,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,\ecryptfs_passthrough=n,ecryptfs_enable_filename_crypt=y \ /home/user/.Private /home/user/Private
# Unmount (hides data)ecryptfs-umount-private
# Add signature to keyring for auto-mountecryptfs-add-passphrase --fnek# Add to /etc/ecryptfs/rc.local or pam_ecryptfsfscrypt (Modern Alternative)
Section titled “fscrypt (Modern Alternative)”# ============================================================# fscrypt - Native Linux Encryption (Kernel 4.2+)# ============================================================
# Installsudo apt install fscrypt libpam-fscrypt
# Enable on filesystemsudo tune2fs -O encrypt /dev/sdX1# Or at mount: mount -o encrypt /dev/sdX1 /mnt
# Setupfscrypt setupfscrypt setup root # For root userfscrypt setup other_user # For other users
# Create encrypted directorymkdir -p ~/encryptedfscrypt encrypt ~/encrypted
# Check statusfscrypt statusfscrypt status ~/encrypted
# Lock/Unlockfscrypt lock ~/encryptedfscrypt unlock ~/encrypted36.5 Swap Encryption
Section titled “36.5 Swap Encryption”# ============================================================# ENCRYPTED SWAP# ============================================================
# Method 1: Using systemd (recommended)# /etc/fstab:# /dev/mapper/cryptswap none swap sw 0 0
# /etc/systemd/system/cryptswap.service:[Unit]Description=Encrypted SwapAfter=swap.target
[Service]Type=oneshotRemainAfterExit=yesExecStart=/sbin/cryptsetup open --type plain /dev/sda2 cryptswap --key-file /root/swap.keyExecStart=/sbin/mkswap /dev/mapper/cryptswapExecStop=/sbin/cryptsetup close cryptswap
[Install]WantedBy=multi-user.target
# Create keyfiledd if=/dev/urandom of=/root/swap.key bs=4096 count=1chmod 600 /root/swap.key
# Enablesudo systemctl enable cryptswap.servicesudo systemctl start cryptswap.service
# Method 2: Using /etc/crypttab (legacy)# /etc/crypttab:# cryptswap /dev/sda2 /dev/urandom swap,cipher=aes-xts-plain64,size=51236.6 OpenSSL for TLS/SSL
Section titled “36.6 OpenSSL for TLS/SSL”# ============================================================# OPENSSL - TLS CERTIFICATES# ============================================================
# Generate private keyopenssl genrsa -out server.key 2048openssl genrsa -out server.key 2048 # With encryptionopenssl genrsa -aes256 -out server.key 2048
# Generate CSRopenssl req -new -key server.key -out server.csropenssl req -new -key server.key -out server.csr \ -subj "/C=US/ST=State/L=City/O=Organization/CN=example.com"
# Self-signed certificate (for testing)openssl req -x509 -days 365 -key server.key -in server.csr -out server.crtopenssl req -x509 -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
# Verify certificateopenssl x509 -in server.crt -text -nooutopenssl verify -CAfile ca.crt server.crt
# Extract infoopenssl x509 -in server.crt -noout -subjectopenssl x509 -in server.crt -noout -issueropenssl x509 -in server.crt -noout -datesopenssl x509 -in server.crt -noout -fingerprint
# Convert formatsopenssl x509 -in cert.pem -outform DER -out cert.deropenssl x509 -in cert.der -inform DER -outform PEM -out cert.pem
# Generate DH parametersopenssl dhparam -out dhparam.pem 2048
# Test SSL connectionopenssl s_client -connect example.com:443openssl s_client -connect example.com:443 -showcertsopenssl s_client -connect example.com:443 -verify_return_error
# Check cipher suitesopenssl ciphers -v 'HIGH:!aNULL:!MD5'36.7 Production Encryption Checklist
Section titled “36.7 Production Encryption Checklist”# ============================================================# PRODUCTION ENCRYPTION CHECKLIST# ============================================================
# 1. Disk Encryption# [ ] All sensitive data disks encrypted with LUKS# [ ] LUKS header backed up and stored securely# [ ] Keyfiles protected (permissions 600)# [ ] Multiple LUKS passphrases for recovery
# 2. Filesystem Encryption# [ ] Home directories encrypted (fscrypt/ecryptfs)# [ ] Database files encrypted# [ ] Log files containing sensitive data encrypted
# 3. Network Encryption# [ ] All production traffic uses TLS 1.2+# [ ] Strong cipher suites only# [ ] Certificates from trusted CA# [ ] Certificate expiration monitoring
# 4. Key Management# [ ] GPG keys backed up securely# [ ] Expiration dates set on all keys# [ ] Revocation certificates generated# [ ] Key rotation policy in place
# 5. Swap and Temp# [ ] Swap encrypted# [ ] /tmp on encrypted volume if sensitive data# [ ] /dev/shm permissions restricted
# 6. Monitoring# [ ] Failed decryption attempts logged# [ ] LUKS authentication failures monitored# [ ] Certificate expiration alerts
# 7. Recovery# [ ] Documented recovery procedures# [ ] Test recovery process# [ ] Multiple authorized individuals for recovery36.8 Interview Questions
Section titled “36.8 Interview Questions”┌─────────────────────────────────────────────────────────────────────────┐│ ENCRYPTION INTERVIEW QUESTIONS │├─────────────────────────────────────────────────────────────────────────┤ │Q1: Explain the difference between symmetric and asymmetric encryption. │ │A1: │- Symmetric: Same key for encryption/decryption (AES, ChaCha20) │ - Pros: Fast, efficient for bulk data │ - Cons: Key distribution problem │ │- Asymmetric: Public key encrypts, private key decrypts (RSA, ECC) │ - Pros: Solves key distribution, enables signatures │ - Cons: Slow, computationally intensive │ │- Hybrid: Encrypt data with symmetric key, encrypt key with │ asymmetric key (standard practice for file encryption) │ │─────────────────────────────────────────────────────────────────────────┤ │Q2: How does GPG implement the Web of Trust? │ │A2: │- Each user can sign other users' public keys │- Trust levels: ultimate > full > marginal > never > unknown │- A key is considered trusted if: │ - One path with full trust, OR │ - Three paths with marginal trust │- Reduces dependency on centralized CAs │- More complex but decentralized │ │─────────────────────────────────────────────────────────────────────────┤ │Q3: Describe the LUKS encryption structure and key slots. │ │A3: │- LUKS header contains: │ - Magic string, version, cipher info │ - 8 key slots (each can hold encrypted master key) │ - PBKDF2 parameters for key derivation │- Master key encrypts actual data (via dm-crypt) │- Different passphrases can unlock different slots │- Allows: key rotation, backup passphrases, multiple users │- Header backup critical for recovery │ │─────────────────────────────────────────────────────────────────────────┤ │Q4: What are the differences between LUKS1 and LUKS2? │ │A4: │| Feature | LUKS1 | LUKS2 | │|----------------|-----------------|--------------------------| │| Max slots | 8 | 8 (unlimited internally) | │| Header size | 512KB fixed | 16MB default | │| KDF | PBKDF2 | Argon2id, PBKDF2 | │| Integrity | None | dm-integrity | │| Reencryption | Offline only | Online reencryption | │| Performance | Good | Better (more iterations) | │ │─────────────────────────────────────────────────────────────────────────┤ │Q5: How would you recover data from a corrupted LUKS container? │ │A5: │1. First, backup the entire device (dd if=/dev/sdX of=backup.img) │2. Try to read header: cryptsetup luksDump /dev/sdX │3. If header corrupted, restore from backup: │ cryptsetup luksHeaderRestore /dev/sdX --header-backup-file backup │4. Try each key slot: cryptsetup luksOpen --test-crypto /dev/sdX │5. If header completely lost and no backup - data is UNRECOVERABLE │6. Use grep -a /dev/sdX for "LUKS" magic string to find header │ │─────────────────────────────────────────────────────────────────────────┤ │Q6: Explain the difference between dm-crypt and dm-luks. │ │A6: │- dm-crypt: Plain device encryption, no LUKS header │ - No key slots, single passphrase │ - Can be faster (no header I/O) │ - Harder to verify correct passphrase │ - No key rotation │ │- dm-luks: LUKS wrapper around dm-crypt │ - Has LUKS header with key slots │ - Multiple passphrases │ - Key management features │ - Default choice for most use cases │ │─────────────────────────────────────────────────────────────────────────┤ │Q7: What is Argon2id and why is it preferred over PBKDF2? │ │A7: │- Argon2id is winner of Password Hashing Competition (2015) │- Memory-hard: Uses significant RAM to compute hash │- GPU-resistant: Hard to parallelize on GPU clusters │- Better security margin than PBKDF2 │- Recommended for new LUKS2 containers │ │─────────────────────────────────────────────────────────────────────────┤ │Q8: How do you secure a Linux server's sensitive data at rest? │ │A8: │1. Encrypt system disk (LUKS) - prevents physical theft │2. Encrypt data drives with separate LUKS containers │3. Use filesystem-level encryption for user directories │4. Encrypt swap and /tmp │5. Store encryption keys in hardware security modules (HSM) │6. Implement proper key management: rotation, backup, access control │7. Enable full-disk encryption on laptops/mobile devices │ │─────────────────────────────────────────────────────────────────────────┤ │Q9: What are the security considerations when using keyfiles? │ │A9: │- Keyfile is just as secure as the passphrase it replaces │- If keyfile is compromised, entire encryption is compromised │- Best practices: │ - Use strong randomness: dd if=/dev/urandom (not /dev/random) │ - Restrict permissions: chmod 600 keyfile │ - Store separately from encrypted data │ - Use TPM for automatic unlock without exposed keyfile │ - Encrypt keyfile itself with another layer of protection │ │─────────────────────────────────────────────────────────────────────────┤ │Q10: Explain the difference between file encryption and disk encryption.│ │A10: │- Disk/Full-disk encryption: │ - Encrypts entire block device │ - All data at rest protected │ - Transparent to applications │ - LUKS, dm-crypt, VeraCrypt │ │- File-level encryption: │ - Encrypts individual files/directories │ - Can have different keys for different files │ - eCryptfs, fscrypt, GPG-encrypted files │ - Portable - encrypted file can be moved │ │- Hybrid approach often used in production │ │└─────────────────────────────────────────────────────────────────────────┘Quick Reference
Section titled “Quick Reference”# GPG Commandsgpg --full-generate-key # Generate key pairgpg --list-keys # List public keysgpg --list-secret-keys # List private keysgpg -e -r recipient file.txt # Encryptgpg -d file.txt.gpg # Decryptgpg --sign file.txt # Signgpg --verify file.sig # Verify signaturegpg --armor --export email > key.asc # Export public keygpg --import key.asc # Import key
# LUKS Commandscryptsetup luksFormat /dev/sdX1 # Create LUKScryptsetup luksOpen /dev/sdX1 name # Open containercryptsetup luksClose name # Close containercryptsetup luksDump /dev/sdX1 # Show header infocryptsetup luksAddKey /dev/sdX1 # Add passphrasecryptsetup luksRemoveKey /dev/sdX1 # Remove passphrasecryptsetup luksHeaderBackup /dev/sdX1 -f backup.img # Backup header
# OpenSSL Commandsopenssl genrsa -out key.pem 2048 # Generate keyopenssl req -new -key key.pem -out csr.pem # Generate CSRopenssl x509 -req -days 365 -in csr.pem -signkey key.pem -out cert.pem # Self-signedopenssl x509 -in cert.pem -text -noout # View certificateopenssl s_client -connect host:443 # Test connection
# fscrypt Commandsfscrypt setup # Initializefscrypt encrypt directory # Encrypt directoryfscrypt lock directory # Lock directoryfscrypt unlock directory # Unlock directoryCommon Mistakes & Anti-Patterns
Section titled “Common Mistakes & Anti-Patterns”1. Not Encrypting Data at Rest
Section titled “1. Not Encrypting Data at Rest”# ❌ WRONG: No encryption on sensitive data# /dev/sdb1 mounted as plain ext4# Database files unencrypted
# ✅ CORRECT: Use LUKS for disk encryptioncryptsetup luksFormat /dev/sdb1cryptsetup open /dev/sdb1 datamkfs.ext4 /dev/mapper/data# Or use filesystem encryptionfscrypt encrypt /mount/point2. Weak Key Management
Section titled “2. Weak Key Management”# ❌ WRONG: Storing encryption keys with data# Keys in same directory as encrypted files!gpg --encrypt --recipient keyfile key.txt
# ✅ CORRECT: Separate key management# Use hardware security modules (HSM)# Use key management services (AWS KMS, HashiCorp Vault)# Never store keys with encrypted data3. Not Backing Up Encryption Keys
Section titled “3. Not Backing Up Encryption Keys”# ❌ WRONG: No backup of LUKS header# If disk fails, data is lost!
# ✅ CORRECT: Backup LUKS header and keyscryptsetup luksHeaderBackup /dev/sda5 --header-backup-file /backup/luks-header.img# Store backup securely (offsite, encrypted)gpg --symmetric --armor /backup/luks-header.img4. Using Deprecated Algorithms
Section titled “4. Using Deprecated Algorithms”# ❌ WRONG: Weak encryption algorithms# DES, 3DES, MD5, SHA1 are brokengpg --cipher-algo IDEAopenssl enc -des3
# ✅ CORRECT: Use modern algorithmsgpg --cipher-algo AES256openssl enc -aes-256-cbc# Use Ed25519 for signing, not RSA < 2048Summary
Section titled “Summary”- GPG: Asymmetric encryption for secure communication, signing, and key management
- Web of Trust: Decentralized trust model through key signatures
- LUKS: Standard for Linux disk encryption with key slots and secure key derivation
- LUKS2 vs LUKS1: LUKS2 offers Argon2id, integrity protection, and online reencryption
- Filesystem Encryption: eCryptfs and fscrypt for directory-level encryption
- Production: Combine disk encryption, key management, and monitoring
Next Chapter
Section titled “Next Chapter”Chapter 36: System Logging - rsyslog, syslog-ng
Last Updated: February 2026