21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

directory /home/myhome/stuff/securestuff. If the directory /home/myhome/stuff is writable<br />

by another user, that user could rename the directory securestuff to something<br />

else. The result would be that your program would no longer be able to find the file<br />

containing its sensitive data.<br />

Even if the securestuff directory is owned by the user who owns the file containing<br />

the sensitive data, and the permissions on the directory prevent other users from<br />

writing to it, the permissions that matter are on the parent directory, /home/myhome/<br />

stuff. This same problem exists for every directory in the path, right up to the root<br />

directory.<br />

In this recipe we present a function, spc_is_safedir( ), for checking all of the directories<br />

in a path specification on Unix. It traverses the directory tree from the bottom<br />

back up to the root, ensuring that only the owner or superuser have write access to<br />

each directory.<br />

The spc_is_safedir( ) function requires a single argument specifying the directory to<br />

check. The return value from the function is –1 if some kind of error occurs while<br />

attempting to verify the safety of the path specification, 0 if the path specification is<br />

not safe, or 1 if the path specification is safe.<br />

46 | Chapter 2: Access Control<br />

On Unix systems, a process has only one current directory; all threads<br />

within a process share the same working directory. The code presented<br />

here changes the working directory as it works; therefore, the<br />

code is not thread-safe!<br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

int spc_is_safedir(const char *dir) {<br />

DIR *fd, *start;<br />

int rc = -1;<br />

char new_dir[PATH_MAX + 1];<br />

uid_t uid;<br />

struct stat f, l;<br />

if (!(start = opendir("."))) return -1;<br />

if (lstat(dir, &l) = = -1) {<br />

closedir(start);<br />

return -1;<br />

}<br />

uid = geteuid( );<br />

do {<br />

if (chdir(dir) = = -1) break;<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!