Home > Articles > Software Development & Management > Architecture and Design

This chapter is from the book

Time-of-Check, Time-of-Use

Not every race condition occurs in threaded programs. Any time that there are multiple threads of execution at once, race conditions are possible, regardless of whether they are really simultaneous as in a distributed system, such as on a single-processor multitasking machine. Therefore, multiple processes on a single machine can have race conditions between them when they operate on data that may be shared. What kinds of data may be shared? Although some systems allow you to share memory between processes, all systems allow processes to share files. File-based race conditions are the most notorious in terms of security-critical race conditions.

Note that this kind of race condition is primarily a problem on UNIX machines, mostly because local access is usually required. Much of the time, if an attacker can remotely break into a Windows machine, the attacker already has all the access necessary for whatever nefarious ends the attacker has in mind. Also, many Windows machines are not really multiuser machines. Nonetheless, this does not make security-critical, file-based race conditions impossible on a Windows machine, and you should still watch out for them. The Windows API for opening files makes these kinds of race conditions much more difficult, but they are still possible. 1 Most file-based race conditions that are security hazards follow a common formula. There is a check on some property of the file that precedes the use of that file. The check needs to be valid at the time of use for proper behavior, but may not be. (Recall the elevator problem.) Such flaws are called time-of-check, time-of-use flaws, often abbreviated TOCTOU. In the canonical example, a program running setuid root is asked to write a file owned by the user running the program. The root user can write to any file it wants, so the program must take care not to write to anything unless the actual user has permission to do so. The preferred way to solve this problem is to set the EUID to the UID running the program. However, programmers commonly use the call access in an attempt to get the same results:

/* access returns 0 on success */ 
if(!access(file, W_OK)) { 
f = fopen(file, "wb+"); 
write_to_file(f); 
} 
else { 
fprintf(stderr, "Permission denied when trying to open %s.\n", 
  file); 
} 

The access call checks whether the real UID has permissions for a particular check, and returns 0 if it does. A text editor that needs to run as root for some reason may do this. In this case, the attacker can create a file that is malicious, such as a bogus /etc/passwd. It's then just a matter of exploiting the race condition to install it.

The window of vulnerability here is the time it takes to call fopen and have it open a file, after having called access(). If an attacker can replace a valid file to which the attacker has permissions to write with a file owned by root, all within that time window, then the root file will be overwritten. The easiest way to do this is by using a symbolic link, which creates a file that acts very much like any other file, except that it "points to" some other file. The attacker creates a dummy file with his permissions, and then creates a symbolic link to it:

$ touch dummy 
$ ln –s dummy pointer 
$ 

Now, the attacker tells the program to open the file pointer. The attacker's goal is to perform a command such as the following within the window of vulnerability:

$ rm pointer; ln –s /etc/passwd pointer 

If successful, the program will overwrite the system password file. The attacker will have a better chance of success if using a C program that makes system calls directly rather than using the shell. To make the job easy, the attacker would write a program that fires up the editor, performs these commands, checks to see if the real password file was overwritten, and repeats the attack until successful. Problems like this are unfortunately common. A well-known, similar problem in old versions of xterm provides a classic example.

When it comes to exploitable file system race conditions, there are a few things that should be true. Usually, the attacker must have access to the local machine, legitimate or not. Also, the program with the race condition needs to be running with an EUID of root. The program must have this EUID for the period of time over which the race condition exists. Otherwise, the attacker will not be able to obtain root privileges, only the privileges he already has. There is no sense in running a race for your own privilege!

Broken passwd

Let's look at a historic case of a TOCTOU problem (introduced in [Bishop, 1996]): a broken version of the passwd command on SunOS and HP/UX machines. The UNIX utility program passwd allows someone to change a password entry, usually their own. In this particular version of the program, passwd took the name of a password file to manipulate as one of its parameters. The broken version of passwd works as follows when the user inputs a passwd file to use:

passwd step 1. Open the password file and read it in, retrieving the entry for the user running the program.

passwd step 2. Create and open a temporary file called ptmp in the same directory as the password file.

passwd step 3. Open the password file again, copying the unchanged contents into ptmp, while updating modified information.

passwd step 4. Close both the password file and ptmp, then rename ptmp to be the password file.

Let's pretend we're the attacker, and that we can "step" the activities of passwd at will (causing it to wait for us in between steps while we modify the file system). Of course, in practice, we need to automate our attack, and run it multiple times in parallel with the passwd process until we hit just the right interleaving.

In this attack, we are going to overwrite some other user's .rhosts file so that we can log in as that user. We could just as easily write over the system password file. We'll also use symbolic linking on a directory level, instead of a file level.

Figure 9–1A shows the state of the file system just before our attack begins. Note that we're running our attack in our own directory, attack-dir, within which we'll create a subdirectory pwd and the file .rhosts. We also need to fill the .rhosts file with valid information (a simulated password file entry with a blank password). And finally, we run passwd itself.

Here's how to do this in a generic UNIX shell:

$ mkdir pwd 
$ touch pwd/.rhosts 
$ echo "localhost attacker :::::" >> pwd/.rhosts 
$ ln –s pwd link 
$ passwd link/.rhosts 

Figure 9–1A The state of the system after step 1 of the passwd race condition.

Figure 9–1B The state of the system after step 2 of the passwd race condition.

And then . . .

passwd step 1. Open and read the password file (link/.rhosts) to retrieve the entry for the user running the program. Just after step 1, passwd will have opened and read the file we created (link/.rhosts). The system is now in a situation similar to what is shown in Figure 9–1A. Before step 2 runs, we need to change link quickly to point to target-dir. This is the part that must happen with exactly the right timing. (In our pretend version of the attack, remember that we have control over what happens when.) Change the link as follows: rm link; ln –s target-dir link

(target-dir actually has to be specified relative to the root directory, but we'll ignore that detail in our simplified example).

passwd step 2. Create and open a temporary file called ptmp in the same directory as the password file (link/.rhosts). Note that passwd is now using a different location to write out the file ptmp. It ends up creating a file in target-dir called ptmp, because link now points to target-dir. Now quickly, before step 3 happens, we need to change the link to point back to our directory as follows: rm link; ln –s pwd link. We need to do this because the passwd file is going to be looking for an entry in it with our UID. If we're attacking the system password file, we wouldn't have to go through this step (see Figure 9–1B).

passwd step 3. Open the password file (link/.rhosts in attack-dir) again and copy the contents of ptmp while updating the changed information. Note that the file ptmp has not yet been closed, so it is still the file that lives in target-dir. This means that the .rhosts file is being read from our pwd directory and is being copied to the temporary file in target-dir. See Figure 9–2A.

Finally, once again, we need to change link quickly to point to the target-dir: rm link; ln –s target-dir link. We do this so that when passwd performs step 4, its version of link points to target-dir again.

passwd step 4. Close both the password file and ptmp, then rename ptmp to be the password file. After all this work, our attack will have written a new .rhosts file into target-dir. This allows us to log in to the target's account with no password (remember all those ::::'s?) and become the user who owns target-dir. Note that we can do this for target-dir equivalent to root; meaning, that if we choose the right target, we can win complete control over the machine. See Figure 9–2B.

Figure 9–2A The state of the system after step 3 of the passwd race condition.

Figure 9–2B The state of the system after step 4 of the passwd race condition.

Clearly, timing is everything in this attack. The directory pointed to through link must be pointed at precisely the right place in every stage of the attack. Getting this to happen is not always possible. In a real version of this attack we create a program to do all of the renaming and hope that our script interleaves in exactly the way described earlier with the passwd process. We do have one huge advantage in getting this to happen, though. We can run passwd as many times as we want and attack it over and over again in an automated fashion until the attack is successful.

Avoiding TOCTOU Problems

One thing you should do to help avoid TOCTOU problems is to avoid any file system call that takes a filename for an input, instead of a file handle or a file descriptor. By dealing with file descriptors or file pointers, we ensure that the file on which we are operating does not change behind our back after we first start dealing with it. Instead of doing a stat() on a file before opening it, open the file and then do an fstat() on the resulting file descriptor. Sometimes there is no reasonable alternative to a call, whether it is a check or use (and some calls can be both). In such cases, you can still use the call, but you must do so carefully. We detail a technique for doing so in the next section.

Additionally, you should avoid doing your own access checking on files. Leave that to the underlying file system. This means that you should never use the access() call. Instead, set the EUID and the EGID to the appropriate user, drop any extra group privileges by calling setgroups(0,0);.

Also, when opening arbitrary files, we recommend that you start by using open() and then using fdopen to create a FILE object once you're sure you have the proper file. To be sure you have the proper file, we recommend the following approach:

  1. lstat() the file before opening it, saving the stat structure. Note that this may be susceptible to a race condition if we perform no other checks.

  2. Perform an open().

  3. fstat() the file descriptor returned by the open() call, saving the stat structure.

  4. Compare three fields in the two stat structures to be sure they are equivalent: st_mode, st_ino and st_dev. If these comparisons are successful, then we know the lstat() call happened on the file we ultimately opened. Moreover, we know that we did not follow a symbolic link (which is why we used lstat() instead of stat()).

If the file does not exist, lstat() says so, but an attacker may be able to place a file there where there isn't one, before you perform the open(). To thwart this problem, pass the O_CREAT and O_EXCL flags to open(), which causes the open to fail if the file cannot be created.

As an example of these techniques, here is some code that shows how to open a file safely in a way that simulates fopen's w+ mode. That is, the file should be created if it doesn't exist. If it does exist, then it will be truncated:

include <sys/stat.h>
include <sys/types.h>
include <sys/stat.h>
include <fcntl.h>
include <unistd.h>
include <stdio.h>
include <errno.h>
FILE *safe_open_wplus(char *fname) { 
struct stat lstat_info, fstat_info; 
FILE *fp; char *mode = "rb+"; /*We perform our own truncation.*/ 
int fd; 

if(lstat(fname, &lstat_info) == –1) { 
/* If the lstat() failed for reasons other than the file 
  not existing, return 0, specifying error. */
if( errno != ENOENT ) { return 0; } 
if((fd = open(fname, O_CREAT|O_EXCL| O_RDWR, 0600)) == –1) { 
return 0; } mode = "wb"; 
} 
else {
/* Open an existing file */
if((fd = open(fname, O_RDWR)) == –1) { return 0; } 
if(fstat(fd, &fstat_info) == –1 || 
lstat_info.st_mode != fstat_info.st_mode || 
lstat_info.st_ino != fstat_info.st_ino || 
lstat_info.st_dev != fstat_info.st_dev ) { 

  		close(fd); 
return 0; 
} 
   /* Turn the file into an empty file, to mimic w+ semantics. */ 
   ftruncate(fd, 0); 
} 
   /* Open an stdio file over the low-level one */ fp = fdopen(fd, mode); if(!fp) { 
   close(fd); unlink(fname); return 0; 
  } 
  return fp; 
} 

Note in the previous code that we truncate the file ourselves, and only after ensuring that it is safe to do so.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020