Secure Programmer: Prevent Race Conditions

Total Page:16

File Type:pdf, Size:1020Kb

Secure Programmer: Prevent Race Conditions Secure programmer: Prevent race conditions Resource contention can be used against you David Wheeler ([email protected]), Research Staff Member, Institute for Defense Analyses Summary: Learn what a race condition is and why it can cause security problems. This article shows you how to handle common race conditions on UNIX-like systems, including how to create lock files correctly, alternatives to lock files, how to handle the file system, and how to handle shared directories -- and, in particular, how to correctly create temporary files in the /tmp directory. You'll also learn a bit about signal handling. Date: 07 Oct 2004 Level: Intermediate Also available in: Japanese Activity: 9098 views Comments: (View | Add comment - Sign in) Rate this article Using a stolen password, "Mallory" managed to log into an important server running Linux. The account was limited, but Mallory knew how to cause trouble with it. Mallory installed and ran a trivial program with odd behavior: It quickly created and removed many different symbolic link files in the /tmp directory, using a multitude of processes. (When accessed, a symbolic link file, also called a symlink, redirects the requester to another file.) Mallory's program kept creating and removing many different symlinks pointing to the same special file: /etc/passwd, the password file. A security precaution on this server was that every day, it ran the security program Tripwire -- specifically, the older version, 2.3.0. As Tripwire started up, it tried to create a temporary file, as many programs do. Tripwire looked and found that there was no file named /tmp/twtempa19212, so that appeared to be a good name for a temporary file. But after Tripwire checked, Mallory's program then created a symlink with that very name. This was no accident. Mallory's program was designed to create the very file names most likely to be used by Tripwire. Tripwire then opened up the file and starting writing temporary information. But instead of creating a new empty file, Tripwire was now overwriting the password file. From then on, no one -- not even the administrators -- could log into the system, because the password file had been corrupted. It could have been worse. Mallory's attack could have overwritten any file, including critical data stored on the server. Introduction to race conditions The story is hypothetical; Mallory is a conventional name for an attacker. But the attack, and the vulnerability it exploits, are all too common. The problem is that many programs are vulnerable to a security problem called a race condition. A race condition occurs when a program doesn't work as it's supposed to because of an unexpected ordering of events that produces contention over the same resource. Notice that a race condition doesn't need to involve contention between two parts of the same program. Many security problems occur if an outside attacker can interfere with a program in unexpected ways. For example, Tripwire V2.3.0 determined that a certain file didn't exist, and then tried to create it, not taking into account that the file could have been created by an attacker between those two steps. Decades ago, race conditions were less of a problem. Then, a computer system would often run one simple sequential program at a time, and nothing could interrupt it or vie with it. But today's computers typically have a large number of processes and threads running at the same time, and often have multiple processors executing different programs simultaneously. This is more flexible, but there's a danger: If those processes and threads share any resources, they may be able to interfere with each other. In fact, a vulnerability to race conditions is one of the more common vulnerabilities in software, and on UNIX-like systems, the directories /tmp and /var/tmp are often misused in a way that opens up race conditions. But first, we need to know some terminology. All UNIX-like systems support user processes; each process has its own separate memory area, normally untouchable by other processes. The underlying kernel tries to make it appear that the processes run simultaneously. On a multiprocessor system, they really can run simultaneously. A process notionally has one or more threads, which share memory. Threads can run simultaneously, as well. Since threads can share memory, there are usually many more opportunities for race conditions between threads than between processes. Multithreaded programs are much harder to debug for that very reason. The Linux kernel has an elegant basic design: There are only threads, and some threads happen to share memory with other threads (thus implementing traditional threads), while others don't (thus implementing separate processes). To understand race conditions, let's first look at a trivial C statement: Listing 1. Trivial C statement b = b + 1; Looks pretty simple, right? But let's pretend that there are two threads running this line of code, where b is a variable shared by the two threads, and b started with the value 5. Here's a possible order of execution: Listing 2. Possible order of execution with shared "b" (thread1) load b into some register in thread 1. (thread2) load b into some register in thread 2. (thread1) add 1 to thread 1's register, computing 6. (thread2) add 1 to thread 2's register, computing 6. (thread1) store the register value (6) to b. (thread2) store the register value (6) to b. We started with 5, then two threads each added one, but the final result is 6 -- not the expected 7. The problem is that the two threads interfered with each other, causing a wrong final answer. In general, threads do not execute atomically, performing single operations all at once. Another thread may interrupt it between essentially any two instructions and manipulate some shared resource. If a secure program's thread is not prepared for these interruptions, another thread may be able to interfere with the secure program's thread. Any pair of operations in a secure program must still work correctly if arbitrary amounts of another thread's code is executed between them. The key is to determine, when your program is accessing any resource, if some other thread could interfere with it. Back to top Solving race conditions The typical solution to a race condition is to ensure that your program has exclusive rights to something while it's manipulating it, such as a file, device, object, or variable. The process of gaining an exclusive right to something is called locking. Locks aren't easy to handle correctly. One common problem is a deadlock (a "deadly embrace"), in which programs get stuck waiting for each other to release a locked resource. Most deadlocks can be prevented by requiring all threads to obtain locks in the same order (for example, alphabetically, or "largest grain" to "smallest grain"). Another common problem is a livelock, where programs at least manage to gain and release a lock, but in such a way that they can't ever progress. And if a lock can get stuck, it can be very difficult to make it gracefully release. In short, it's often difficult to write a program that correctly, in all circumstances, locks and releases locks as needed. A common mistake to avoid is creating lock files in a way that doesn't always lock things. You should learn to create them correctly or switch to a different locking mechanism. You'll also need to handle races in the file system correctly, including the ever-dangerous shared directories /tmp and /var/tmp, and how signals can be used safely. The sections below describe how to deal with them securely. Back to top Lock files UNIX-like systems have traditionally implemented a lock shared between different processes by creating a file that indicates a lock. Using a separate file to indicate a lock is an example of an advisory lock, not a mandatory lock. In other words, the operating system doesn't enforce the resource sharing through the lock, so all processes that need the resource must cooperate to use the lock. This may appear primitive, but not all simple ideas are bad ones. Creating separate files makes it easy to see the state of the system, including what's locked. There are some standard tricks to simplify clean-up if you use this approach -- in particular, to remove stuck locks. For example, a parent process can set a lock, call a child to do the work (make sure only the parent can call the child in a way that it can work), and when the child returns, the parent releases the lock. Or, a cron job can look at the locks, which contain a process id. If the process isn't alive, it would erase the lock and restart the process. Finally, the lock file can be erased as part of system start-up, so that if the system suddenly crashes, you won't have a stuck lock later. If you're creating separate files to indicate a lock, there's a common mistake: calling creat() or its open() equivalent (the mode O_WRONLY | O_CREAT | O_TRUNC). The problem is that root can always create files this way, even if the lock file already exists -- which means that the lock won't work correctly for root. The simple solution is to use open() with the flags O_WRONLY | O_CREAT | O_EXCL (and permissions set to 0, so that other processes with the same owner won't get the lock). Note the use of O_EXCL, which is the official way to create "exclusive" files. This even works for root on a local file system.
Recommended publications
  • Software Security for Open-Source Systems
    Open-Source Security Software Security for Open-Source Systems Debate over whether open-source software development leads to more or less secure software has raged for years. Neither is in- trinsically correct: open-source software gives both attackers and defenders greater power over system security. Fortunately, several security-enhancing technologies for open-source sys- tems can help defenders improve their security. classify methods that CRISPIN ome people have claimed that open-source ensure and enforce COWAN software is intrinsically more secure than closed the “nothing else” part into three broad categories: WireX source,1 and others have claimed that it’s not.2 Communications Neither case is absolutely true: they are essen- • Software auditing, which prevents vulnerabilities by Stially flip sides of the same coin. Open source gives both searching for them ahead of time, with or without auto- attackers and defenders greater analytic power to do matic analysis something about software vulnerabilities. If the defender • Vulnerability mitigation, which are compile-time tech- does nothing about security, though, open source just niques that stop bugs at runtime gives that advantage away to the attacker. • Behavior management, which are operating system fea- However, open source also offers great advantages to tures that either limit potential damage or block specif- the defender, giving access to security techniques that are ic behaviors known to be dangerous normally infeasible with closed-source software. Closed source forces users to accept the level of security diligence Software auditing that the vendor chooses to provide, whereas open source The least damaging software vulnerability is the one that lets users (or other collectives of people) raise the bar on never happens.
    [Show full text]
  • Version 7.8-Systemd
    Linux From Scratch Version 7.8-systemd Created by Gerard Beekmans Edited by Douglas R. Reno Linux From Scratch: Version 7.8-systemd by Created by Gerard Beekmans and Edited by Douglas R. Reno Copyright © 1999-2015 Gerard Beekmans Copyright © 1999-2015, Gerard Beekmans All rights reserved. This book is licensed under a Creative Commons License. Computer instructions may be extracted from the book under the MIT License. Linux® is a registered trademark of Linus Torvalds. Linux From Scratch - Version 7.8-systemd Table of Contents Preface .......................................................................................................................................................................... vii i. Foreword ............................................................................................................................................................. vii ii. Audience ............................................................................................................................................................ vii iii. LFS Target Architectures ................................................................................................................................ viii iv. LFS and Standards ............................................................................................................................................ ix v. Rationale for Packages in the Book .................................................................................................................... x vi. Prerequisites
    [Show full text]
  • On Trends in Low-Level Exploitation
    On trends in low-level exploitation Christian W. Otterstad Department of Informatics, University of Bergen Abstract Low-level computer exploitation and its mitigation counterpart has accumulated some noteworthy history. Presently, especially in academia, it features a plethora of mitigation techniques and also various possible modes of attack. It has seen numerous developments building upon basic methods for both sides and certain trends have emerged. This paper is primarily an overview paper, focusing especially on x86 GNU/Linux. The basic reasons inherent for allowing low-level exploitability are identified and explained to provide background knowledge. The paper furthermore describes the history, present state of the art and future developments that are topical and appear to be important in the field. Several attack and defense techniques have overlapping notions with not always obvious differences. Herein the notion of the bar being raised for both exploits and mitigation methods is examined and extrapolated upon based on the known relevant present state and history. The difference between academia and the industry is discussed especially where it relates to application of new mitigation techniques. Based on this examination some patterns and trends are identified and a conjecture for the likely future development of both is presented and justified. This paper was presented at the NIK-2016 conference; see http://www.nik.no/. 1 Introduction and earlier related work In 1972 the paper “Computer Security Technology Planning Study” was published [1]. Since then, research surrounding the main ideas in this paper has grown to become a ma- ture and complex field in its own right. There are many different exploitation techniques and mitigation techniques.
    [Show full text]
  • Hardening Linux
    eBooks-IT.org 4444_FM_final.qxd 1/5/05 12:39 AM Page i eBooks-IT.org Hardening Linux JAMES TURNBULL 4444_FM_final.qxd 1/5/05 12:39 AM Page ii eBooks-IT.org Hardening Linux Copyright © 2005 by James Turnbull All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN (pbk): 1-59059-444-4 Printed and bound in the United States of America 987654321 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Lead Editor: Jim Sumser Technical Reviewer: Judith Myerson Editorial Board: Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis, Jason Gilmore, Chris Mills, Dominic Shakeshaft, Jim Sumser Project Manager: Kylie Johnston Copy Edit Manager: Nicole LeClerc Copy Editor: Kim Wimpsett Production Manager: Kari Brooks-Copony Production Editor: Kelly Winquist Compositor: Linda Weidemann Proofreader: Lori Bring Indexer: Kevin Broccoli Artist: Kinetic Publishing Services, LLC Cover Designer: Kurt Krames Manufacturing Manager: Tom Debolski Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013, and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112 Heidelberg, Germany. In the United States: phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], or visit http://www.springer-ny.com.
    [Show full text]
  • Powerview Command Reference
    PowerView Command Reference TRACE32 Online Help TRACE32 Directory TRACE32 Index TRACE32 Documents ...................................................................................................................... PowerView User Interface ............................................................................................................ PowerView Command Reference .............................................................................................1 History ...................................................................................................................................... 12 ABORT ...................................................................................................................................... 13 ABORT Abort driver program 13 AREA ........................................................................................................................................ 14 AREA Message windows 14 AREA.CLEAR Clear area 15 AREA.CLOSE Close output file 15 AREA.Create Create or modify message area 16 AREA.Delete Delete message area 17 AREA.List Display a detailed list off all message areas 18 AREA.OPEN Open output file 20 AREA.PIPE Redirect area to stdout 21 AREA.RESet Reset areas 21 AREA.SAVE Save AREA window contents to file 21 AREA.Select Select area 22 AREA.STDERR Redirect area to stderr 23 AREA.STDOUT Redirect area to stdout 23 AREA.view Display message area in AREA window 24 AutoSTOre ..............................................................................................................................
    [Show full text]
  • Rhd256.Bowez Notes.2006-07-20.Txt Thu Jul 20 15:31
    ../rhd256.bowez_notes.2006-07-20.txt Thu Jul 20 15:31:29 2006 1 ==> ./01_intro/notes.txt <== ---------------------------------------------------------------------- ---------------------------------------------------------------------- 2.3 Bash Special Characaters 1.3 Prerequisates ---------------------------------------------------------------------- ---------------------------------------------------------------------- ------------------------------------------------------------------ Familiarity: Redirection (Stream Manipulation) ------------------------------------------------------------------ the classroom setup (server1, station1, etc...) the "pub" directory every process has three default file descriptors (streams): Common Tools: 0: stdin 1: stdout terminal: 2: stderr changing fonts, etc.... - by default, all are connected to the terminal. editors: - In RHL, can be accessed by /dev/std{in,out,err} emacs vi, vim, gvim < redirect descriptor input pico -w, gedit > redirect descriptor output (create or clobber) (less pager) >> redirect descriptor output (create or append) finding information: 2>&1 bind one descriptor to another (i.e., combine stderr and stdout) --help, -h >& bash shortcut for the same man pages (chapters) info pages (info, pinfo, nautilus) examples: /usr/share/doc grep root /etc/* rpm (-qf filename, -ql, -qi) grep root /etc/* > /tmp/out grep root /etc/* 2> /tmp/err ---------------------------------------------------------------------- grep root /etc/* > /tmp/out2 2> /tmp/err2 grep root /etc/* >& /tmp/all 1.4 Procedures
    [Show full text]
  • Detecting Exploit Code Execution in Loadable Kernel Modules
    Detecting Exploit Code Execution in Loadable Kernel Modules HaizhiXu WenliangDu SteveJ.Chapin Systems Assurance Institute Syracuse University 3-114 CST, 111 College Place, Syracuse, NY 13210, USA g fhxu02, wedu, chapin @syr.edu Abstract and pointer checks can lead to kernel-level exploits, which can jeopardize the integrity of the running kernel. Inside the In current extensible monolithic operating systems, load- kernel, exploitcode has the privilegeto interceptsystem ser- able kernel modules (LKM) have unrestricted access to vice routines, to modify interrupt handlers, and to overwrite all portions of kernel memory and I/O space. As a result, kernel data. In such cases, the behavior of the entire sys- kernel-module exploitation can jeopardize the integrity of tem may become suspect. the entire system. In this paper, we analyze the threat that Kernel-level protection is different from user space pro- comes from the implicit trust relationship between the oper- tection. Not every application-level protection mechanism ating system kernel and loadable kernel modules. We then can be applied directly to kernel code, because privileges present a specification-directed access monitoring tool— of the kernel environment is different from that of the user HECK, that detects kernel modules for malicious code ex- space. For example, non-executableuser page [21] and non- ecution. Inside the module, HECK prevents code execution executable user stack [29] use virtual memory mapping sup- on the kernel stack and the data sections; on the bound- port for pages and segments, but inside the kernel, a page ary, HECK restricts the module’s access to only those kernel or segment fault can lead to kernel panic.
    [Show full text]
  • Computer Security 03
    Computer Security 03. Program Hijacking & Code Injection Paul Krzyzanowski Rutgers University Spring 2019 September 25, 2019 CS 419 © 2019 Paul Krzyzanowski 1 Top vulnerability concerns for 2019 MITRE, a non-profit organization that manages federally-funded research & development centers, publishes a list of top security weaknesses Rank Name Score 1 Improper Restriction of Operations within the Bounds of a Memory Buffer 75.56 2 Cross-site Scripting 45.69 3 Improper Input Validation 43.61 4 Information Exposure 32.12 5 Out-of-bounds Read 26.53 6 SQL Injection 24.54 7 Use After Free 17.94 8 Integer Overflow or Wraparound 17.35 9 Cross-Site Request Forgery (CSRF) 15.54 10 14.10 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') https://cwe.mitre.org/top25/archive/2019/2019_cwe_top25.html September 25, 2019 CS 419 © 2019 Paul Krzyzanowski 2 Hijacking Getting software to do something different from what the user or developer expected Examples: • Redirect web browser to a malicious site • Change DNS (IP address lookup) results • Change search engine • Change search paths to load different libraries or have different programs run • Intercept & alter messages Code injection Getting a program to process data in a way that it changes the execution of a program September 25, 2019 CS 419 © 2019 Paul Krzyzanowski 3 Bugs and mistakes • Most attacks are due to – Social engineering: getting a legitimate user to do something – Or bugs: using a program in a way it was not intended • Attacked system may be further weakened because
    [Show full text]
  • 11.6. Tempfile — Generate Temporary Files and Directories — Python V2
    Navigation • index • modules | • next | • previous | • Python v2.6.4 documentation » • The Python Standard Library » • 11. File and Directory Access » 11.6. tempfile — Generate temporary files and directories¶ This module generates temporary files and directories. It works on all supported platforms. In version 2.3 of Python, this module was overhauled for enhanced security. It now provides three new functions, NamedTemporaryFile(), mkstemp(), and mkdtemp(), which should eliminate all remaining need to use the insecure mktemp() function. Temporary file names created by this module no longer contain the process ID; instead a string of six random characters is used. Also, all the user-callable functions now take additional arguments which allow direct control over the location and name of temporary files. It is no longer necessary to use the global tempdir and template variables. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity. The module defines the following user-callable functions: tempfile.TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])¶ Return a file-like object that can be used as a temporary storage area. The file is created using mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system. The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed.
    [Show full text]
  • GNU Coreutils Cheat Sheet (V1.00) Created by Peteris Krumins ([email protected], -- Good Coders Code, Great Coders Reuse)
    GNU Coreutils Cheat Sheet (v1.00) Created by Peteris Krumins ([email protected], www.catonmat.net -- good coders code, great coders reuse) Utility Description Utility Description arch Print machine hardware name nproc Print the number of processors base64 Base64 encode/decode strings or files od Dump files in octal and other formats basename Strip directory and suffix from file names paste Merge lines of files cat Concatenate files and print on the standard output pathchk Check whether file names are valid or portable chcon Change SELinux context of file pinky Lightweight finger chgrp Change group ownership of files pr Convert text files for printing chmod Change permission modes of files printenv Print all or part of environment chown Change user and group ownership of files printf Format and print data chroot Run command or shell with special root directory ptx Permuted index for GNU, with keywords in their context cksum Print CRC checksum and byte counts pwd Print current directory comm Compare two sorted files line by line readlink Display value of a symbolic link cp Copy files realpath Print the resolved file name csplit Split a file into context-determined pieces rm Delete files cut Remove parts of lines of files rmdir Remove directories date Print or set the system date and time runcon Run command with specified security context dd Convert a file while copying it seq Print sequence of numbers to standard output df Summarize free disk space setuidgid Run a command with the UID and GID of a specified user dir Briefly list directory
    [Show full text]
  • Securing Debian HOWTO
    Securing Debian HOWTO Javier Fernández-Sanguino Peña <[email protected]> v1.92 6 noviembre 2001Tue Oct 23 00:59:57 CEST 2001 Abstract This document describes the process of securing and hardening the default Debian installation. It covers some of the common taks to setup a secure network environment using Debian GNU/Linux. Copyright Notice Copyright c 2001 Alexander Reelsen, Javier Fernández-Sanguino Peña Copyright c 2000 Alexander Reelsen however it is distributed under the terms of the GNU free documentation license. This document is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. i Contents 1 Introduction 1 1.1 Download the HOWTO ................................... 1 1.2 Organizational Notes/Feedback ............................... 2 1.3 Prior knowledge ....................................... 2 1.4 Things that need to be written (TODO) ........................... 2 1.5 Changelog .......................................... 4 1.5.1 Version 1.92 .................................... 4 1.5.2 Version 1.91 .................................... 4 1.5.3 Version 1.9 ..................................... 4 1.5.4 Version 1.8 ..................................... 5 1.5.5 Version 1.7 ..................................... 5 1.5.6 Version 1.6 ..................................... 5 1.5.7 Version 1.5 ..................................... 6 1.5.8 Version 1.4 ..................................... 6 1.5.9 Version 1.3 ..................................... 6 1.5.10 Version 1.2 ..................................... 6 1.5.11 Version 1.1 ..................................... 6 1.5.12 Version 1.0 ..................................... 6 1.6 Credits ............................................ 7 2 Before you begin 9 2.1 What do you want this system for? ............................. 9 2.2 Be aware of general security problems ........................... 9 2.3 How does Debian handle security? ............................. 11 CONTENTS ii 3 Before and during the installation 13 3.1 Choose a BIOS password .................................
    [Show full text]
  • Securing Linux
    466_HTC_Linux_FM.qxd 10/2/07 10:05 AM Page iii How to Cheat at Securing Linux Mohan Krishnamurthy Eric S. Seagren Raven Alder Aaron W. Bayles Josh Burke Skip Carter Eli Faskha 466_HTC_Linux_FM.qxd 10/2/07 10:05 AM Page iv Elsevier, Inc., the author(s), and any person or firm involved in the writing, editing, or production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results to be obtained from the Work. There is no guarantee of any kind, expressed or implied, regarding the Work or its contents.The Work is sold AS IS and WITHOUT WARRANTY.You may have other legal rights, which vary from state to state. In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other incidental or consequential damages arising out from the Work or its contents. Because some states do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you. You should always use reasonable care, including backup and other appropriate precautions, when working with computers, networks, data, and files. Syngress Media®, Syngress®,“Career Advancement Through Skill Enhancement®,”“Ask the Author UPDATE®,” and “Hack Proofing®,” are registered trademarks of Elsevier, Inc.“Syngress:The Definition of a Serious Security Library”™,“Mission Critical™,” and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Elsevier, Inc. Brands and product names mentioned in this book are trademarks or service marks of their respective companies. PUBLISHED BY Syngress Publishing, Inc.
    [Show full text]