Last active
October 28, 2024 15:21
.bashrc lines to stop user from accessing block devices directly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# disallow accessing block devices directly | |
reject_devsdx () { | |
# check if being executed at the top-level (e.g. invoked by the user trying to execute a command, but not when doing tab completion) | |
if [[ -z "${FUNCNAME[1]}" ]] | |
then | |
blockdev_path="" | |
# check each argument if it is a path that refers to a block device | |
for arg in ${BASH_COMMAND} | |
do | |
# it is safe to use ${arg} without quotes here since the for loop has split it anyway | |
if [[ ${arg} =~ "/dev/" && "$(LC_ALL=C stat --format %F $(echo ${arg} | grep -oE /dev/[^\"\']+))" == "block special file" ]] | |
then | |
blockdev_path=${arg} | |
fi | |
done | |
if [[ -n "${blockdev_path}" ]] | |
then | |
aliases="$(find /dev/disk -type l -printf '%p -> ' -exec readlink --canonicalize {} ';' | grep --word-regexp ${blockdev_path})" | |
if [[ -n "${aliases}" ]] | |
then | |
echo "Stop being stupid. Use one of these:" | |
echo "${aliases}" | |
return 1 # this will inhibit the command execution | |
fi | |
fi | |
fi | |
} | |
shopt -s extdebug | |
trap reject_devsdx DEBUG |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment