2.3. Determining Whether a User Has Access to a File on Unix
Problem
Your program is running with extra permissions because its executable has the setuid or setgid bit set. You need to determine whether the user running the program will be able to access a file without the extra privileges granted by setuid or setgid.
Solution
Temporarily drop privileges to the user and group for which access is to be checked. With the process’s privileges lowered, perform the access check, then restore privileges to what they were before the check. See Recipe 1.3 for additional discussion of elevated privileges and how to drop and restore them.
Discussion
It is always best to allow the operating system to do the bulk of the work of performing access checks. The only way to do so is to manipulate the privileges under which the process is running. Recipe 1.3 provides implementations for functions that temporarily drop privileges and then restore them again.
When performing access checks on files, you need to be careful to
avoid the types of race conditions known as
Time of Check, Time of Use
(TOCTOU), which are illustrated in Figure 2-1 and Figure 2-2. These
race
conditions occur when access is checked before opening a file. The
most common way for this to occur is to use the access(
)
system
call to verify access to a file, and then to use open(
)
or
fopen( )
to open the file if the return from
access( )
indicates that access will be granted.
The problem is that between the time the access check via ...
Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.