Wanderer
Wanderer

Reputation: 272

sudo -u flawed file permissions

I am using Bash on Lubuntu 16.04. LTS, but I'm not sure if this matters much for this question.

I noticed, that when I create a file as standard user, the file has 664 permissions. But when I am root and execute the same command for the same user via the -u argument, it has 644 permissions, so the write permissions for the group are missing.

I suppose this to be a flaw, since the sudo manpages clearly state:

     -u user, --user=user
             Run the command as a user other than the default target user (usually root).  The user may be either a user name or a
             numeric user ID (UID) prefixed with the ‘#’ character (e.g.  #0 for UID 0).  When running commands as a UID, many
             shells require that the ‘#’ be escaped with a backslash (‘\’).  Some security policies may restrict UIDs to those
             listed in the password database.  The sudoers policy allows UIDs that are not in the password database as long as the
             targetpw option is not set.  Other security policies may not support this.

Now that I know that the -u argument's behavior differs from the behavior that has to be expected, my question is:

How can I make sure, that a command that is started in a root shell gets executed exactly as it would be executed from another user's shell?

Remark: I know that I could fix this one problem by tinkering with the umask, but this won't guarantee me that the behavior doesn't differ in an arbitrary amount of other cases.

Upvotes: 2

Views: 932

Answers (2)

Wanderer
Wanderer

Reputation: 272

A nice and clean solution that shows the expected behavior is this:

sudo su <username> -c '<any commands>'

Upvotes: -1

l0b0
l0b0

Reputation: 58918

It looks like the umask depends on whether the shell is interactive:

$ umask
0002
$ sudo -u $USER bash -c umask
0022
$ sudo -u $USER bash -ic umask
0002

This appears to be from from /etc/bashrc, which applies umask 002 only if

  • it's not a login shell,
  • the UID is greater than or equal to 200, and
  • the username is equal to the group name,

or from /etc/profile, which applies umask 002 if the last two criteria are met. I'm not sure if something else is overriding this, because shopt login_shell prints the same whether the shell is interactive or not, and the UID is also the same.

You can get the user's default shell thusly:

$ getent passwd $USER | cut --delimiter=: --fields=7
/bin/bash

Combining them:

$ sudo -u $USER $(getent passwd $USER | cut --delimiter=: --fields=7) -ic umask
0002

Upvotes: 2

Related Questions