How to disallow access to a file for one user?

A Unix permission primer:

Every file has an user. This is a user on the system. Every file also has a group. This is a group on the system. A user can be in one or more groups. A file has exactly one user and one group that “own” the file.1

So what does a number like 0444 mean?

The first number is used for some special flags such as sticky, setuid, setgid. We don’t need to bother with that right now. Just remember to set it to 0

The next three numbers indicate the three permissions: one for the user, group, and other (everybody that is not user or group), in that order.

To set the permissions we use a number from zero to seven (an octal number). This is actually a bitmask. 1 is for execute, 2 is for write, 4 is for read.

In a table it looks like:2

N   Description                    ls output

0   No read, no write, no execute    ---
1   No read, no write, execute       --x
2   No read, write, no execute       -w-
3   No read, write, execute          -wx
4   Read, no write, no execute       r--
5   Read, no write, execute          r-x
6   Read, write, no execute          rw-
7   Read, write, execute             rwx

read and write should be self-explanatory. execute means that you can run a file with ./ls (this is not a security measure, and can be circumvented by the way). Note that directories are also files on Unix systems such as Linux. A directory must have the execute bit set if you want to be able to cd into it.

The number you’ll use most often are:

  • 7, for full access
  • 6, for full access except execute
  • 4, for read only.

So, if you look at your command os.chmod(path, 0444) we see that you’ve set read-only access for all users. This is not what you want.

The correct permissions depend on which user and group own the file. If the file does not belong to the user you want to disallow access to, and is not in the group that the file belongs to, you can use:

os.chmod(path, 0440)

If we look at the table above, we see that it means:

  • Read, write, no execute for user.
  • Read, write, no execute for group.
  • NO permissions for other.

If the file does not belong to the user you want to disallow access to, and is in the group that the file belongs to, you can use:

os.chmod(path, 0400)

This will make it readable for the user only. Note that this may have side-effects, as everyone else in the group can’t read it now either.

However, if the file belongs to the user, then you need to change the file user. This can be done with the os.chown() function. e.g.:

os.chown(path, 'martin')
os.chmod(path, 0400)

1: You can use ACLs if you want to assign more users or groups to a file, but in >95% there is no need to, and it only adds complexity that may be difficult to manage. It’s often disabled by default.

2: Table lifted from the FreeBSD handbook

Leave a Comment