ptg From the Library of Lee Bogdanoff ptg Securing PHP Web Applications From the Library of Lee Bogdanoff Download at WoweBook.Com ptg This page intentionally left blank From the Library of Lee Bogdanoff Download at WoweBook.Com ptg Securing PHP Web Applications Tricia Ballad William Ballad Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City From the Library of Lee Bogdanoff Download at WoweBook.Com ptg Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for inci- dental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 corpsales@pearsontechgroup.com For sales outside the United States please contact: International Sales international@pearsoned.com Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Ballad, Tricia. Securing PHP web applications / Tricia Ballad, William Ballad. p. cm. Includes index. ISBN 978-0-321-53434-7 (pbk. : alk. paper) 1. PHP (Computer program language) 2. Web services—Security measures. 3. Internet—Computer programs—Security measures. 4. Application software—Development. I. Ballad, Bill. II. Title. QA76.73.P224B35 2009 005.8—dc22 2008042783 Copyright © 2009 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax (617) 671-3447 ISBN-13: 978-0-321-53434-7 ISBN-10: 0-321-53434-4 Text printed in the United States on recycled paper at Donnelley in Crawfordsville, Indiana First printing, December 2008 From the Library of Lee Bogdanoff Download at WoweBook.Com ptg v Contents Acknowledgments xiii About the Authors xv Part I Web Development Is a Blood Sport—Don't Wander onto the Field Without a Helmet 1 Chapter 1 Security Is a Server Issue and Other Myths 3 Reality Check 3 Security Is a Server Issue 5 Hackers Gain Control Through Insecure Applications 5 Programmers Can Harden Their Own Applications 6 Security Through Obscurity 7 Native Session Management Provides Plenty of Security 9 “My Application Isn’t Major Enough to Get Hacked” 9 The “Barbarians at the Gate” Syndrome 10 Wrapping It Up 10 Part II Is That Hole Really Big Enough to Drive a Truck Through? 11 Chapter 2 Error Handling 13 The Guestbook Application 13 Program Summary 13 Primary Code Listing 14 From the Library of Lee Bogdanoff Download at WoweBook.Com ptg CONTENTS vi Users Do the Darnedest Things . . . 15 I Wonder What Will Happen If I Do This? 15 Expecting the Unexpected 18 Building an Error-Handling Mechanism 19 Test for Unexpected Input 20 Decide What to Do with Erroneous Data 23 Make the System Mind-Numbingly Easy to Use 24 Wrapping It Up 26 Chapter 3 System Calls 27 Navigating the Dangerous Waters of exec(), system(), and Backticks 27 Using System Binaries with the SUID Bit and sudo 28 Using System Resources 29 Using escapeshellcmd() and escapeshellarg() to Secure System Calls 30 escapeshellcmd() 30 escapeshellarg() 30 Create an API to Handle All System Calls 31 Why Not Just Escape the Arguments and Be Done? 31 Validate User Input 32 Patch the Guestbook Application 32 The moveFile()Function 32 Changes to the Application 34 Wrapping It Up 34 Part III What's In a Name? More Than You Expect 35 Chapter 4 Buffer Overflows and Variable Sanitation 37 What Is a Buffer, How Does It Overflow, and Why Should You Care? 37 Buffers, Stacks, Heaps, and Memory Allocation 39 Consequences of a Buffer Overflow 42 Memory Allocation and PHP 42 Pay Attention to the Latest Security Alerts 44 Prevent Buffer Overflows by Sanitizing Variables 46 Premise: Data Is Guilty Until Proven Innocent, Especially If It Comes from Outside the Application 46 Where Does Data Come From? 48 How to Sanitize Data to Prevent Buffer Overflows 48 Patch the Application 49 Verify That We’re Running the Latest Stable Versions 49 Check Variable Sanitation 51 Wrapping It Up 52 Chapter 5 Input Validation 53 New Feature: Allow Users to Sign Their Guestbook Comments 53 From the Library of Lee Bogdanoff Download at WoweBook.Com ptg CONTENTS vii The Problem: Users Who Give You More Than You Asked For 54 Spammers 55 Injection Attacks 55 Assumptions: You Know What Your Data Looks Like 55 Database Constraints 56 Logical Constraints 56 The Solution: Regular Expressions to Validate Input 57 Tainted Data 57 Regexes 101 58 That Greedy, Lazy . . . Regex! 62 Common Input Validation Patterns 65 Wrapping It Up 67 Chapter 6 Filesystem Access: Accessing the Filesystem for Fun and Profit 69 Opening Files 69 Local Filesystem Access 69 Remote Filesystem Access 71 Preventing Remote Filesystem Exploits 72 Creating and Storing Files 73 Allowing File Uploads 73 Storing Files Safely 75 Changing File Properties Safely 76 Changing File Permissions in UNIX, Linux, and Mac OS X 76 Changing Windows File Permissions 77 Changing File Permissions in PHP 87 Patching the Application to Allow User-Uploaded Image Files 88 Modify the API 88 Create the Upload Form 90 Wrapping It Up 90 Part IV “Aw come on man, you can trust me” 93 Chapter 7 Authentication 95 What Is User Authentication? 95 Usernames and Passwords 97 Image Recognition 99 Privileges 100 How to Authenticate Users 101 Directory-Based Authentication 101 User Database 114 Storing Usernames and Passwords 115 Encryption 115 Password Strength 116 Assess Your Vulnerability 117 From the Library of Lee Bogdanoff Download at WoweBook.Com ptg CONTENTS viii Patching the Application to Authenticate Users 117 Add User Database Table and Double-Check Database Security 118 Create Authentication API 119 Wrapping It Up 120 Chapter 8 Encryption 121 What Is Encryption? 121 Choosing an Encryption Type 123 Algorithm Strength 123 Speed Versus Security 124 Use of the Data 124 Password Security 125 Patching the Application to Encrypt Passwords 125 Modifying the User Table 126 Create the Encryption and Salting Functions 126 Modify the Password Validation System 127 Wrapping It Up 128 Chapter 9 Session Security 129 What Is a Session Variable? 129 Major Types of Session Attacks 129 Session Fixation 130 Session Hijacking 131 Session Poisoning 133 Patching the Application to Secure the Session 133 Wrapping It Up 136 Chapter 10 Cross-Site Scripting 137 What Is XSS? 137 Reflected XSS 137 Stored XSS 138 Patching the Application to Prevent XSS Attacks 138 Wrapping It Up 139 Part V Locking Up for the Night 141 Chapter 11 Securing Apache and MySQL 143 Programming Languages, Web Servers, and Operating Systems Are Inherently Insecure 143 Securing a UNIX, Linux, or Mac OS X Environment 144 Update the Operating System 145 Securing Apache 147 Upgrade or Install the Latest Stable Version of Apache 147 Give Apache Its Own User and Group 149 From the Library of Lee Bogdanoff Download at WoweBook.Com ptg CONTENTS ix Hide the Version Number and Other Sensitive Information 151 Restrict Apache to Its Own Directory Structure 152 Disable Any Options You Don’t Explicitly Need 153 Install and Enable ModSecurity 154 Securing MySQL 159 Upgrade or Install the Latest Version 159 Disable Remote Access 163 Change Admin Username and Password 163 Delete Default Database Users and Create New Accounts for Each Application 164 Delete the Sample Databases 165 Wrapping It Up 166 Chapter 12 Securing IIS and SQL Server 167 Securing a Windows Server Environment 167 Update the Operating System 168 Securing IIS 177 Reduce the Server’s Footprint 177 Secure the Web Root 179 Securing SQL Server 187 Install or Upgrade to the Latest Version 187 Secure Microsoft SQL Server 200 Wrapping It Up 205 Chapter 13 Securing PHP on the Server 207 Using the Latest Version of PHP 207 Examining the Zend Framework and Zend Optimizer 208 Finding the Latest Stable Version of PHP 212 Using the Suhosin Patch and Extension 213 Using the Security Features Built into PHP and Apache 213 safe_mode 213 SuEXEC 214 Using ModSecurity 215 Hardening php.ini 216 Wrapping It Up 218 Chapter 14 Introduction to Automated Testing 219 Why Are We Talking About Testing in a Security Book? 219 Testing Framework 220 Types of Tests 222 Unit Tests 222 System Tests 223 Choosing Solid Test Data 223 Wrapping It Up 224 From the Library of Lee Bogdanoff Download at WoweBook.Com [...]... application, don’t connect it to the Web If you want to truly secure PHP code, write a wrapper that sits between PHP and everything else, keeping it safe The Hardened -PHP Group is working on this type of wrapper, but we’ll get to that in Chapter 13, Securing PHP on the Server.” All we are trying to do—all we can do—is make it harder for malicious users to attack our applications We can never create truly... the business of securing Web applications: the idea that as long as you have strong network security, you don’t have to worry about securing each and every application that runs on the server After all, if nobody can hack into the network, then nobody can get to the applications, right? Wrong! This is especially true of a Web server, which has to be open to the public in order to serve Web sites On a... first time you’ve really thought about securing your applications Our goal in writing this book is to give you the tools you need to make your applications more secure By their nature, Web applications are inherently insecure You are allowing unknown users to have direct access to your server Even if you have a firewall, you have to poke a hole in it to allow your Web application to be accessible to the... through holes created by insecure applications • Application programmers can close the holes in their applications without dropping everything to earn a degree in computer science System administrators do have a role in securing the Web server, and if you happen to wear both the system administration and application programming hats, be sure to read Chapter 13, Securing PHP on the Server.” The rest of... insecure applications in PHP, a language that is inherently insecure It doesn’t have strongly typed variables, it utilizes global variables, and users can make function calls through the browser Many programmers 3 From the Library of Lee Bogdanoff Download at WoweBook.Com CHAPTER 1 SECURITY IS A SERVER ISSUE AND OTHER MYTHS consider these to be features of PHP, not liabilities, but we’re examining Web applications. .. books on Web application programming, including PHP & MySQL Web Development All-in-One Desk Reference for Dummies (Wiley Publishing, 2008) They have seen firsthand the damage that can be done to shared hosting through a single insecure application xv From the Library of Lee Bogdanoff Download at WoweBook.Com This page intentionally left blank From the Library of Lee Bogdanoff Download at WoweBook.Com... insecure applications and how you can be sure that yours isn’t one of them HACKERS GAIN CONTROL THROUGH INSECURE APPLICATIONS Some hackers do attack servers and networks directly, but most search for insecure applications running on those servers and use them as a gateway to the server and network Why do they focus on applications, rather than the true targets—servers and networks? They target applications. .. literally would not exist without you xiii From the Library of Lee Bogdanoff Download at WoweBook.Com This page intentionally left blank From the Library of Lee Bogdanoff Download at WoweBook.Com About the Authors Tricia Ballad spent several years as a Web applications developer on the LAMP (Linux, Apache, MySQL, PHP/ Perl) platform before becoming a full-time writer and technical editor She writes online... Download at WoweBook.Com PART I WEB DEVELOPMENT IS A BLOOD SPORT— DON'T WANDER ONTO THE FIELD WITHOUT A HELMET 1 From the Library of Lee Bogdanoff Download at WoweBook.Com This page intentionally left blank From the Library of Lee Bogdanoff Download at WoweBook.Com Security Is a Server Issue and Other Myths Welcome! The purpose of this chapter is to tackle some of the most common PHP security myths head-on... Download at WoweBook.Com CONTENTS Appendix Additional Resources 285 PEAR Books Web Sites Tools Integrated Development Environments (IDE) and Frameworks Exploit Testing Tools Automated Testing Tools 285 286 287 288 288 288 288 Glossary 289 Index 293 xi From the Library of Lee Bogdanoff Download at WoweBook.Com This page intentionally left blank From the Library of Lee Bogdanoff Download at WoweBook.Com . Bogdanoff ptg Securing PHP Web Applications From the Library of Lee Bogdanoff Download at WoweBook.Com ptg This page intentionally left blank From the Library of Lee Bogdanoff Download at WoweBook.Com ptg Securing. Sales international@pearsoned.com Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Ballad, Tricia. Securing PHP web applications / Tricia Ballad, William Ballad. p 166 Chapter 12 Securing IIS and SQL Server 167 Securing a Windows Server Environment 167 Update the Operating System 168 Securing IIS 177 Reduce the Server’s Footprint 177 Secure the Web Root 179 Securing