How To Secure /tmp , /var/tmp and /dev/shm Partition In Linux Servers

Temporary directories such as /tmp, /var/tmp, and /dev/shm are world-writable directories which can hold temporary files of all users/applications, which means any users/applications can execute malicious scripts and programs to crack your server. So it is recommended to create a /tmp as a separate partition and mount it with noexec and nosuid mount options. The noexec disables the executable file attribute within an entire file system, effectively preventing any files within that file system from being executed. The nosuid disables the SUID file-attribute within an entire file system. This prevents SUID attacks on, for example, the /tmp file system.

You can follow the below instructions for securing /tmp , /var/tmp and /dev/shm partitions.

1. Secure /tmp:

# dd if=/dev/zero of=/usr/tmpDSK seek=1024 count=1024 bs=2M
# mkfs.ext4 /usr/tmpDSK
# mv /tmp /usr/tmp.secure
# mkdir /tmp
# chmod 1777 /tmp
# mount -o loop,noexec,nosuid,rw /usr/tmpDSK /tmp

Add the string into /etc/fstab:

/usr/tmpDSK /tmp ext4 defaults,nodev,nosuid,noexec 1 2

Check new partition is mounted,

# df -h | grep DSK

Copy old tmp files to new partition,

# cp -apRf /usr/tmp.secure/ /tmp/

2. Securing /var/tmp

The /var/tmp directory is made available for programs that require temporary files or directories that are preserved between system reboots. Therefore, data stored in /var/tmp is more persistent than data in /tmp.Files and directories located in /var/tmp must not be deleted when the system is booted. Although data stored in /var/tmp is typically deleted in a site-specific manner, it is recommended that deletions occur at a less frequent interval than /tmp.

# mv /var/tmp /var/tmp.secure
# ln -sf /tmp /var/
# cp -apRf /var/tmp.secure/ /var/tmp/

3. Securing /dev/shm

The /dev/shm is a temporary file storage filesystem, i.e., tmpfs, that uses RAM for the backing store. It can function as a shared memory implementation that facilitates IPC. Add nodev, nosuid, and noexec options to /dev/shm, Append the following line or edit the existing into /etc/fstab:

tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0

Remount /dev/shm ,

# mount -o remount /dev/shm
    1. r jasmin June 24, 2017

    Add Your Comment