๐ Securing `/tmp` and `/var/tmp` with a Dedicated Loopback Filesystem
๐ Purpose
๐ซ Prevent malicious code execution โ Stops attackers from running scripts in `/tmp`.
๐ Block setuid exploits โ `nosuid` prevents privilege escalation.
๐ก Isolate `/tmp` from root โ Limits filesystem exposure if `/tmp` is compromised.
๐ Apply same restrictions to `/var/tmp`** โ Ensures uniform security for temporary directories.
๐ Step-by-Step Guide
Unmount Existing `/tmp` and `/var/tmp`
umount /tmp umount -l /tmp umount -l /var/tmp
ย umount โ detaches a filesystem.
-l โ lazy unmount, detaches immediately but cleans up references later.
Ensures /tmp and /var/tmp can be reconfigured safely.
Stop Services Using `/tmp`
systemctl stop mysql || systemctl stop httpd systemctl stop mysqld.service
Stops services that might be using `/tmp`.
|| โ attempts the next command if the first fails.
Prevents files from being locked while remounting `/tmp`.
Backup Old Disk File
mv /usr/tmpDSK /usr/tmpDSK_bk
Moves the old disk file to a backup location.
Preserves data in case rollback is needed.
Create a New Disk File (4GB)
dd if=/dev/zero of=/usr/tmpDSK bs=1 count=0 seek=4G
dd โ low-level file creation.
if=/dev/zero โ fills with zeros.
seek=4G โ reserves 4GB sparse file for /tmp.
Format as ext4
mkfs.ext4 /usr/tmpDSK
Formats the file as an ext4 filesystem.
Required to mount as a loopback device.
Mount the Disk as `/tmp`
mount -o loop,rw,nodev,nosuid,noexec /usr/tmpDSK /tmp
chmod 1777 /tmp
`loop` โ treat the file as a block device.
`rw` โ read/write.
`nodev` โ block device files disabled.
`nosuid` โ ignore setuid bits.
`noexec` โ prevent executing binaries.
`chmod 1777` โ world-writable with sticky bit (users only delete own files).
Bind-Mount `/var/tmp`
mount -o rw,noexec,nosuid,nodev,bind /tmp /var/tmp
Shares `/tmp` restrictions with `/var/tmp`.
Prevents setuid, device files, and executable scripts.
Verify Mounts
df -Th
Shows all mounted filesystems and types.
Confirms `/tmp` and `/var/tmp` are mounted correctly.
Make Mounts Persistent
vim /etc/fstab
Add:
/usr/tmpDSK /tmp ext4 defaults,noauto,loop,rw,nodev,nosuid,noexec 0 0
mount -a
`/etc/fstab` โ persistent mount configuration.
`mount -a` โ mounts all filesystems listed in fstab.
Restart Services
systemctl start httpd systemctl start mysqld.service
Restart web, database, and spam services.
Ensures normal operations resume after remounting `/tmp`.
โ Verification
cd /tmp touch test.txt ls -l
Tests that `/tmp` is writable.
Confirms permissions and proper mount.
๐ก Security Benefits
๐ฆ `/tmp` is isolated from root filesystem.
๐ Prevents execution of untrusted scripts.
๐ `/var/tmp` inherits the same restrictions.
๐ Reduces attack surface and improves security.
๐ Troubleshooting
Service fails to start:** Check `/tmp` permissions (`chmod 1777 /tmp`).
Disk full:** Resize `/usr/tmpDSK` with `dd` and `resize2fs`.
Changes not persistent:** Verify `/etc/fstab` entry and run `mount -a`.