Simulating O_NOFOLLOW (2): Is this other approach safe?
        Posted  
        
            by Daniel Trebbien
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Daniel Trebbien
        
        
        
        Published on 2010-05-30T12:17:24Z
        Indexed on 
            2010/05/30
            12:22 UTC
        
        
        Read the original article
        Hit count: 400
        
As a follow-up question to this one, I thought of another approach which builds off of @caf's answer for the case where I want to append to file name and create it if it does not exist.
Here is what I came up with:
- Create a temporary directory with mode 0700 in a system temporary directory on the same filesystem as file 
name. - Create an empty, temporary, regular file (
temp_name) in the temporary directory (only serves as placeholder). - Open file 
namefor reading only, just to create it if it does not exist. The OS may follownameif it is a symbolic link; I don't care at this point. - Make a hard link to 
nameattemp_name(overwriting the placeholder file). If thelinkcall fails, then exit. (Maybe someone has come along and removed the file atname, who knows?) - Use 
lstatontemp_name(now a hard link). IfS_ISLNK(lst.st_mode), then exit. opentemp_namefor writing, append (O_WRONLY | O_APPEND).- Write everything out. Close the file descriptor.
 unlinkthe hard link.- Remove the temporary directory.
 
(All of this, by the way, is for an open source project that I am working on. You can view the source of my implementation of this approach here.)
Is this procedure safe against symbolic link attacks? For example, is it possible for a malicious process to ensure that the inode for name represents a regular file for the duration of the lstat check, then make the inode a symbolic link with the temp_name hard link now pointing to the new, symbolic link?
I am assuming that a malicious process cannot affect temp_name.
© Stack Overflow or respective owner