Access () Protective Hole

I am writing a shell and find a recommendation for access () to check if a file exists, it can be read, etc. It seems to be very easy to implement and faster than stat (). When I started looking for the man page, I noticed that it was NOT recommended for use, because it could lead to a security hole. This page says:

Using access () to check if the user is allowed, for example. opening a file before doing this using open (2) creates a security hole because the user can use the short time between checking and opening the file to manipulate it.

Does anyone know how this can be used, or if it only refers to using open () after checking the file? I know that many people say using stat () instead, but access () is so easy to implement, especially for the shell in which I used it.

thanks

+3
source share
3 answers

This is the TOCTOU race (check time for update time). An attacker can replace a file to which he has access for a symbolic link to something he does not have access between access() and open() calls. Use faccessat() or fstat() . In general, open the file once and use f*() functions in it (for example: fchown() , ...).

+5
source

One thing I can think of, although it seems weak, is access () uses real, not efficient uid and gid. This presumably allows you to use the setuid program (which runs as a regular user, but which gets owner permissions) to check if the caller can read the file, to prevent that user from unintentionally granting access to a file that they cannot read, possibly using some symbolic link or hard link trick. I cannot find any evidence that this is possible, or that this is not possible with stat (), but imagine this scenario:

 user executes program program is setuid, immediately gets all privs of root program checks file1 to ensure that user has access file1 is a hardlink to file2, which user has access to user changes file1 to hardlink to file3 (/etc/shadow or something like that) program reads file1 and does something to it (print, convert, whatever) user now has access to a file they shouldn't 
0
source

The template seems to call access() or stat() to determine if it is possible to open the file and then open it if you have permission.

Instead, it's usually best to just go ahead and try to open it and then check if the attempt succeeded (and if not, why). This avoids the time interval between checking and trying to open the file.

0
source

Source: https://habr.com/ru/post/920694/


All Articles