Contents FOREWORD INTRODUCTION INDUSTRY ANALYSIS PREFACE ACKNOWLEDGMENTS BIOGRAPHY XV xvii xix xxiil XXV xxvii PART I CHAPTER 1 INTRODUCTION TO MOBILE SECURITY DEVELOPMENT Understanding Secure Web Development What This Book Is What This Book Is Not Prerequisite Technologies Applying Architecture Tools to Security Creating Consistent Reusable Code from Project to Project Mobile Application Using HTML5, AJAX, and jquery Mobile Mobile App A Social Mashup Client Technologies Client Application Layout Server Application Evolution of Security Measures SQL Injection to XSS to CSRF Battle for Output Context :. New Technologies HTML5 Bad Practices Invite Holes " Security as Add-on ' ' - Lack of Information \ Lack of Consistency A New Mindset for Web Application Security 3 3 3 4 5 5 5 5 6 6 6 6 7 7 8 8 8 8 9 9 10
CHAPTER 2 WEB APPLICATION ATTACK SURFACE 15 Attack Vectors 15 Common Threats 16 SQL Injection 16 Cross-Site Scripting 17 Cross-Site Request Forgery 18 Session Hijacking 18 Defending Input and Output Streams; First Glance 19 GET Requests 19 POST Requests 20 COOKIE Data 21 Session Fixation 21 Cross-Site Request Forgery ^V Theory of Input Filtering and Output Escaping 25 Input Validation ^ ^. - - 26 Input Filtering li 26 Output Escaping f 28 You Must Know Where Your Data Is Displayed 28 CHAPTER 3 P H P SECURITY ANTI-PATTERNS 37 Anti-Pattern #1 37 Not Matching Data Character Set to Filter Character Set 37 Not Designing with Content Security Policy Anti-Pattern 38 One Size Fits All Ann-Pattern 38 Misinformation Anti-Patterns 38 The Mantra Anti-Pattern 39 Critical Data Type Understanding and Analysis 40 Single Data Type Anti-Pattern 40 All Incoming HTTP Data Are Strings 45 Validation by Tvpe Process 47 Input Same as Output Anti-Pattern, =49 The Assumed Clean Anti-Pattern 50 Improper mysql real escape string () Usage, 50 Filtering versus Escaping versus Encoding 51 Only One Output Context Anti-Pattern 52 Lack of Planning Anti-Patterns 52 Lack of Consistency Anti-Patterns 52 Lack of Testing Anti-Patterns 53 Parameter Omission Anti-Pattern S3 Design Practices Anti-Patterns 56 No Clear Separation of HTML and PHP Code Anti-Pattern 56 Too Many Database Function Calls 57 Misleading Filtering Anti-Pattern 58 Too Many Quotes Anti-Pattern 58 Raw Request Variables as Application Variables 59 Common Direct URL Input Anti-Pattern 59 Poor Ernir Management Practices 60 Poor Cryptography Practices 61 Poor Cookie Expiration 62 Poor Session Management ^ 6 Overcoming Anti-Patterns: Patterns, Testing, Automation \3
CHAPTER 4 P H P ESSENTIAL SECURITY 65 A Consistent UTF-8 Character Set 65 UTF-8 in the Database 66 UTF-8 in the PHP AppHcation 66 UTF-8 in the CHent Browser 67 Clean Secure Data : - 67 Input Validation; Account for Size and Tvpe - 67 Escape Output: Account for Context ''. 67 Database Access Pattern - >, 68 Application Secrets Location Pattern 68 Error Processing Pattern 68 Error Logging Process Pattern. ib Authentication Pattern 69 Authorization Pattern 69 White Listing Acceptable Input PHP Security Design Best Practices Summary 70 Architect Application Character Set 70 Architect HTTP Request Patterns 70 Architect HTTP Cookie Usage 71 Architect Input Validation - 71 Architect Output Escaping 71 Architect Session Management 72 Protect Secret Files/Protect Included Files 72 Protect User Passwords 72 Protecting User Session Data ' 72 Protect against CSRF Attacks 73 Protect against SQL Injection Attacks 73 Protect against XSS Attacks : - 73 Protect against File System Attacks \\ 73 Proper Error Handling ' "'" 74 OWASP Recommendations for PHP 74 The CheckUst 74 Additional PHP Security Checklist - 75 Disable Dangerous PHP Functions v 7 5 Abstract Classes, Interfaces, Facades, Templates, Strategy, Factories, and Visitors 77 CHAPTER 5 P H P SECURITY TOOLS OVERVIEW 77 Object Language Support 77 Variable Variables; Power DRY 80 Native Function Support 81 Encoding Functions 81 DRY Enforcement Functions 83 Type Enforcement Functions 84 Filter Functions 85 Mobile Functions 88 Cryptography and Hashing Functions 89 Modern Crypto '\9 Modern Hashing ^ ^ 91 Modern Salting and Randomization, ^. 91 HTML Templating Support ' 92 How to Inline Heredoc Functions 92
Best Practices Tips Use Integer Values as Much as Possible Use Type Enforcement Everywhere You Can Enforce String Sizes and Numeric Ranges Politely Cut Strings before Filtering Keep Strings as Small as Possible for Filters and for SQL Tables Issues to Avoid Hie Reason for PDO Prepared Statements Deprecated Security Functions Modern Crypto versus Old Crypto : CHAPTER 6 U T F - 8 FOR P H P AND M Y S Q L Why UTF-8 :' UTF-8 Advantages UTF-8 Disadvantages How UTF-8 Affects Security li Complete PHP UTF-8 Setup i UTF-8 MySQL Database and Table Creation UTF-8 PDO Client Connection Manual UTF-8 PDO/MySQL Connection How To PHP UTF-8 Initialization and Installation UTF-8 Browser Setup Header Setup Meta-Tag Setup Form Setup PHP UTF-8 Multi-Byte Functions UTF-8 Input Validation Functions UTF-8 String Functions UTF-8 Output Functions UTF-8 Mail UTF-8 Configuration PHPUnit Testing Test PHP Internal Encoding Test PHP Output Encoding PHPUnit Test Class for Asserting UTF-8 Configuration 94 94 95 95 95 96 96 98 99 100 101 101 161 101 102 102 102 104 104 105 105 106 106 106 107 107 108 109 110 111 111 111 112 CHAPTER 7 PROJECT LAYOUT TEMPLATE Every App Has Some Basic Similarities Project Layout Should Be Handled Consistently Select Query Wrapper Separation of HTML Static Resources The Completely Commented Files PHP PDO/UTF-8 Security Checklist 115 115 115 118 119 120 120 { CHAPTER 8 SEPARATION OF CONCERNS b What Is Separation ot Concerns? Keep HTML as HTML Keep PHP Out of HTML Keep JavaScript Out of HTML Content Security Policy Keep CSS Out of JS Use of IDs and Classes in HTML Summary 121 121 122 122 124 126 126 127 128
CHAPTER 9 P H P AND P D O 129 PDO UTF-8 Connection 131 MySQL UTF-8 Database and Table Creation Support 132 PDO Prepared Statements 133 Prepared Statement Examples 133 Selecting Data and Placing into HTML and URL Context 135 PDO SELECT Queries and Class Objects 137 Quoting Values and Database Type Conversion 137 PDO Manual Quoting Example. 138 PDO and WHERE IN Statements 139 White Listing and PDO Quoting of Column Names 140 Summary ^ 141 CHAPTER 10 TEMPLATE STRATEGY PATTERNS 143 Template Pattern Enforces Process ^---^""'T^ Account Registration Template ^ 143 Account Registration Template Activation 145 Strategy Pattern for Output Escaping 147 Escaping Strategy Class 147 Improved Escaping Strategy Class 149 The Input Cleaner Class 152 Testing the Cleaner Class 156 Examples of Cleaner: :getkey() Validation Usage 158 CHAPTER 11 MODERN P H P ENCRYPTION 159 Using MCrypt for Two-Way Encryption 159 Encrypting Hashed Passwords with Blowfish 162 CHAPTER 12 PROFESSIONAL EXCEPTION AND ERROR HANDLING 165 Configuring PHP Error Environment 166 Secure php.ini and Error Log Files 166 Error Options Overview 167 Production Error Configuration for php.ini 168 Development Error Configuration for php.ini 168 PHP Error Level Constants 168 Exception Handling 169 Introduction to Exceptions 169 Trapping All Errors and Exceptions 174 Converting Errors to Exceptions 174 ErrorManager Class 176 Handle Fatal Errors with register_shutdown_f unction () 177 PART II SECURE SESSION MANAGEMENT 181 The SSL Landing Page 181 Secure Session Overview 182 Secure Session Management Checklist 182 Session Checklist Details \ 183 Setting Configuration and Setup 189 Detecting Session Tampering 191 Force Page Request over SSL 192 SSL Redirect 192 Protocol Relative Links 193
CHAPTER 14 SECURE SESSION STORAGE PHP Default Session Storage Overview -' Session Storage Life Cycle Session Locking AJAX and Session Locking Session Management Configuration Configure Security before Session_Start () Is Called Properly Destroy Session Encrypted Session Storage Encrypted Session Storage via MySQL Creating a Custom Session Handler in MySQL Encrypted Session Storage via File System Class SccureSessionFilc Details CHAPTER 15 SECURE FORMS AND ACCOUNT REGISTRATION Secure User Registration and Login Process Overview Unlimited Password Length, Unlimited Password Characters Secure Form Landing Pages Are over SSL Secure Form Nonce -Prevent CSRF Class NonceTracker Class NonceTracker Listing Class NonceTracker Detail Form Input Validation Overview Registration Form Registration Form Details Double Encryption of User Passwords Account Management Class AccountManager Details and Authorization Checks Email Verification and Activation System Future Proof Encryption Strength with Blowfish Rounds Secure Password Request Link Reauthorize on Privilege Elevation Session Management Class SessionManagement Details Secure Logout Details via SessionManager Privilege Elevation Protection System Secure Login Secure Login Form Secure Login Form Details Protect Pages via Authentication Check Secure Logout Page Secure Logout Page Details A Secure RememberMe Feature Closing Points CHAPTER 16 SECURE CLIENT SERVER FORM VALIDATION PHP UTF-8 Input Validation Server UTF-8 Validation Validating UTF-8 Names and Emails via RegEx PREG for PHP = PREG for JavaScript Server Side Regular Expressions JavaScript Validation via Regular Expressions jquery Validation via Regular Expressions 195 196 196 197 197 197 198 201 202 202 202 224 229 239^ 239 240 241 241 242 242 244 247 248 252 254 257 261 262 269 271.272 273 276 278 279 281 281 283 285 286 287 287 291 293 293 293 294 297 297 302 303
jquery Password Strength Meter 306 JavaScript and jquery Escaping and Filtering 308 Replace innerhtml with innertext 309 Embedded HTML HyperLinks Problems with innerhtml 310 Insecure JavaScript Functions 312 Preventing Double Form Submission.. - 313 Post-Redirect-Get Pattern for Form Processing - 313 The PRC Pattern 314 ThePRG Directive 315 Tracking Form Tokens to Prevent Double Submission 317 Controlling Form Page Caching and Page Expiration,..' 319 Main Cache-Control Settings 320 Microsoft Internet Explorer Extension ' 321 Timestamping AJAX GET Requests. ^ 321 Constructing Secure GET Request URLs 321 CHAPTER 17 SECURE FILE UPLOADING ^' 323 Basic Principles of Secure File Uploading 323 Authentication of File Uploads 324 Create White List of Allowable Types 324 File Extensions and Types Are Meaningless 324 Create a System-Generated File Name 324 Always Store Uploaded Files Outside Web Root 324 Enforce File Size Limits 324 Control File Permissions 325 Limit Number of Uploaded Files 325 Optional: Use CAPTCHA 325 Optional: Use Virus Scan 325 Secure File Uploading to Database 325 SQL Table.. ^ 326 HTML Form,.. 326 Retrieving Uploaded Images 330 CHAPTER 18 SECURE J S O N REQUESTS ^. ' 333 Building Secure JSON Responses - ^' ^"^ 333 Correct and Incorrect JSON 333 Proper JSON Construction Depends on Array Construction 334 Safe Array Construction with PDO Records 336 Send and Receive JSON in PHP 337 SendJSON from PHP 337 Receive JSON in PHP 340 Parsing JSON Securely with JavaScript/jQuery ;.. - ' 34j jquery JSON Calls ' '. 342 Post and Parse JSON Response Example 342 PART III CHAPTER 19 GOOGLE MAPS, YOUTUBE, AND JQUERY MOBILE 347 Code Setup. 347 About the Code 348 Placing Videos inside Google Map InfoWindows 348 Creating InfoWindow Markers 349 HTML and jquery Mobile Layout 349
Separation of Concerns HTM L Fragments Description. L YouTube Elements Description Javascript File: gmap.js Map Functions. InfoWindow Marker vv'ith Playable Video j.. Map Marker Database Table VideoMap URL Table. v Data Repository Class: GMapData ', Processing Markers Generating Markers Inserting and Updating Markers Preparing Safe JSON Data CHAPTER 2 0 TWITTER AUTHENTICATION AND SSL curl Twitter vl.l via PHP,^ Step 1: Create a Twitter Application Step 2: Exchange Twitter Credentials for Access Token Step 3: Request Tweets Using Access Token Step 4: Activate Tweet Links TweetFetcher Class Fetching vl.l Tweets via TweetFetcher Getting Twitter oauth Token Setting SSL Verification for curl Retrieve Latest Tweets from Timeline Creating and Filtering Hyperlinks from Plain Text Filtering Bad Tweet Examples Examples of Secure Processing with processtweet () Using TweetFetcher CHAPTER 21 SECURE A J A X SHOPPING CART JQuery Mobile Store Up and Running The Mobile Store Add Items to Cart Remove Items from Cart Making the PayPal Purchase Beginning the PayPal Transaction Securely Posting to PayPal Completing the PayPal Purchase Conclusion CHAPTER 2 2 COMMON FACEBOOK CANVAS VULNERABILITY POINTS Saving Facebook RealTime Updates via PDO Reflecting JSON Coordinates I Reflecting Messages J; Reflecting URLs JavaScript and JQuery Filters Method 1.. - Method 2 Methods JSONP Precaution APPENDIX INDEX v ^ 351 352 353 354 354 359 363 364 364 366 366 368 373 377\ 377 377 378 378 378 378 382 382 383 385 385 387 387 388 393 393 394 393 397 405 407 407 411 413 417 419 419 420 422, 422 425 429