Pro PHP Security - gbv.de · ProPHPSecurity FromApplicationSecurity Principlesto the Implementation...

12
Pro PHP Security From Application Security Principles to the Implementation of XSS Defenses Second Edition Chris Snyder Thomas Myer Michael Southwell Apress*

Transcript of Pro PHP Security - gbv.de · ProPHPSecurity FromApplicationSecurity Principlesto the Implementation...

Pro PHP SecurityFrom Application Security Principles to the

Implementation of XSS Defenses

Second Edition

Chris SnyderThomas MyerMichael Southwell

Apress*

Contents

Contents at a Glance iv

iiAbout the Authors xvi

Acknowledgments xvii

% Preface xwiii

Part 1: The Importance of Security 1

'

Chapter 1: Why Is Secure Programming a Concern? 3

What Is Computer Security? 3

Why Absolute Computer Security Is Impossible 4

What Kinds of Attacks Are Web Applications Vulnerable To? 4

When Users Provide Information 4

When Information Is Provided to Users 8

In Other Cases 8

Five Good Habits of a Security-Conscious Developer 9

Nothing Is 100% Secure 10

Never Trust User Input 10

Defense in Depth Is the Only Defense 11

Simpler Is Easier to Secure 11

Peer Review Is Critical to Security 12

Summary 12

V

CONTENTS

Part 2: Practicing Secure PHP Programming 13

Chapter 2: Validating and Sanitizing User Input 15

What to Look For 15

Input Containing Metacharacters 16

Input of the Wrong Type 16

Too Much Input 17

Abuse of Hidden Interfaces 17

Input Bearing Unexpected Commands 18

Strategies for Validating User Input in PHP 18

Secure PHP's Inputs by Turning Off Global Variables 18

Declare Variables 20

Allow Only Expected Input 21

Check Input Type, Length, and Format 22

Sanitize Values Passed to Other Systems 25

Testing Input Validation 31

Summary 31

Chapter 3: Preventing SQL Injection 33

What SQL Injection Is 33

How SQL Injection Works 33

PHP and MySQL Injection 35

Kinds of User Input 35

Kinds of Injection Attacks 36

Multiple-Query Injection 36

Preventing SQL Injection 37

Demarcate Every Value in Your Queries 37

Check the Types of Users' Submitted Values 38

Escape Every Questionable Character in Your Queries 39

Abstract to Improve Security 39

Full Abstraction 42

vi

CONTENTS

Test Your Protection Against Injection 42

Summary 43

Chapter 4: Preventing Cross-Site Scripting 45

How XSS Works 45

Scripting 45

Categorizing XSS Attacks 46

A Sampler of XSS Techniques 47

HTML and CSS Markup Attacks 48

JavaScript Attacks 49

Forged Action URIs 49

Forged Image Source URIs 50

Extra Form Baggage 50

Other Attacks 51

Preventing XSS ..51

SSL Does Not Prevent XSS 51

Strategies 51

Test for Protection Against XSS Abuse 57

Summary 57

Chapter 5: Preventing Remote Execution 59

How Remote Execution Works 59

The Dangers of Remote Execution 60

Injection of PHP Code 60

Embedding of PHP Code in Uploaded Files 61

Injection of Shell Commands or Scripts 63

Strategies for Preventing Remote Execution 65

Limit Allowable Filename Extensions for Uploads 65

Store Uploads Outside the Web Document Root 66

Allow Only Trusted, Human Users to Import Code 66

Sanitize Untrusted Input to evalQ 66

vii

CONTENTS

Do Not Include PHP Scripts from Remote Servers 71

Properly Escape All Shell Commands 71

Beware of preg_replace() Patterns with the e Modifier 75

Testing for Remote Execution Vulnerabilities 78

Summary 78

fiCliapter 6: Enforcing Security for Temporary Files 81

The Functions of Temporary Files 81

Characteristics of Temporary Files 82

Locations 82

Permanence 82

Risks 82

Preventing Temporary File Abuse 84

Make Locations Difficult 84

Make Permissions Restrictive 87

Write to Known Files Only 88

Read from Known Files Only 88

Checking Uploaded Files 89

Test Your Protection Against Hijacking 90

Summary 91

mChapter 7: Preventing Session Hijacking 93

How Persistent Sessions Work 93

PHP Sessions 93

Abuse of Sessions 96

Session Hijacking 97

Fixation 99

Preventing Session Abuse 100

Use Secure Sockets Layer 100

Use Cookies Instead of $_6£TVariables 100

Use Session Timeouts 101

viii

mCONTENTS

Regenerate IDs for Users with Changed Status 101

Take Advantage of Code Abstraction 102

Ignore Ineffective Solutions 102

Test for Protection Against Session Abuse 104

Summary 104

Chapter 8: Securing REST Services 105

What Is REST? 105

What Is JSON? 106

REST Security 106

Restricting Access to Resources and Formats 107

Authenticating/Authorizing RESTful Requests 108

Enforcing Quotas and Rate Limits 108

Using SSL to Encrypt Communications 109

A Basic REST Server in PHP 109

Summary 113

Part 3: Practicing Secure Operations 115

IChapter 9: Using CAPTCHAs 117

Background 117

Kinds of Captchas 118

Text Image Captchas 118

Audio Captchas 120

Cognitive Captchas 121

Creating an Effective Captcha Test Using PHP 122

Let an External Web Service Manage the Captcha for You 122

Creating Your Own Captcha Test 124

Attacks on Captcha Challenges 129

Potential Problems in Using Captchas 130

Hijacking Captchas Is Relatively Easy 130

The More Captchas Are Used, the Better Al Attack Scripts Get at Reading Them 130

CONTENTS

Generating Captchas Requires Time and Memory 130

Captchas That Are Too Complex May Be Unreadable by Humans 130

Even Relatively Straightforward Captchas May Fall Prey to Unforeseeable User Difficulties 131

Summary 131

Chapter 10: User Authentication, Authorization, and Logging 133

Identity Verification 133

Who Are the Abusers? 134

Spammers 134

Scammers 134

Griefersand Trolls 135

Using a Working Email Address for Identity Verification 135

Verifying Receipt with a Token 136

When a Working Mailbox Isn't Enough 139

Requiring an Online Payment 139

Using Short Message Service 139

Requiring a Verified Digital Signature 140

Access Control for Web Applications 140

Application Access Control Strategies 141

Roles-Based Access Control 144

Authorization Based on Roles 146

Making RBAC Work 152

A Review of System-level Accountability 155

Basic Application Logging 156

Summary 157

Chapter 11: Preventing Data Loss 159

Preventing Accidental Corruption 160

Adding a Locked Flag to a Table 161

Adding a Confirmation Dialog Box to an Action 161

Avoiding Record Deletion 164

x

CONTENTS

Adding a Deleted Flag to a Table 164

Creating Less-privileged Database Users 165

Enforcing the Deleted Field in SELECT Queries 165

Providing an Undelete Interface 167

Versioning 167

Table Structure 168

Insert, Then Update 169

Creating a Versioned Database Filestore 170

A Realistic PHP Versioning System 171

Garbage Collection 172

Other Means of Versioning Files 174

Summary 175

Chapter 12: Safe Execution of System and Remote Procedure Calls 177

Dangerous Operations 177

Root-level Commands 178

Making Dangerous Operations Safe 180

Create an API for Root-level Operations 180

Queue Resource-intensive Operations 181

Handling Resource-intensive Operations with a Queue 184

How to Build a Queue 184

Triggering Batch Processing 188

Tracking Queued Tasks 192

Remote Procedure Calls 195

RPC and Web Services 196

Keeping a Web Services Interface Secure 197

Making Subrequests Safely 198

Summary 204

xi

mCONTENTS

Part 4: Creating a Safe Environment 207

II Chapter 13: Securing Unix 209

An Introduction to Unix Permissions 209

Manipulating Permissions 210

Shared Group Directories 212

PHP Tools for Working with File Access Controls 214

Keeping Developers (and Daemons) in Their Home Directories 214

Protecting the System from Itself 215

Resource Limits 215

Disk Quotas 216

PHP's Own Resource Limits 217

PHP Safe Mode 217

How Safe Mode Works 218

Other Safe Mode Features 218

Safe Mode Alternatives 219

Summary 220

Chapter 14: Securing Your Database 221

Protecting Databases 221

General Security Considerations 221

Database Filesystem Permissions 222

Securing Option Files 223

Global Option Files 223

Server-Specific Option Files 223

User-Specific Option Files 223

Securing MySQL Accounts 224

Controlling Database Access with Grant Tables 226

Hardening a Default MySQL Installation 226

Grant Privileges Conservatively 227

Avoid Unsafe Networking 228

REALLY Adding Undo with Regular Backups 228

xii

CONTENTS

Summary 228

Chapter 15: Using Encryption 229

Encryption vs. Hashing 229

Encryption 230

Hashing 231

Algorithm Strength 232

A Note on Password Strength 233

Recommended Encryption Algorithms 233

Symmetric Algorithms 234

Asymmetric Algorithms 236

Email Encryption Techniques 237

Recommended Hash Functions 238

MD5 238

SHA-256, 238

DSA 239

Related Algorithms 239

base64 239

XOR 240

Random Numbers ..240

Blocks, Modes, and Initialization Vectors 241

Streams and Blocks 241

Modes 241

Initialization Vectors 243

US Government Restrictions on Exporting Encryption Algorithms 243

Applied Cryptography 244

Protecting Passwords 244

Protecting Sensitive Data 248

Asymmetric Encryption in PHP: RSA and the OpenSSL Functions 249

Verifying Important or At-risk Data 260

xiii

CONTENTS

Verification Using Digests 260

Verification Using Signatures 265

Summary 266

Chapter 16: Securing Network Connections: SSL and SSH 267

Definitions 267

Secure Sockets Layer 268

Transport Layer Security 268

Certificates 268

The SSL Protocols 273

Connecting to SSL Servers Using PHP 273

PHP's Streams, Wrappers, and Transports 274

The SSL and TLS Transports 274

The HTTPS Wrapper 277

The FTP and FTPS Wrappers 279

Secure IMAP and POP Support Using TLS Transport 282

Working with SSH 282

The Original Secure Shell 283

Using OpenSSH for Secure Shell 284

Using SSH with Your PHP Applications 284

The Value of Secure Connections 294

Should I Use SSL or SSH? 294

Summary 294

Chapter 17: Final Recommendations 295

Security Issues Related to Shared Hosting 295

An Inventory of Effects 296

Minimizing System-Level Problems 298

A Reasonable Standard of Protection for Multiuser Hosts 299

Virtual Machines: A Safer Alternative to Traditional Virtual Hosting 301

Shared Hosts from a System Administrator's Point of View 302

xiv

m CONTENTS

Maintaining Separate Development and Production Environments 303

Why Separate Development and Production Servers? 305

Effective Production Server Security 306

Keeping Software Up to Date 314

Installing Programs 315

Updating Software 320

Summary 326

Index 327

XV