Ensure the PATH of a Root Login Shell Holds Only Safe Directories

Description

A login shell of root takes its PATH from /etc/profile, the files in /etc/profile.d and the startup files in the home directory of root. Each entry of that PATH should be the absolute path of an existing directory owned by root and writable by its owner only. An empty entry, a trailing one included, stands for the current directory. To list the PATH of a root login shell, run the command:

# su - root -c 'printf "%s\n" "$PATH"'

Remove each empty, relative or trailing entry from the file that adds it. Create each missing directory, or remove it from the PATH, and give each directory the owner root and the mode 0755 or stricter.

Rationale

Root runs the first program of a given name that it finds in its PATH. A relative or empty entry, or a directory that other users can write to, lets them plant a program that root then runs.

Remediation

Shell script

The following script can be run on the host to remediate the issue.

#!/bin/bash

# Read the PATH of a root login shell as the check does, then create its
# missing directories and make the others owned by root and writable by
# their owner only, as the CIS remediation does. Empty, relative and
# trailing entries stay for the administrator to remove from the startup
# file that adds them.
home=$(awk -F: '$1 == "root" { print $6; exit }' /etc/passwd)
shell=$(awk -F: '$1 == "root" { print $7; exit }' /etc/passwd)
home=${home:-/root}
shell=${shell:-/bin/sh}

start=$(sed -n 's/^[[:space:]]*PATH[[:space:]]*=[[:space:]]*//p' /etc/environment 2>/dev/null | tail -n 1 | tr -d "\"'")
if [ -z "$start" ]; then
    start=$(awk '$1 == "ENV_ROOTPATH" { r = $2 } $1 == "ENV_SUPATH" { s = $2 }
        END { p = s != "" ? s : r; sub(/^PATH=/, "", p); print p }' /etc/login.defs 2>/dev/null)
fi
start=${start:-/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin}

# shellcheck disable=SC2016 # the login shell expands $PATH
root_path=$(cd "$home" 2>/dev/null || cd /
    timeout 30 env -i HOME="$home" SHELL="$shell" USER=root LOGNAME=root PATH="$start" \
        "$shell" -l -c 'printf "\nROOT_LOGIN_PATH=%s\n" "$PATH"' </dev/null 2>/dev/null |
        sed -n 's/^ROOT_LOGIN_PATH=//p' | tail -n 1)

IFS=: read -ra entries <<<"$root_path"
for entry in "${entries[@]}"; do
    case $entry in
    /*) ;;
    *) continue ;;
    esac
    [ -e "$entry" ] || mkdir -p "$entry"
    [ -d "$entry" ] || continue
    [ "$(stat -Lc %u "$entry")" -eq 0 ] || chown root "$entry"
    [ $((0$(stat -Lc %a "$entry") & 022)) -eq 0 ] || chmod go-w "$entry"
done