Quoc An Ha

Editing root restricted files

It is often that we need to edit a file restricted to root privileges. Naively one could simply do sudo vim /path/to/file however this has certain drawbacks:

  1. Your editor is executed as root, which means any vulnerability in your editor now potentially can access your system with root priveleges. E.g.: Simply :terminal in the latest vim versions would give you a root shell. Or likewise :!/bin/bash would give you one too.
  2. Since your editor is executed as root, it will ignore all of your personal configurations!

So what is the best approach?

Instead, try to get into the habit of using sudoedit, which relies on the $EDITOR environment variable. This script copies the targeted file to a temporary file, opens the temp file with your editor and replaces the original one with the edited one when finished. Root priveleges are used to copy the file but never to open your editor.

Alternatively if using vim or nvim and with read (but no write) access you can use:

:w !sudo tee %

Adding some training wheels

In order to get into the habit of using sudoedit instead of sudo nvim add the following snippet into .bashrc or .zshrc.

function sudo() {
    if [ "$1" = "$EDITOR" ] || [ "$1" = "vim" ] || [ "$1" = "emacs" ]  ; then
        if [ "$2" = "/etc/sudoers" ]; then
            echo "Don't edit the sudoers file directly, use 'visudo' instead."
        else
            echo "Don't use 'sudo vim|nvim|nano', use 'sudoedit' or 'sudo -e' instead."
        fi
    else
        command /usr/bin/sudo "$@"
    fi
}

This snippet outputs a warning message when attempting to use sudo $EDITOR, forcing you to use sudoedit or sudo -e.