Is Vim safe to use in combination with sudo?

It is not advisable to use sudo with a graphical application like gedit, as described at this link. Accordingly, I have tended to use vim with sudo.

Recently I noticed my ~/.viminfo was owned by root on a fairly fresh install of Ubuntu 16.04 (Xenial Xerus), so it had me wondering if even Vim is considered to be graphical or if there is some other problem with invoking sudo vim. After changing ownership to myself via:

sudo find $HOME -not -user $USER -exec chown $USER:$(id -g) {} +

and subsequently running sudo vim I was unable to have ~/.viminfo owned by root. However, I am certain that it recently was owned by root.

Is it inadvisable to invoke sudo vim?


Solution 1:

Yes, it is safe.

The problem with sudo gedit is because GUI applications use certain files, such as ~/.cache/dconf, and after elevated gedit that file becomes root-owned. Well, that particular file contains user-specific settings for GUI applications, including desktop, so if the system can't read those settings - it's bad. IIRC a user can't start a particular desktop. The user's recent files data recently-used.xbel also gets affected.

On the other hand, Vim doesn't have that problem. It uses no GUI-related database and doesn't put anything into recently-used.xbel. It was created for a console-only purpose, although gVim also exists. In fact, on some systems Vim is your only choice of editor. So it is safer than gedit by virtue of not causing the same problems. You're still editing as root in both cases, so you could cause problems with improper editing.

According to this blog post:

The first time you use vim, the file ~/.viminfo is created, and if you use sudo vim the first time you use vim after installing it on a fresh system, the permissions on ~/.viminfo will have the owner set to root instead of the default user.

While the author points out it can lead to issues, there's nothing complex - just chown the file back to yourself.

See also:

  • What specific bad things happen when gedit is used with sudo?

Solution 2:

It's also possible to use sudoedit to achieve this; it opens a temporary copy of the file in your editor, with your editor running as you. From the man page:

  1. Temporary copies are made of the files to be edited with the owner set to the invoking user.

  2. The editor specified by the policy is run to edit the temporary files. The sudoers policy uses the SUDO_EDITOR, VISUAL and EDITOR environment variables (in that order). If none of SUDO_EDITOR, VISUAL or EDITOR are set, the first program listed in the editor sudoers(5) option is used.

  3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed.

This works fine with vim (it's what I generally do) and I imagine it would let you use gedit too. There are some security restrictions.