Way in Linux to have one non root user check if another non root user has permissions to a folder / file

filespermissions

The scenario is this – I have a command line program that might not run as root, part of the requirements is to warn if another user has write permissions to some folder / file

e.g.

  • I'm running as non root user A
  • I would like to get the answer to the question: "does user B has write permissions to folder F"

So my questions are

  • Is it even possible to do as a root user? if so how?
  • Is there any way to do it as a non root user?

Best Answer

In general, the only way to know if user B can write to directory D is for user B to attempt to write to directory D.

So, as root, you can su to the user and try it. Though that may not be 100% accurate as the user logging in and entering his password may change things (e.g., a pam module might set up crypto keys based on the user's password).

Almost as accurate, again as root, you can su to the user and use the access(2) syscall or similar. Probably, this is what the shell does if you use test -w, and also be what /usr/bin/test does. Though as the manpage warns, on NFSv2, the actual check is done by the server, but the test for the access syscall is done locally, so it may be wrong. Similarly, FUSE filesystems may do the same.

(The access(2) manpage also mentions a race condition which is fundamental to what you're doing: B's permissions on D might change between when you check and when B actually tries to write to D.)

Other than that, you have to decide how accurate you are willing to accept:

  1. You could stat the directory, and check the users & groups (as several of the other answers show)
  2. You could additionally check the ACLs on the directory.

But even if you do that, the following will trip you up:

  1. With NFS and various other network filesystems, the server decides if access is permitted. It can make that decision based on, well, whatever it likes. Consider e.g., the various squash NFS export options.
  2. Permissions checks are actually done by the filesystem; non-Unix filesystems may give unexpected answers (how is the Unix user mapped to a SID for NTFS?). All bets are off with e.g., FUSE filesystems.
Related Question