Secure Development for Mobile Apps: How to Design and Code Secure Mobile Applications with PHP and JavaScript, 1st Edition (Paperback) book cover

Secure Development for Mobile Apps

How to Design and Code Secure Mobile Applications with PHP and JavaScript, 1st Edition

By J. D. Glaser

Auerbach Publications

472 pages | 6 B/W Illus.

Purchasing Options:$ = USD
Paperback: 9781482209037
pub: 2014-10-13
$62.95
x
Hardback: 9781138428027
pub: 2017-07-27
$195.00
x
eBook (VitalSource) : 9780429069543
pub: 2014-10-13
from $31.48


FREE Standard Shipping!

Description

The world is becoming increasingly mobile. Smartphones and tablets have become more powerful and popular, with many of these devices now containing confidential business, financial, and personal information. This has led to a greater focus on mobile software security. Establishing mobile software security should be of primary concern to every mobile application developer. This book explains how you can create mobile social applications that incorporate security throughout the development process.

Although there are many books that address security issues, most do not explain how to incorporate security into the building process. Secure Development for Mobile Apps does exactly that. Its step-by-step guidance shows you how to integrate security measures into social apps running on mobile platforms. You’ll learn how to design and code apps with security as part of the process and not an afterthought. The author outlines best practices to help you build better, more secure software.

This book provides a comprehensive guide to techniques for secure development practices. It covers PHP security practices and tools, project layout templates, PHP and PDO, PHP encryption, and guidelines for secure session management, form validation, and file uploading. The book also demonstrates how to develop secure mobile apps using the APIs for Google Maps, YouTube, jQuery Mobile, Twitter, and Facebook. While this is not a beginner’s guide to programming, you should have no problem following along if you’ve spent some time developing with PHP and MySQL.

Table of Contents

Foreword

Introduction

Industry Analysis

Preface

Acknowledgments

Biography

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

Web Application Attack Surface

Attack Vectors

Common Threats

SQL Injection

Cross-Site Scripting

Cross-Site Request Forgery

Session Hijacking

Defending Input and Output Streams: First Glance

GET Requests

POST Requests

COOKIE Data

Session Fixation

Cross-Site Request Forgery

Theory of Input Filtering and Output Escaping

Input Validation

Input Filtering

Output Escaping

You Must Know Where Your Data Is Displayed

PHP Security Anti-Patterns

Anti-Pattern #1

Not Matching Data Character Set to Filter Character Set

Not Designing with Content Security Policy Anti-Pattern

One Size Fits All Anti-Pattern

Misinformation Anti-Patterns

The Mantra Anti-Pattern

Critical Data Type Understanding and Analysis

Single Data Type Anti-Pattern

All Incoming HTTP Data Are Strings

Validation by Type Process

Input Same as Output Anti-Pattern

The Assumed Clean Anti-Pattern

Improper mysql_real_escape_string() Usage

Filtering versus Escaping versus Encoding

Only One Output Context Anti-Pattern

Lack of Planning Anti-Patterns

Lack of Consistency Anti-Patterns

Lack of Testing Anti-Patterns

Parameter Omission Anti-Pattern

Design Practices Anti-Patterns

No Clear Separation of HTML and PHP Code Anti-Pattern

Too Many Database Function Calls

Misleading Filtering Anti-Pattern

Too Many Quotes Anti-Pattern

Raw Request Variables as Application Variables

Common Direct URL Input Anti-Pattern

Poor Error Management Practices

Poor Cryptography Practices

Poor Cookie Expiration

Poor Session Management

Overcoming Anti-Patterns: Patterns, Testing, Automation

PHP Essential Security

A Consistent UTF-8 Character Set

UTF-8 in the Database

UTF-8 in the PHP Application

UTF-8 in the Client Browser

Clean Secure Data

Input Validation: Account for Size and Type

Escape Output: Account for Context

Database Access Pattern

Application Secrets Location Pattern

Error Processing Pattern

Error Logging Process Pattern

Authentication Pattern

Authorization Pattern

White Listing Acceptable Input

PHP Security Design Best Practices Summary

Architect Application Character Set

Architect HTTP Request Patterns

Architect HTTP Cookie Usage

Architect Input Validation

Architect Output Escaping

Architect Session Management

Protect Secret Files/Protect Included Files

Protect User Passwords

Protecting User Session Data

Protect against CSRF Attacks

Protect against SQL Injection Attacks

Protect against XSS Attacks

Protect against File System Attacks

Proper Error Handling

OWASP Recommendations for PHP

The Checklist

Additional PHP Security Checklist

Disable Dangerous PHP Functions

PHP Security Tools Overview

Object Language Support

Abstract Classes, Interfaces, Façades, Templates, Strategy, Factories, and Visitors

Variable Variables: Power DRY

Native Function Support

Encoding Functions

DRY Enforcement Functions

Type Enforcement Functions

Filter Functions

Mobile Functions

Cryptography and Hashing Functions

Modern Crypto

Modern Hashing

Modern Salting and Randomization

HTML Templating Support

How to Inline Heredoc Functions

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

The Reason for PDO Prepared Statements

Deprecated Security Functions

Modern Crypto versus Old Crypto

UTF-8 for PHP and MySQL

Why UTF-8

UTF-8 Advantages

UTF-8 Disadvantages

How UTF-8 Affects Security

Complete PHP UTF-8 Setup

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

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

Separation of Concerns

What Is Separation of 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 Class

Summary

PHP and PDO

PDO UTF-8 Connection

MySQL UTF-8 Database and Table Creation Support

PDO Prepared Statements

Prepared Statement Examples

Selecting Data and Placing into HTML and URL Context

PDO SELECT Queries and Class Objects

Quoting Values and Database Type Conversion

PDO Manual Quoting Example

PDO and WHERE IN Statements

White Listing and PDO Quoting of Column Names

Summary

Template Strategy Patterns

Template Pattern Enforces Process

Account Registration Template

Account Registration Template—Activation

Strategy Pattern for Output Escaping

Escaping Strategy Class

Improved Escaping Strategy Class

The Input Cleaner Class

Testing the Cleaner Class

Examples of Cleaner::getKey() Validation Usage

Modern PHP Encryption

Using MCrypt for Two-Way Encryption

Encrypting Hashed Passwords with Blowfish

Professional Exception and Error Handling

Configuring PHP Error Environment

Secure php.ini and Error Log Files

Error Options Overview

Production Error Configuration for php.ini

Development Error Configuration for php.ini

PHP Error Level Constants

Exception Handling

Introduction to Exceptions

Trapping All Errors and Exceptions

Converting Errors to Exceptions

ErrorManager Class

Handle Fatal Errors with register_shutdown_function()

Secure Session Management

The SSL Landing Page

Secure Session Overview

Secure Session Management Checklist

Session Checklist Details

Setting Configuration and Setup

Detecting Session Tampering

Force Page Request over SSL

SSL Redirect

Protocol Relative Links

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 SecureSessionFile Details

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

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

jQuery Password Strength Meter

JavaScript and jQuery Escaping and Filtering

Replace innerHTML with innerText

Embedded HTML HyperLinks—Problems with innerHTML

Insecure JavaScript Functions

Preventing Double Form Submission

Post-Redirect-Get Pattern for Form Processing

The PRG Pattern

The PRG Directive

Tracking Form Tokens to Prevent Double Submission

Controlling Form Page Caching and Page Expiration

Main Cache-Control Settings

Microsoft Internet Explorer Extension

Timestamping AJAX GET Requests

Constructing Secure GET Request URLs

Secure File Uploading

Basic Principles of Secure File Uploading

Authentication of File Uploads

Create White List of Allowable Types

File Extensions and Types Are Meaningless

Create a System-Generated File Name

Always Store Uploaded Files Outside Web Root

Enforce File Size Limits

Control File Permissions

Limit Number of Uploaded Files

Optional: Use CAPTCHA

Optional: Use Virus Scan

Secure File Uploading to Database

SQL Table

HTML Form

Retrieving Uploaded Images

Secure JSON Requests

Building Secure JSON Responses

Correct and Incorrect JSON

Proper JSON Construction Depends on Array Construction

Safe Array Construction with PDO Records

Send and Receive JSON in PHP

Send JSON from PHP

Receive JSON in PHP

Parsing JSON Securely with JavaScript/jQuery

jQuery JSON Calls

Post and Parse JSON Response Example

Google Maps, YouTube, and jQuery Mobile

Code Setup

About the Code

Placing Videos inside Google Map InfoWindows

Creating InfoWindow Markers

HTML and jQuery Mobile Layout

Separation of Concerns

HTML Fragments Description

YouTube Elements Description

Javascript File: gmap.js

Map Functions

InfoWindow Marker with Playable Video

Map Marker Database Table

VideoMap URL Table

Data Repository Class: GMapData

Processing Markers

Generating Markers

Inserting and Updating Markers

Preparing Safe JSON Data

Twitter Authentication and SSL cURL

Twitter v1.1 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 v1.1 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

Secure AJAX 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

Common Facebook Canvas Vulnerability Points

Saving Facebook RealTime Updates via PDO

Reflecting JSON Coordinates

Reflecting Messages

Reflecting URLs

JavaScript and JQuery Filters

Method 1

Method 2

Method 3

JSONP Precaution

Appendix

About the Author

J.D. Glaser is a software developer who loves building things. Circumstance led to a career in developing Windows security software and speaking all over the world on Windows forensic matters. He has trained government agencies in forensic issues and the U.S. Department of Justice has used his tools to capture and convict cybercriminals. He now specializes in building large social games in PHP and keeping players secure in cyber space.

Subject Categories

BISAC Subject Codes/Headings:
COM012040
COMPUTERS / Programming / Games
COM051230
COMPUTERS / Software Development & Engineering / General
COM060000
COMPUTERS / Internet / General