How to Permanently Disable Swap Space in Linux: Kernel-Level vs fstab Methods for Security-Conscious Systems


2 views

When hardening Linux systems, particularly those handling sensitive data with full-disk encryption, swap space becomes a potential security liability. The memory paging mechanism can inadvertently write decrypted contents to persistent storage. Let's examine the most effective approaches to eliminate this risk.

For most users, modifying /etc/fstab provides sufficient swap prevention:

# Original swap entry (to be removed)
# /dev/mapper/swap-partition none swap sw 0 0

# Alternative: Comment out or delete the swap line entirely

After editing, verify with:

sudo swapon --show
free -h

For absolute certainty (especially on security-hardened systems), rebuild your kernel without swap support:

make menuconfig

Navigate to:

Memory Management options → Support for paging of anonymous memory (swap)

Uncheck this option, then compile and install the new kernel. This provides:

1. Complete removal of swap functionality
2. Prevention of any module-based swap reactivation
3. Smaller kernel footprint

For comprehensive protection, consider:

# Disable zswap (compressed swap cache)
echo 0 > /sys/module/zswap/parameters/enabled

# Remove swapfile if present
sudo swapoff /swapfile
sudo rm -f /swapfile

Before disabling swap permanently:

1. Ensure adequate physical RAM (minimum 8GB recommended)
2. Configure vm.swappiness=0 (temporary measure)
3. Monitor OOM killer behavior with:
   dmesg | grep -i 'out of memory'

Confirm swap is fully disabled with:

cat /proc/swaps
# Should return empty output

grep -i swap /proc/meminfo
# SwapTotal and SwapFree should show 0 kB

Swap space in Linux serves as overflow when physical RAM is exhausted, but in encrypted environments or high-memory systems, it can pose security risks through potential disk leakage. For a kernel 3.18.9 system with encrypted partitions, complete swap removal requires multiple approaches.

First disable active swap partitions:

sudo swapoff -a

Verify with:

free -h
swapon --show

To prevent swap mounting at boot:

sudo nano /etc/fstab

Comment out or remove all lines containing "swap", for example:

# /dev/sda5 none swap sw 0 0

For absolute certainty in security-critical environments, recompile kernel without swap support:

make menuconfig

Navigate to:
Memory Management options → Support for paging of anonymous memory (swap)
and disable it.

For systems using systemd-swap:

sudo systemctl disable systemd-swap
sudo systemctl mask systemd-swap

After reboot, confirm:

cat /proc/swaps

Should return empty output. Additionally check:

dmesg | grep -i swap

For any swap-related kernel messages.

If complete removal isn't feasible, consider encrypted swap:

sudo cryptsetup luksFormat /dev/sdX
sudo mkswap /dev/mapper/cryptswap
swapon /dev/mapper/cryptswap