21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.7 Restricting Access Permissions for New<br />

Files on Unix<br />

<strong>Problem</strong><br />

You want to restrict the initial access permissions assigned to a file created by your<br />

program.<br />

Solution<br />

On Unix, the operating system stores a value known as the umask for each process it<br />

uses when creating new files on behalf of the process. The umask is used to disable<br />

permission bits that may be specified by the system call used to create files.<br />

Discussion<br />

Remember that umasks apply only on file or directory creation. Calls<br />

to chmod( ) and fchmod( ) are not modified by umask settings.<br />

When a process creates a new file, it specifies the access permissions to assign the<br />

new file as a parameter to the system call that creates the file. The operating system<br />

modifies the access permissions by computing the intersection of the inverse of the<br />

umask and the permissions requested by the process. The access permission bits that<br />

remain after the intersection is computed are what the operating system actually uses<br />

for the new file. In other words, in the following example code, if the variable<br />

requested_permissions contained the permissions passed to the operating system to<br />

create a new file, the variable actual_permissions would be the actual permissions<br />

that the operating system would use to create the file.<br />

requested_permissions = 0666;<br />

actual_permissions = requested_permissions & ~umask( );<br />

A process inherits the value of its umask from its parent process when the process is<br />

created. Normally, the shell sets a default umask of either 022 (disable group- and<br />

world-writable bits) or 02 (disable world-writable bits) when a user logs in, but users<br />

have free reign to change the umask as they want. Many users are not even aware of<br />

the existence of umasks, never mind how to set them appropriately. Therefore, the<br />

umask value as set by the user should never be trusted to be appropriate.<br />

When using the open( ) system call to create a new file, you can force more restrictive<br />

permissions to be used than what the user’s umask might allow, but the only<br />

way to create a file with less restrictive permissions is either to modify the umask<br />

Restricting Access Permissions for New Files on Unix | 55<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!