77
Building Secure e-Commerce Applications By Bill Jaeger, Patrick McBride, & David Rhoades Edward Moser, Editor

Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

Building Securee-Commerce Applications

By Bill Jaeger,Patrick McBride,

& David Rhoades

Edward Moser,Editor

Page 2: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

Copyright Notice

Copyright © 2000, METASeS™

All rights reserved.

No part of this publication may be reproduced or transmitted in any form or by any means,electronic or mechanical, including photocopy, recording, or any information storage and retrievalsystem, without expressed permission in writing from META Secur e-COM Solutions (METASeS)™.

All brand names and product names mentioned in this book are trademarks or registeredtrademarks of their respective companies.

METASeS8601 Dunwoody Place, Suite 700, Atlanta GA 30350678-250-1250 fax: 678-250-1251www.metases.com

Printed in the United States of America.

Warning and DisclaimerNo part of this publication shall be reproduced, stored in a retrieval system, or transmitted by anymeans, electronic, mechanical, photocopying, recording, or otherwise, without written permissionfrom METASeS™. No patent liability is assumed with respect to the use of the information containedherein. Although every precaution has been taken in the preparation of this publication, METASeS(publisher and author) assumes no responsibility for errors or omissions. Neither is any liabilityassumed for damages resulting from the use of the information contained herein.

Page 3: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

iii

Copyright Notice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ii

Warning and Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ii

Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .iii

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1Focus and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1Intended Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3

Document Road Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3The Challenge of e-Commerce Application Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5Anatomy of an Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6

A Complacent Prelude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6Vulnerabilities Exposed by the e-Hack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6Sequence of the e-Hack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7

Post Mortem, and Prelude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8

Logon and Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9Types of Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9

Digital Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10Form-Based Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11Basic Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14

Authentication Threats and Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16Brute-Force Access Attempts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16Brute-Force Lockouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16User Name Harvesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17Multiple Authentication Disorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17Resource Exhaustion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18

Authentication and Logon Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19

Session Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20Sessions and Session IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20

Hypertext Transfer Protocol (HTTP) and Session IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20Session ID Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21Session Tracking Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22

Table of Contents

Page 4: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Table of Contents

iv

URL Rewriting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22Hidden Form Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24IP Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25

Session Tracking Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25Session Tracking -- Threats and Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26

Session Cloning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26IP Hopping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26Session Tracking Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27

Logout Threats and Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28Cached Logout Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28Physical Access by Unauthorized Individuals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28Cached Data Remains After Logout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29Session Logout Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

Session Issues Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30

Transaction-Level Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31Transaction-Level Issues -- Threats and Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32

Unexpected User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32Client-Side Filtering -- Active Content and HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33GET vs. POST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34Improper Application Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35Verbose Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35Disclosure of Client Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36Commercial Off the Shelf (COTS) Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38

Transaction-Level Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39

Server-Side Coding Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40Secure Coding Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42

Principles of Least Privilege and Compartmentalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42Never Trust User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42User Input and Shell Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43Check All System Function Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45Protecting the Application from its Environment, and Vice Versa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45Verbose Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .47Memory Allocation and Buffer Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48External Application Dependencies and Messages of Arbitrary Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49

Server-Side Coding Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52

Database Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53Protecting Your Database Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55

Disable Unnecessary Network Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55Physically Separate Web and Database Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55Address Platform and Vendor Security Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56Correct File and Device Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57

Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58Permissions and Access Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58Restriction of Data Access Through Database Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61Encrypted Communication Between Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62Database Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62Performance Impact of Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63Disaster Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64

Database Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66

Page 5: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Table of Contents

v

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

Appendix –- Useful Links and Reference Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68Web Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69

Index of e-Commerce and Web Application Security Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

Page 6: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

1

This research report from METASeS, Building Secure e-Commerce Applications, provides guidanceto organizations that are constructing Internet-based business systems and are concerned aboutWeb-related security issues. The goal is to raise awareness of the many application-level securityvulnerabilities that exist in new business systems, and to show how to reduce, eliminate, or avoidthem.

Given the rapid transformation of the Internet segment of the computer industry, this report isintended as a living document. It will be updated by METASeS over time to expand upon pastsolutions, cover new issues, and provide more specific guidance on various programming modelsand Web/e-Commerce development environments.

Focus and ScopeThis report is primarily focused on e-Commerce applications. It specifically emphasizes systemsthat involve some sort of transaction or session with an end user.

Building Secure e-Commerce Applications applies a rather liberal definition to e-Commerce thatincludes the following:

1. Public Web Presence ("Brochureware" Sites) – Traditional, organizational Web sites forinformation dissemination. Examples include organizational home pages, news and pressreleases, product/service descriptions, employment opportunities, and contact information.Many of these systems started out as purely static HTML systems, but now include more sessionor transactional features to expand the customer experience (the so called "stickiness" of a site).For example, they gather direct input from users, or track user activity for marketing or otherfuture design purposes. Examples include search engines and user feedback mechanisms.

2. Company Intranet Web Site -- Traditional, internal company Web sites that supportinformation sharing among and across various business functions. Examples include HumanResources (benefits selection, employee phone books, etc.), finance (financial submission andreporting, for example), engineering and design (project management, distributed design,etc.), and marketing and sales.

3. Business to Business (B2B) – Systems that enable enterprises to conduct business with eachother by extending the traditional business process and support systems beyond the companyborders. Business to Government (B2G) systems share similar characteristics. Examples ofB2B providers include Ariba, CommerceOne, ANX, General Electric’s Supply Net, and iManage.

Introduction1

Page 7: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

2

4. Business to Consumer (B2C) – Applications that enable customers to transact business overthe Internet with organizations, and vice-versa. Examples include Amazon, Priceline.com, andCDNOW.

5. Consumer to Consumer (C2C) – Applications that allow consumers to conduct transactionsdirectly with one other online. Examples are Web-based auction sites such as eBay, whereconsumers can exchange cars, antiques, and used computers.

The basis of this report is the wide-ranging research, consulting, and training experience ofMETASeS. Its expertise extends to e-Commerce, application-level security assessments, andauditing. Drawing on the extensive METASeS client list, and actual attacks on Web sites that the eliteteam of METASeS consultants has investigated, the report often frames the discussion from theperspective of the attacker. It discusses not only the various components of an e-Commerceapplication, but also methods that intruders may employ to practice their nefarious "art."

Page 8: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

3

Intended AudienceThe audience for this report is application development teams responsible for designing, fashioningthe architecture of, and coding e-Commerce systems. Their counterparts among security personnelare also among the intended readers. The document can be used to help set up guidelines fordesign reviews, code reviews, and even security audits. Given the relatively new and rapidlychanging field of application-level security, it may be premature to develop hard and fast standards,that is, strict rules, for audit. However, as this field progresses, audit teams should be able to usethis document and its future, revised versions to set up security standards. At a minimum,development teams will know at some future point what they are being graded against in auditsituations!

Document Road Map

This report is organized into chapters that cover the broad, major portions of an e-Commerceapplication, as follows:

• Chapter 2, Logon and Authentication• Chapter 3, Session Issues• Chapter 4, Transaction-Level Issues• Chapter 5, Server-Side Coding Techniques• Chapter 6, Database Security

Each chapter has a summary checklist of "best practices" for enhancing application security1.

Logon and Authentication, chapter 2, discusses types of authentication and authentication threatsand attacks. The types of authentication concern tokens, digital certificates, form-basedauthentication, and basic authentication. The authentication threats and attacks involve brute-forceaccess attempts, brute-force lockouts, user name harvesting, multiple authentication disorder,concurrency, and resource exhaustion.

Session Issues, chapter 3, defines a Web session, explains what constitutes a strong session ID, andsketches the various session tracking techniques used to pass a session ID between server andclient. Session tracking techniques include URL rewriting, hidden form elements, cookies, and IPaddresses. The chapter also discusses threats and attacks such as session cloning and IP hopping,and logout threats and attacks, namely, cached logout pages, physical access by unauthorizedindividuals, the lingering of cached data after logout, and session inactivity timeouts.

Transaction-Level Issues, chapter 4, covers the different aspects of a transaction, namely, userinput sent to the Web application, the processing of user input by the Web application, and theoutput sent by the Web application as a result of the user’s transaction. Transaction-level threatsand attacks discussed are unexpected user input, client-side filtering, GETs vs. POSTs, improperapplication flow, verbose error messages, disclosure of client data, and concerns relating toCommercial Off the Shelf (COTS) products.

Server-Side Coding Techniques, chapter 5, discusses the Common Gateway Interface (CGI). Itoutlines the principle of least privilege and compartmentalization, trustworthiness of user input,shell evaluation, system function return values, environmental issues, error messages, memoryallocation and buffer overflows, and external application dependencies.

Database Security, chapter 6, outlines the broad areas of database security, such as databaseservers, encryption, the data itself, and disaster recovery.

Figure 1-1 is a diagram of the topics covered by this report. Each chapter contains this diagram,modified to highlight the functions discussed in the particular chapter.

1 The techniques and suggestions outlined under "Best Practices" may not be possible in everysituation. Extenuating circumstances may prevent their implementation. In most cases, viablealternatives are available using other techniques than those discussed.

Page 9: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

4

As reflected in Figure 1-1, this document assumes that the application is built atop a secureinfrastructure, such as the Web server and operating system (OS) configuration and the networksecurity. From a use perspective, and often a code segmentation perspective, e-Commerceapplications typically include logon- and logoff-related code, code to establish, track, and maintainuser sessions and transaction processing, and database code for storage and retrieval ofinformation. Input and output take place between users, the application, and the database.Important functionalities include the Common Gateway Interface (CGI), active server pages (ASPs),and servlets. The report steps through these areas and explores some of their criticalvulnerabilities and solutions.

The report covers specific best practices in developing CGI-based applications are covered. Futureversions of the report will include best practices for specific development techniques andenvironments such as Microsoft's Active Server Pages (ASPs) and Sun's Java v2 Enterprise Edition(J2EE), including Java Server Pages (JSPs), servlets, and Java Beans.

Session Tracking

CGIASP

Servlet

Logic

User I

/O

DB I/O

Log On Log Off

Database

User

Web Application

Network Security

Web Server Configuration

OS Configuration

Figure 1-1: Illustration of e-Commerce Application Functions

Page 10: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

5

The Challenge of e-Commerce Application SecurityIn building secure e-Commerce systems, organizations face a complicated problem that requirescoordination and cooperation from different groups within, and sometimes without, theorganization. Security in general and Web/e-Commerce security in particular is the quintessentialexample of the "weakest link in the chain." A truly secure system requires – in addition to secureapplications, the subject of this paper -- secure network and systems infrastructure, secure businessand operational processes and procedures, and well-educated developers, system administrators,and end users.

While a secure e-Commerce infrastructure is a very important component of overall systemsecurity, this document does not specifically address it. Other METASeS publications can helporganizations tackle that subject. METASeS has an extensive portfolio of technical securitystandards (that explain what to do to harden various network and system elements), andconfiguration guides (that provide step-by-step, procedures on how to harden specific systems, forexample, Solaris 2.6 and Windows NT 4.0 Server.

From a security point of view, the process for designing, building, testing, and deploying new e-Commerce systems is as important as the coding issues and practices discussed in this document.Given the importance of designing security up front into every aspect of the system -- rather thanbolting it on afterwards -- METASeS also offers its research report Secure Systems Development LifeCycle (SDLC). It covers all security-related tasks relating to life cycle development, includingsecurity architecture/design tasks, vulnerability assessments before and after productiondeployment, and performance testing to check the effect on performance of security features suchas logging and encryption, to name a few.

A good analogy for a secure life cycle process is automobile safety. When seatbelts were firstintroduced, they had a limited impact on auto safety. It was not until safety became integrated intoevery aspect of designing and building automobiles that truly significant strides were made indriver and passenger security. Likewise, including Information Security up front in architecture anddesign and carrying it all the way through the testing and delivery of new system infrastructure andapplications will greatly enhance its effectiveness.

While this paper does not address training, education is a very important aspect of security. Even ifa new e-Commerce application has a perfect technical security architecture, your organizationremains highly vulnerable if end users and operations teams -- systems administration, changemanagement, help desk, etc. -- are not adequately versed in how to use security features.

On another facet of security, it is important to mention "appropriateness". Because creating securesystems is a complex and potentially expensive proposition, it is critical to provide a level ofsecurity commensurate with the value of the information stored in or moving through a system.The level of security should also take into account the likely threat to the information. (Threatsrefer to people who would exploit vulnerabilities or holes in the system and adversely impact thesystem or its data.)

If the value and importance of your data is low, your level of security should be relatively less.If, on the other hand, you need to protect a treasure lode of data, your security will have to bemuch greater. The vast topic of classifying and valuing information is covered in otherMETASeS publications, especially in our high-level, policy-related document, Secure InternetPractices. At a minimum, for the purpose of secure Web applications, system architects shouldhave a firm grasp on the business value of data in order to tailor an appropriate securitysolution.

Lastly, application developers should understand their organization’s fundamental security goals.Developers often have a fairly narrow definition of what they should be trying to protect against.Information security is very often erroneously defined as the mere confidentiality of information.But e-Commerce shops need to consider other equally important security goals. The main securitygoals are:

Page 11: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

6

• Confidentiality -- Maintaining the secrecy of information whether it is traversing a network, ormaintained on a workstation or server.

• Integrity -- Ensuring the completeness and validity of information. This goal is particularlyimportant in making sure that Web-site information cannot be maliciously, or eveninadvertently, altered. There have been far too many major incidents involving crackers thatshut down or defaced Web sites, including those of Yahoo, the US Senate, and the New YorkTimes2. (For a good historical record of public sites that have been defaced, seewww.AntiOnline.com).

• Availability -- Ensuring the usability of information and the systems it resides on or isaccessed through. This is also an important security goal given the spate of so-called Denialof Service (DoS) attacks that have taken down many prominent Web sites (for example, CNNand Yahoo).

In addition to these three elements – classically referred to as CIA -- two other goals are critical toaddress in Web or e-Commerce applications. They are:

• Non-repudiation -- Ensuring that parties in a transaction cannot deny or repudiate that thetransaction took place.

• Auditibility -- Tracking user or system activity for future reference or through real-timemonitoring and logging.

Your security solution needs to address these fundamental security goals. While not specificallynoted, the vulnerabilities discussed throughout this document can adversely impact one or more ofthese goals.

2 This document refers to security intruders as "crackers." The more common term, "hackers," moreproperly refers to legitimate intruders authorized to test and probe the security of a system.

Anatomy of an Attack

This report deals with securing Web applications. So this section provides a concrete example to illustrate the kind ofreal-world risks that may threaten your organization. The example sketches how small, seemingly insignificantweaknesses, as well as overconfidence, can combine to compromise a Web server.

A Complacent Prelude

The organization, although under intense outside scrutiny, felt safe and secure. And why not? Its site had thesefeatures:

• It accepted credit card applications over a "safe," Secure Sockets Layer (SSL) encrypted session link.

• Session tracking was done using encrypted URL rewriting to prevent tampering.

• It had no known Web server or OS bugs.

Vulnerabilities Exposed by the e-Hack

However, lurking in the background were vulnerabilities that a malicious intruder could exploit. These included:

• An indexed directory• URL parameters in clear text• An old Common Gateway Interface (CGI) script was functioning and accessible• Weak session IDs • A customer input verification page containing actual applicant data• Old customer data cached by the server for long periods of time

Page 12: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

7

Sequence of the e-Hack

The intruder cracked the application with a stealthy, logical plan of attack. He knew the site accepted credit cardapplications. Anyone could apply, so the attacker started off the stealthy assault by applying for a credit card:

1. The intruder’s scan discovered an indexable directory, which revealed a .TAR file containing a mirror of theentire Web site. Retrieving this .TAR file showed non-parsed HTML templates. This meant that URLparameters such as the session tracking information, normally encrypted before being served to the client,were in clear text. The non-encrypted URL parameters provided the format needed to interact with themain CGI script. But the CGI script only accepted encrypted URL parameters; how to encrypt them theproper way was not yet known.

2. One file in the .TAR3 file was a CGI script that had a similar name as the main CGI script, except that an olddate had been added to the file name. For example, for the main CGI script of CREDITAPP.CGI, the attackersaw a file called CREDITAPP-03-96.CGI. The attacker immediately wondered: ‘Is the old CGI script still onthe Web site? How similar is this old CGI script to the current CGI script used by the site?’ ‘If the currentCGI script cannot be exploited,’ the intruder reasoned, ‘perhaps the old one can be.’

3. A quick request to the Web server showed that this old CGI script was still on the server and accessible by aWeb browser. But wait, there was more: The old CGI script accepted non-encrypted URL parameters! (Atthis point the faint smell of blood wafted into the air.)

4. The session IDs used by the site to track users throughout the credit application process were weak. Theattacker could see this because he was able to access the old CGI script that did not encrypt the session ID.The session IDs were medium-sized numbers that increased in a predictable fashion. It was trivial to requesta smaller number (that is, someone else’s session). (The scent of blood became much stronger.)

5. So what page should the intruder request if he found a valid session ID for another customer? Actually, thesite had a verification page that included all of the applicant’s data, that is, a complete credit card application.This included the applicant’s name, Social Security number, and even credit card numbers if the applicant wastransferring balances from an old card to a new card. The applicant was to review this confirmation pagebefore final submission of the credit card application.

6. Using the old CGI script, the intruder was able to access numerous completed credit card applications frompast applicants. (In the end, there was blood in the water, and plenty of potential sharks ready to feed.)

3 A .TAR file is a UNIX archive, akin to a .ZIP file stored without compression.

Page 13: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Introduction

8

Post Mortem, and PreludeThe application and its vulnerabilities as described above are based on a true story -- except thatthe intruder was in fact a security analyst hired by the credit card company to assess itsapplication’s security. The company used the data gathered on the vulnerabilities to fix them beforea real "shark" came surfing along.

By applying the best practices outlined in this paper, you can address these types of real-lifesecurity issues before deploying your application into the shark-infested waters of the Web.

Building Secure e-Commerce Applications begins at the beginning, by examining security concernsrelating to logon and authentication.

Page 14: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

9

One of the most essential steps in any application is to identify the user and determine his or herlevel of access or privileges.

This chapter discusses the logon and authentication process and its security issues for Webapplications. Topics include types of authentication and authentication threats and attacks.

The act of positively identifying a particular entity, for example, a person or a router, is calledauthentication. Multi-factor authentication combines something you "know," like a password or PIN,and something you "have," like a token, smart card, or certificate. The act of determining an entity’slevel of access or privileges, based on that verified identity, is called authorization. This documentuses the term logon to refer to the process by which a user initially1 authenticates himself to theWeb application.

Types of AuthenticationThis section outlines a few basic ways to perform Web application authentication, along with thestrengths and weaknesses for each approach. The methods discussed are:

Logon and Authentication2CGIASP

Servlet

Logic

User I

/O

DB I/O

Session Tracking

Log On Log Off

Database

User

Web Application

Network Security

Web Server Configuration

OS Configuration

1 As later discussed in the section Session Tracking Techniques in chapter 3, Session Issues, a useractually reauthenticates himself every time he requests a page from or submits a transaction to theWeb application.

Page 15: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

10

• Digital certificates• Form-based authentication• Basic authentication

Tokens, discussed in a subsequent section, are an important way of strengthening these forms ofauthentication.

Digital Certificates

Digital certificates are issued by trusted third parties known as Certification Authorities (CAs),using the industry-standard X.509 format. The CA digitally signs the certificate using its own privatekey, thereby vouching for the holder's identity and protecting the certificate against tampering.

Digital certificates bind information about the certificate owner to the owner’s public key, which isused to encrypt data. Typically, a Web server that handles sensitive data encrypts, or scrambles,the traffic between the user and itself, especially when the data travels across untrusted networks,such as the Internet. In that case, the Web server presents the user with a digital certificate thatserves two purposes:

• Authentication -- The Web server’s identity is proven to the user. This helps prevent usersfrom being redirected or intercepted by a malicious site surreptitiously. (Note that proof of aWeb site’s identity does not necessarily mean that the site is where the user wants to go2.)

• Confidentiality -- The Web server’s public key is embedded within its digital certificate, andfacilitates the encryption of traffic between the server and the user.

In the typical scenario, the Web server presents its digital certificate to users. However, users canalso have digital certificates. When both parties -- server and client -- authenticate to each other,for example, by presenting digital certificates to each other, mutual authentication takes place.

Web sites that require users to have a digital certificate may also require another form ofauthentication, such as a user name and password. Digital certificates can be transparent to theuser, or the browser can require entry of a pass phrase before the browser can use thecorresponding private key. The use of multiple forms of authentication, such as a certificate anduser name/password, is commonly called multi-factor authentication.

Strengths• Certificates are more secure than simple user names and passwords. Possession of the

certificate and corresponding private key are required to impersonate a user. Passwords alonecan be easily discovered through network sniffing, malicious programs, brute force attacks3, orother means.

• Certificates are the most appropriate choice for business to business Web applications, or incases where a higher level of security is required. An example of the latter is legalrequirements for non-repudiation.

Weaknesses• Limited mobility. Users must have ready access to their digital certificates and corresponding

private keys.

2 Web Spoofing: An Internet Con Game discusses this subject. Seehttp://www.cs.princeton.edu/sip/pub/spoofing.html

3 A brute force attack occurs when an attacker repeatedly attempts to guess user credentials such as apassword. A brute force attack is sometimes referred to as a dictionary attack, named for the wordlists that an intruder’s automated script references.

4 Shoulder surfing is that act of "looking over someone’s shoulder" while he enters his password, inhopes of seeing the keystrokes and learning the password. This can be accomplished in person,through a reflective surface, through video surveillance, or other means.

Page 16: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

11

• Certificate private keys can be stored in encrypted format. This is often done on the user’s PC.To use the private key, the user must usually enter a pass phrase to decrypt it. Assuming anattacker gains access to a certificate and its corresponding private key, security is reduced to"something you know" -- the pass phrase -- which an intruder may guess, shoulder-surf4, orattack via brute force.

• End users may resist using certificates due to unfamiliarity with the technology, lack ofinteroperability (for example, certificates issued under Netscape are not accessible underInternet Explorer), or the portability factor (for example, the ability to securely transport anduse the certificate and corresponding private key between home and work.)

• Digital certificates are a promising technology that has been successfully employed. However,it is still a maturing technology. A number of technical, policy, and procedural issues remain,for example, the administration of certificates, and issues involving the revoking ofcertificates.

Best Practices❏ Use digital certificates for business to business Web applications, or where a higher level of

security is required.

❏ A way to counter the weakness of limited mobility is to store a certificate and itscorresponding private key on a card key or a smart card, which can also serve as a photo IDbadge. Since many employees require ID badges, badges are a convenient means oftransporting a certificate and its key.

Form-Based Authentication

In form-based authentication, as the name suggests, the user fills out an HTML form. Thecredentials requested from the user typically include an identifier, such as user name or accountnumber, and an authenticator5, such as password or PIN. These credentials can be tied to UNIX orNT accounts to enforce various logon restrictions such as time of day and lockouts.

StrengthsWhen implemented securely, this method can provide a reasonable compromise between building asecure application and not overly inconveniencing users. It is the most common technique forcurrent Web applications. However, beware that widespread use does not imply that all solutionshave been implemented securely.

Weaknesses• Attackers can employ easy-to-use freeware tools to attack this method of authentication by

brute force.

• Many sites use form-based authentication and never encrypt the session with, for example,SSL. This is often true of small organizations and those with membership access, andespecially true of the many single-person firms that have started conducting business on theWeb. However, larger sites also suffer from this problem, one notable example being eBay’sdefault login mechanism.

• The Web server may accidentally allow the user’s browser to transmit his credentials acrossan untrusted network via a clear-text session rather than over a Secure Sockets Layer (SSL).

• Some Web sites do not employ any form of logout function that would clear the user’s sessionID from their browser, or from the Web server.

5 The authenticator does not have to be a static password, but can be a one-time password (OTP), suchas SecurID™.

Page 17: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

12

Best Practices❏ The Hypertext Transfer Protocol (HTTP) method that sends the credentials from the browser

to the server should be a POST. The GET method embeds user-supplied data into the URL sentback to the server. Although the URL is likely encrypted while in transit from the user to theWeb server, the URL will be recorded in numerous places that are not encrypted such as serverlog files, bookmarks, and browser history files. Therefore, the user’s credentials could beexposed to prying eyes if sent in the URL (that is, the GET method). See the section GET vs.POST in chapter 4, Transaction-Level Issues, for a more detailed discussion of POST and GET.

❏ Web application developers can minimize brute-force attacks through techniques such asaccount lockouts. (See Brute-Force Access Attempts and Brute-Force Lockouts in the sectionAuthentication Threats and Attacks).

❏ Web sites should employ a logout function to clear the user’s session ID from their browsersor from the Web server.

❏ Encrypt sessions with SSL or other means.

Basic Authentication

Basic authentication is built into the Hypertext Transfer Protocol (HTTP). It allows the server tosend the browser a specific HTTP message that causes the browser to request authentication fromthe user. Figure 2-1 shows the dialog box presented to the user by his Web browser.

The user’s credentials, that is, user name and password, are base-64 encoded to comply with theHTTP specifications. Encoded means the characters are transposed from one character set intoanother in a way that an intruder can easily reverse. This encoding allows the use of specialcharacters within the password, such as spaces, that might otherwise interfere with HTTP. Onceencoded, the browser embeds these credentials into an HTTP header that is sent with nearly everyrequest to the Web server.

Do not confuse encoding with encryption. Although the user name and password are encoded andnot encrypted, and thus are essentially being transmitted in the clear, SSL encryption can be usedto mitigate the risk of interception of the credentials while in transit across the network.

Strengths• Basic authentication is built into HTTP; no extra HTML forms are required.

• All browsers and Web servers support basic authentication.

Figure 2-1: Basic Authentication Prompt

Page 18: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

13

Weaknesses• While session IDs should be a short-term secret, HTTP basic authentication involves the

encoding of the user’s user name and password, a long-term secret.

• Numerous freeware tools exist, some with slick Graphical User Interfaces (GUIs), that allow amalicious attacker to brute-force attack HTTP basic authentication. Intruders use tools toguess one password after another from a dictionary file.

• The Web server may accidentally allow the user’s browser to transmit his credentials acrossan untrusted network via a clear-text session rather than over SSL.

• Most Web sites that use HTTP basic authentication do not employ any form of logout functionthat would clear the user’s session ID from the browser. Typically, the user is instructed toshut down his browser to fully remove his credentials from memory.

• Many sites use basic authentication and never encrypt the session with, for example, SSL. Thisis often true of small organizations and those with membership access, and especially true ofone-person firms doing business over the Web.

Best PracticesGenerally, HTTP basic authentication is not recommended for secure Web applications deployed for public use. However, if deployed, take the following steps:

❏ Implement temporary account lockouts to prevent brute-force attacks from gaining access orcausing long-term Denial of Service (DoS) (see Brute Force Access Attempts and Brute ForceLockouts in the section Authentication Threats and Attacks below.)

❏ Ensure that only encrypted access to the application is permitted to prevent the encoded usercredentials from being transmitted in clear text.

❏ In conjunction with basic authentication, employ SSL.

❏ Employ SSL with long key lengths. Some applications use 40-bit key lengths, even when thebrowser may support 128-bit lengths.

❏ Implement a logout process that clears the user credentials from the browser’s memorywithout requiring the user to close his browser (refer to the accompanying discussion, HTTPbasic authentication – How to Clear User Credentials from the Browser).

HTTP Basic Authentication – How to Clear User Credentials fromthe Browser

The browser stores the basic authentication credentials in memory. These are associated with a specific Web siteand realm name -- an arbitrary name set by the Web server.

The realm name is used when defining areas of a Web site, and is useful if partitioning a site into different areas. Therealm name is shown to the user when she is prompted to enter her user name and password.

For example, to restrict access in Apache to just the user Chris for the directory /~chris, you could use a .htaccess file.

The .htaccess file would look something like this:

AuthType BasicAuthName UserAreaAuthUserFile /usr/local/apache/conf/users<Limit GET POST>Require user Chris</Limit>

Page 19: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

14

It should be noted that closing or quitting the Web browser also erases the user’s credentials frommemory. This may offer a simpler option.

Tokens

Tokens describe a class of hardware devices or software applications that a user needs tosuccessfully authenticate to an application or system. Without physical possession of the token, itis theoretically impossible for the user to log in.

The token, combined, with a user ID and password, is an example of multi-factor authentication.Tokens involve the use of something the user knows (the user ID and password), and something theuser has (the token).

Common examples of tokens include SecurID, Digital Pathways, smart cards, the iButton, and theiKey.

Strengths• Only the person in possession of the token can access the application or system through the

standard user login interface.

Later, if you wanted to clear Chris' name and password from the browser, you would need to create two "Logout"links. The first link leads to a page that displays some instructions as well as the second logout link. The instructionstell Chris to click on the second link and enter EXIT as the user name and password when prompted. (Alternatively,this page can simply explain that the browser needs to be shut down completely in order to clear the credentials.)

Now, when the user clicks on this second link it should point to a directory -- (called /LOGOUT) -- that has thefollowing .htaccess file:

AuthType BasicAuthName UserAreaAuthUserFile /usr/local/apache/conf/users<Limit GET POST>Require user EXIT</Limit>

The realm name (UserArea) is the same employed by the user, but the only valid user name is called EXIT. Sincethe user Chris does not match the allowed user name of EXIT, the user is prompted to authenticate before beingserved this new page. The browser only tracks the credentials by site name and realm name. Both of these are thesame as before: UserArea is the realm name in this example. Therefore, this new "sign-on" attempt (for the usernamed EXIT) writes over the old credentials in the browser’s memory. Since only the user called EXIT is permittedto enter this directory (/LOGOUT), this prevents Chris from accidentally entering a valid account name andpassword. The site would continue to prompt the user until she entered the correct user name and password (thatis, EXIT and EXIT).

For this to work, the site requires the creation of a user with the name EXIT and the password EXIT. Theindex.html file for the /LOGOUT directory is the document that will be shown to the user after she enters EXIT inthe basic authentication dialog box. Therefore, the index.html file could contain some sort of "success" message,such as "You have successfully cleared your user name and password from memory – thanks for using basicauthentication."

Unfortunately, this method requires the user to take several steps. If the site enforces a lockout mechanism toprevent brute-force attacks (and it should), this could cause problems if someone accidentally (or intentionally) locksthe EXIT user. Therefore, the lockout mechanism for the EXIT user should not be enforced.

Further, if the user leaves her computer unattended, and forgets to log out, there is no apparent way to remotelyclear the HTTP basic authentication credentials from the browser. Java or JavaScript could be used to automaticallyrequest the logout URL, but cannot enter the required user name and password (that is, EXIT) into the dialog boxto write over the cached credentials.

Page 20: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

15

• Application or system security does not rest entirely upon a user ID and password. Thissignificantly lessens the likelihood of an unauthorized login.

• Some tokens eliminate the need for users to remember or change passwords.

• The use of tokens enhances other forms of Web application authentication. Certificates can bestored on smart cards, making them more mobile. One-time password (OTP) generators,SecurID for example, make form-based authentication less vulnerable to brute-force attacks.

WeaknessesGiven the "stateless" nature of HTTP and the Web, the user needs to re-authenticate with every request to a protected server. In some cases, such as with SecurID, this could be less than user-friendly unless a cached credential such as a session identifier maintains state. Without a cachedcredential, the user is prompted to re-authenticate for each URL requested, including eachindividual embedded graphic.

However, when using session IDs, one should be careful to follow best practices. Otherwise, aweakness in the session ID results in the compromise of the session, despite the use of robust userauthentication such a OTP generator. This is true for other forms of authentication, such as form-based, and not just tokens.

Note that other tokens, such as smart cards containing digital certificates, may not pose the sameuser inconvenience or risk. Each request to a protected server still requires the user to re-authenticate. However, this re-authentication process is transparent to the user.

Best Practices❏ Use tokens together with user IDs and passwords to reduce chances of unauthorized logins.

Page 21: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

16

Authentication Threats and AttacksThis section discusses authentication threats, namely:

• Brute-force access attempts• Brute-force lockouts• User name harvesting• Multiple authentication disorder • Concurrency• Resource exhaustion

Brute-Force Access Attempts

A brute force attack occurs when an attacker repeatedly attempts to guess a user’s credentials suchas a password. An intruder’s motto for such an attempt might be, "If at first you don’t succeed,write an automated script to keep trying."

A brute force attack is sometimes referred to as a dictionary attack. The script attempts to useeach word in a dictionary word list one at a time. Numerous word lists have been compiled, andmany are freely available on the Internet. These include lists for specific genres and themes, suchas Science Fiction, Old Movie Titles, Star Trek, Monty Python, First Names, etc. The idea is that theuser is more likely to use a password relating to a favorite hobby or subject.

Numerous freeware utilities, some with GUIs, are readily available for performing brute-force attackson many protocols, including: File Transfer Protocol (FTP), HTTP basic authentication, HTTP form-based authentication, Post Office Protocol (POP), Internet Message Access Protocol (IMAP),Microsoft Windows network authentication, and Telnet.

Best Practices❏ Employ some form of account lockout. That is, after a predetermined number of incorrect login

attempts, the Web application disables the account to prevent the brute force attack fromgaining access to the account. However, an attacker can leverage account lockouts to cause amassive Denial of Service (DoS) for legitimate users due to their accounts being locked. Seethe next section for more details.

Brute-Force Lockouts

An attacker may brute-force attack an account not to gain access, but simply to cause the Webapplication’s lockout feature to disable the account. This in effect is a DoS attack. Freeware toolsthat perform brute-force attacks against HTTP basic authentication or form-based authenticationare especially insidious and effective for this purpose.

Best Practices❏ A lockout mechanism must be used, otherwise an attacker could simply brute-force attack the

account to gain access.

❏ The way in which the lockout mechanism is implemented is of the utmost importance. Youshould implement a "speed bump" mechanism whereby the Web application inserts a delay,such as 30 seconds, between each login attempt. A variation on this theme is to increase thedelay after consecutive failed logon attempts. For example, after three incorrect attempts, theWeb application temporarily disables the account for 30 seconds. After the fourth log-onattempt is unsuccessful, the Web application disables the account for 45 seconds, and so on.This would continue until some maximum was reached, say 15 minutes. This makes brute-forcing the password impractical, while still preventing a long-term DoS attack.

Page 22: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

17

User Name Harvesting

When a user fails a log-on attempt, an error message is typically displayed to the user. This errormessage may provide information that helps an attacker determine the correct username/password. For example, consider the two error messages below:

Scenario 1: Correct user ID with the wrong password"Sorry, but the password supplied is not correct. Please retry…"

Scenario 2: Incorrect user ID"Sorry, but the user ID supplied is not valid…"

The error message indicates whether the password or user ID is invalid, thus providing informativefeedback to an intruder trying to discern the user credentials. In this sort of scenario, an attacker coulddetermine valid user IDs by performing a dictionary or brute-force attack against the application.

Best Practices❏ Login error messages should not explicitly state which of the supplied credentials are incorrect, but

simply that the combination of credentials is incorrect. This concept has been understood andimplemented in UNIX for many years.

Multiple Authentication Disorder

Multiple Authentication Disorder (MAD) can occur when a user requires multiple credentials, suchas a digital certificate and a username/password combination, to log into a system. In suchsystems, it is important for the application to check that both sets of credentials actually representthe same user, and that a single operational identity is established for that user’s session.

METASeS security consultants have examined applications that simply require the user to present avalid digital certificate issued by the Certificate Authority (CA) established by the application’sowner. In some situations, a certificate is considered valid simply because it was issued by a knownCA, such as Verisign. Assuming this certificate is recognized, the user is then prompted for a loginuser ID and password. As long as the user ID and password themselves, and the certificate itself,are valid, then the system allows the user to access the application. In such a case, the less secureuser ID privileges validate identity, rather than the more secure certificate. Not validating both setsof credentials for the same user leads to a case of MAD, and a false sense of security due to theperception that digital certificates are being properly used.

Best Practices❏ Design the application to validate each set of credentials separately and to ensure each applies to

the same user ID.

Concurrency

Concurrent use of an application by the same user at the same point in time is both a design and asecurity issue. While it may seem unlikely that concurrence could occur, it is in fact quite possible.

Concurrency is a design issue in regards to creating the application to handle simultaneous loginsby the same user. It is also a design issue in regards to whether a user receives a unified viewacross all sessions, or one distinct view per session, or is restricted to a single session.

Concurrency is a security issue when no thought is given to handling multiple, simultaneous loginsfrom the same user ID. In fact, many Web application developers do not consider the possibilitythat one user could be simultaneously logged on from multiple locations or perhaps even multipletimes from the same computer. Systems that are neither designed nor tested for this condition aresubject to security breaches.

To illustrate, imagine a home banking application that was neither designed nor developed withconcurrency in mind. Say a user has $1,500 in his savings account. What happens if two people,

Page 23: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

18

simultaneously logged in as the same user from two locations, attempt to withdraw $1,000 from thesavings account at the exact same time? Will one of the transactions fail, or will both transactionssucceed? Both results are possible, depending on how the application is coded to handleconcurrency.

Best Practices❏ Follow secure session management practices. (See chapter 3, Session Issues.)

Resource Exhaustion

During login, some Web applications allocate resources, such as memory, for the "soon to beauthenticated" user. However, if the user never completes the login, the server may not free theresources fast enough for use by other processes. Numerous, incomplete login attempts of anattacker could result in resource exhaustion, which prevents successful logins by legitimate users,triggering in effect a DoS.

Best Practices❏ The login process should include an inactivity timeout, which frees temporarily allocated

resources for use by other sessions if the login process is not quickly completed. This "logintimeout" varies according to the complexity of the login process. For example, if the usermust enter a user ID, email address, and password, the login timeout needs to accommodatethe time required for the average user to input all of this required information.

❏ Ideally, the login process should avoid allocating resources until the user has been fullyauthenticated. In such a case, a login timeout is not needed.

Page 24: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Logon and Authentication

19

Authentication and Logon Best Practices❏ The best-practice authentication method, for the majority of consumer sites that typically

possess low to medium-high security, is form-based. For business to business or high-securitysites, certificates may be needed.

❏ Store certificates and corresponding private keys on card keys or smart cards.

❏ Use HTTP POST. When using form-based authentication, submit the user’s credentials to theWeb server with the HTTP POST method. See chapter 4, Transaction-Level Issues.

❏ Encrypt the session when sending the user’s credentials to the Web application.

❏ Employ SSL with long key lengths.

❏ Verify credentials and assign a session ID (or "bind identify" to the current session ID). Seechapter 3, Session Issues, for details about session tracking techniques and the characteristicsof a strong session ID.

❏ Avoid detailed logon failure messages that an intruder may leverage to collect valid usernames and/or lock accounts. Be sure to avoid login error messages that reveal the validity ofthe supplied credentials.

❏ As with all data being submitted from the client, perform proper filtering at the server. (Seechapter 4, Transaction-Level Issues).

❏ Set up a lockout mechanism to prevent brute-force attacks. See the section AuthenticationThreats and Attacks for tips on mitigating DoS lockout attacks.

❏ Use tokens together with userIDs and passwords to reduce chances of unauthorized logins.

❏ Make sure each set of credentials applies to the same user ID.

❏ Design and test against multiple, simultaneous logins from the same user ID.

❏ Use inactivity timeouts to automatically log out.

❏ Avoid allocating resources until the user has been fully authenticated, or use an appropriatelogin inactivity timeout to ensure server resources are quickly recycled.

Page 25: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

20

This chapter defines Web sessions and session IDs, various session tracking techniques to passsession IDs between server and client, threats and attacks such as session cloning and IP hopping,and logout threats and attacks.

Sessions and Session IDsA Web session is the entire period of interaction between a browser and a Web server, from when auser first enters the site until the session is terminated, either through the direct action of the useror through a forced timeout. Since the focus is on security issues, an authenticated user’sinteraction with the Web application is emphasized. However, whenever a session needs to bemaintained, such as for tracking an anonymous user from page to page, many of the issues outlinedin this chapter apply.

Hypertext Transfer Protocol (HTTP) and Session IDs

When a user requests a Web page, the Web browser makes a network-level connection (that is,TCP/IP) to the Web server, and asks for a specific resource (for example, an HTML document).After receiving the requested item, the Web browser disconnects from the server, thus tearing downthe network connection.

As a user browses from one page to another on a Web site, for example, by clicking on a hyperlink,the Web server doesn’t inherently know that it is the same user who requests the different pages.

Session Issues3CGIASP

Servlet

Logic

User I

/O

DB I/O

Session Tracking

Log On Log Off

Database

User

Web Application

Network Security

Web Server Configuration

OS Configuration

Page 26: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

21

Therefore, a token or unique identifier must be used when the browser communicates with the Webserver to maintain state (that is, track the user’s session). We refer to this token as a sessionidentifier or session ID. A session ID uniquely identifies the user and distinguishes the session fromall other active sessions. A session ID often serves as a surrogate for a user ID and passwordcombination.

Without a session ID, the server cannot recognize a sequence of requests as coming from the sameuser. Thus, the server does not have a clear picture of who is going where on the Web site. Thiswill affect the evaluation of hit counts. For example, it is important to know if 100 usersintentionally clicked on your ad banner, versus the same one user clicking 100 times. Withoutsession ID, you may not be able to tell the difference.

The server generates the session ID and gives it to the client; it is then used whenever the clientcommunicates with the server. When the user is authenticated, the server binds the user’s identityand privileges to the user’s session ID. In this way, the session ID automatically re-authenticates theuser for subsequent connections with that server, at least for connections that requireauthentication. So, in brief, the session ID is a short-term secret that uniquely identifies a userduring a session. For most e-Commerce packages, such as WebLogic or OpenMarket, the session IDgeneration and management are integrated into the product to help ease the development of Websites and applications.

If an attacker can guess, steal, or intercept an authenticated user’s session ID, then the attacker maybe able to use it to impersonate that user during the session. Therefore, the session ID must bedesigned to prevent this type of attack. (See Session Cloning under the section Session Tracking --Threats and Attacks). To an attacker, a session ID can be just as valuable as a user ID and password.

Session ID Best Practices

The session ID should have the following characteristics:

❏ Uniquely identifies the user and distinguishes the session from all other active sessions (notwo session IDs are alike ). Ideally, session IDs will never be reused. This is particularlyimportant in cases where the session ID is embedded within a URL and can be saved as abookmark, posted on a message board, or e-mailed to a friend.

❏ Be random in nature (that is, not predictable).

❏ Has a large alphanumeric string (cannot be easily brute-forced via a dictionary attack, forexample, by guessing every possible string).

❏ Does not contain sensitive1 information in clear text (information such as the user’s accountnumber or Social Security number).

❏ Is temporary (does not persist for excessively2 long periods of time).

❏ Has cryptographic properties that make it difficult for users to modify their own session IDs.

❏ Has a rotating session ID, that is, the session ID changes periodically throughout the session.

1 Even if the session ID’s privacy can be guaranteed, the end user who has access to the session ID maybe concerned with the use of such information. So this issue becomes one of user perception.

2 What is defined as "excessively long periods" depends on the nature of the application and its users.In some financial Web applications, a session ID automatically expires after 24 hours, even if it isactively used the entire time. This forces issuance of a new session ID to the user, and requires him tomanually re-authenticate to continue accessing the Web application.

Page 27: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

22

Session Tracking TechniquesThis section discusses techniques for tracking the session ID between the client and server duringthe session. The techniques discussed include:

• URL Rewriting• Hidden Form Elements• Cookies• IP Addresses

Keeping the session ID secret for the duration of the session is of paramount importance.Therefore, the main threat to all session tracking techniques is accidental exposure of the sessionID, which could lead to session cloning, the unauthorized duplication of a session ID (see thesection Session Cloning). Each technique discussed below describes ways to mitigate this risk, inaddition to describing other best practice principles.

URL Rewriting

URL rewriting is a form of session tracking that places the session ID at the end of every URLserved to the browser, for instance:

https://www.bank.firm/scripts/transfer.asp?sID=3948KD839

The above example illustrates a weak session ID. In the figure, the session ID is sID and is equal to3948KD839. Whenever the user clicks on a link that points back to the Web server, the browsersends the session ID as part of the URL requested. The Web application parses the session ID fromthe URL in order to track the user.

Strengths• URL rewriting is universally accepted by all browsers, regardless of the user’s configuration.

• URL rewriting is not perceived by users to be a privacy concern on the order of cookies.

WeaknessesThe session ID can be revealed accidentally in many ways:

• Through the browser history file• Via the HTTP Referrer field• By placement on the end of non-encrypted hyperlinks, for example:

http://some-other-public-site.com/index.html?SessionID=Kdk93kd8fw).• In Web server access logs (every URL requested is typically recorded in such logs)• In proxy logs

For more information on the risks of placing sensitive information within a URL, see the section GETvs. POST in chapter 4, Transaction-Level Issues.

Furthermore, a malicious user can easily manipulate his own session ID to exploit the Web application.Such "malicious user input" could result in the execution of commands on the Web server, or theimpersonation of another user. (For details, see the section Unexpected User Input in chapter 4,Transaction Level Issues.) While all session tracking methods are susceptible to manipulation by theuser receiving the session tracking information, URL rewriting is especially trivial to exploit.

Best PracticesGiven the various ways in which the session ID could be revealed, URL rewriting is not a preferred method. However, if its use is required, apply the following principles:

❏ Ensure the session ID is not placed on the end of non-encrypted URLs .

3 Web and proxy logs may be susceptible to theft. Valid session IDs have been captured by leveragingdefault material or weaknesses in the logging software.

Page 28: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

23

❏ Enforce session inactivity timeouts.

❏ Use an encrypted session ID. This makes it very difficult for a user to manipulate his ownsession ID, or for a malicious user to guess the session ID of another user.

❏ Avoid non-encrypted links to other Web servers (for example, business partners orinformational sites) whenever the last URL requested contains the session ID. This is becausethe HTTP Referrer field may contain the URL, thereby revealing a user’s session ID.

Hidden Form Elements

HTML supports a form element type called "hidden." The server sends to the browser variables ofthis type, along with their values, embedded in the HTML code. Browsers do not display thesevalues as default values, since the user is not supposed to change them. The following exampleshows a session ID embedded in a hidden form element:

<FORM ACTION="/cgi-bin/shopper.cgi" METHOD="POST"><TD ALIGN=right><INPUT TYPE="SUBMIT" VALUE="Buy Now"></TD><INPUT TYPE="HIDDEN" NAME="SessionID" VALUE="S7jd7S8394kS80g"></FORM>

HTML source code like that illustrated can easily be viewed with the "view source" feature built intomost browsers. A malicious user can also modify the HTML source code using Notepad,FrontPage, or another editor. Once modified, the form can then be sent to the Web server.

An example of the vulnerability created by trusting hidden fields can be found in a popular Web-based shopping cart application. This application uses hidden fields to store the price of items thata user has in his shopping cart. Once the user checks out, the total bill is computed based uponthe prices contained in the hidden fields. The Web application does not validate that the pricestored in the hidden fields is actually valid. Thus, a malicious user can set his own prices by editingthe HTML source code.

Strengths• Hidden form elements are universally accepted by all browsers, regardless of the user’s

configuration.

• Hidden form elements are not perceived by users as a privacy concern on the order ofcookies.

Weaknesses• Hidden form elements require all user interaction with the Web site to be an ACTION

statement, for example, GET or POST statements. (See the section GET vs. POST in chapter 4,Transaction-Level Issues). The use of GET for any ACTION statement reduces the hidden formelements method to the security equivalent of the URL rewriting method. The session ID maybe exposed in a variety of ways (see the section URL Rewriting above).

• Users can view and potentially alter any information contained within hidden fields. Oncemodified, the hidden fields can then be transmitted to the Web server.

Best Practices❏ Use the POST method for all ACTION statements.

❏ Do not rely on hidden fields to store sensitive information.

❏ Do not blindly trust values contained within hidden fields, particularly for making criticalbusiness decisions.

Page 29: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

24

Cookies

HTTP cookies are a Web server mechanism to store and retrieve information on the user’s Webbrowser. Cookies are actually HTTP fields. They have only the following six parameters:

1. NAME -- The name is an arbitrary string used to identify the cookie, as a Web server can sendthe user more than one cookie.

2. DOMAIN -- The domain parameter defines the range of hosts where the browser is permittedto transmit the cookie. For example, for any Web server with the domain nevam.com.

3. PATH -- The path shows the range of URLs where the browser is permitted to transmit thecookie within the listed domain. For example, only for URL paths that contain /cgi-bin.

4. EXPIRES -- This date parameter indicates when the browser can no longer store the cookie. Ifthe browser sets the date to one in the past, then the browser does not save the cookie to theuser’s hard drive. Instead, the cookie is kept in memory and only used when the browser isopen. When the browser is shut down, the cookie is cleared from memory and is no longeravailable for use by the browser. Such a cookie is known as non-persistent cookie.

5. SECURE -- This Boolean value indicates if the browser is permitted to send the cookie over anon-encrypted session. A value of True or Yes means the browser can only transmit the cookieto the Web server when communicating over a Secure Hyper Text Transfer Protocol (HTTPS),that is, a Secure Sockets Layer (SSL) encrypted connection.

6. DATA -- This field can contain arbitrary strings of text. It is where the server places data suchas a session ID.

Strengths• The SECURE parameter can be used to ensure the session ID only gets transmitted within an

encrypted session (for example, SSL).

• PATH and DOMAIN limit the scope of use for the session ID, thus reducing accidentally exposure.

Weaknesses• Privacy concerns over the use of cookies by marketing and advertising firms to track users

and build profiles may cause some users to disable this browser feature.

• Users can view the contents of all cookies that are sent to them or stored on their computer.Users can also modify the contents of those cookies.

• Browser bugs in parsing Internet domain names can cause the scope of the DOMAIN parameterto be virtually ignored, thereby sending cookies to all sites to which a user connects.

Best Practices❏ Mark the cookie as SECURE.

❏ Limit the PATH and DOMAIN, whenever possible, to only systems and areas where the cookieis needed.

❏ Encrypt or cryptographically sign the contents of the DATA field to prevent user tampering orthe revealing of stored sensitive data such as account numbers.

❏ Use non-persistent cookies. This makes it more difficult (but not impossible) for a malicioususer to modify the cookie’s contents (see the section Unexpected User Input in chapter 4,Transaction-Level Issues).

4 There are cases were a persistent cookie supports desired functionality. Suppose a bank encrypts your account numberin a cookie. When you go to the site, the cookie is retrieved, decrypted, and the account number is placed into theHTML. You see a drop-down menu with your account number, which is a handy feature when you have numerousaccounts. However, it is a risky feature if someone steals your cookie files (and PIN number) and cracks the encryption.

Page 30: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

25

IP Addresses

An identifier for a computer or device on a TCP/IP network. Networks using the TCP/IP protocolroute messages based on the IP address of the destination. The format of an IP address is a 32-bitnumeric address written as four numbers separated by periods. For example, 1.160.10.240 could bean IP address.

StrengthsTracking the client’s IP address throughout the session can help mitigate the threat of session cloning.

WeaknessesAttempts to rely solely on the client’s IP address as a session ID is problematic for several reasons. Most notable is the loss of the one-to-one relationship needed to uniquely identify and track a userwhen HTTP proxies are involved. In addition, the ease in which IP addresses can be spoofed makesthis an impractical method for security reasons.

Best Practices❏ Do not rely solely on the user’s IP address as a form of session tracking.

❏ Track the user’s IP address or the domain name it is coming from in order to reduce the threatof session cloning.

Session Tracking Techniques Best Practices

❏ Ensure the session ID is not placed on the end of non-encrypted URLs.

❏ Use an encrypted session ID.

❏ Enforce session inactivity timeouts.

❏ Avoid non-encrypted links to other Web servers.

❏ Use the POST method for all ACTION statements.

❏ Do not rely on hidden fields to store sensitive information.

❏ Mark the cookie as SECURE.

❏ Limit the PATH and DOMAIN, whenever possible, to only systems and areas where the cookieis needed.

❏ Encrypt or cryptographically sign the contents of the DATA field.

❏ Use non-persistent cookies.

❏ Do not rely solely on the user’s IP address as a form of session tracking.

❏ Track the user’s IP address or the domain name it is coming from in order to reduce the threatof session cloning.

Page 31: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

26

Session Tracking -- Threats and AttacksThis section outlines session tracking threats and attacks -- such as session cloning and IPhopping -- and ways to mitigate them.

Session Cloning

As previously stated, the session ID identifies a user every time he requests a resource from theWeb server during his session. If an attacker can guess, steal, or intercept the authenticated user’ssession ID, then the attacker may be able to use it to impersonate that user during the session.This is similar to TCP/IP hijacking, whereby an attacker predicts the TCP sequence numbers inorder to grab control of a TCP/IP connection from a legitimate user. For Web applications,duplicating a user’s session ID for unauthorized access is called session cloning.

The conditions that contribute to session cloning are:

• Session IDs that can be intercepted, stolen, or predicted

• Sessions that allow the client to change its IP address in mid-session without the need to re-authenticate. This condition is referred to as IP hopping, and is discussed below. While thiscondition is not required for session cloning, it does make easier for the attacker toaccomplish session cloning.

Best Practices❏ Ensure that the session ID cannot be predicted, intercepted, or stolen. Key defenses include

using unique, long, randomly generated session IDs to avoid prediction, and avoiding the practiceof passing session IDs in URLs in order to prevent theft or interception. Additional mechanismssuch as the use of SSL, always logging out when you’re done surfing, and protecting or erasingyour Web browser cache file can also help avoid the interception or theft of session IDs.

❏ Prevent the user from changing his IP address in mid-session (see the section IP Hopping).

IP Hopping

IP Hopping occurs when a client is allowed to change its IP address during a session, and the Webapplication continues the session without re-authenticating the user. While a legitimate userchanging his own IP address in mid-session does not pose a security risk, allowing such behaviormakes it easier for an attacker to perform other kinds of attacks, for example, session cloning.

At first, trying to prevent IP hopping may seem like a moot point, since an attacker of sufficient skillcould perform IP spoofing5. However, for most applications, the difficulty of attempting sessioncloning and IP spoofing at the same time reduces the risk of session cloning to an acceptable level.

Best Practices❏ Have the server track the user’s IP address for the duration of the session. However, this

introduces functionality problems for users going through Web proxies. Some proxies fail tokeep the session passing through the same proxy for the entire session6. Thus, the sessionappears, by no fault of the user, to change IP addresses when the proxy routes the user througha different proxy in mid-session. Such behavior has been reported with some large ISPs.Therefore, Web applications that terminate user sessions because they change IP addresses inmid-session terminate legitimate users whose ISPs are using faulty or misconfigured proxies.

❏ Preventing IP hopping in this situation places an unacceptable burden on the user since hewould have to manually re-authenticate at random intervals. To avoid this, the server could

5 A process whereby an intruder at a remote location pretends to be transmitting data on a localnetwork

6 The feature that allows a session to always be established with the original Web server is sometimesreferred to as the "sticky" feature for load balancing devices and proxies.

Page 32: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

27

simply track the domain from where the user is coming (for example, SomeISP.net). While thisdoesn’t completely eliminate the possibility of attackers within the same domain trying toclone the session, is does reduce exposure without hindering performance.

❏ Note that, depending on how domain names are parsed, exposure may be left open to a muchlarger audience than intended. For example, many organizations are uniquely identified bydomain names that take the format of domain.com. This could lead application developers toincorrectly assume that all domain names consist of only two components. However, thereare other valid domain name constructs, such as site.com.au. (The term au denotesAustralia when used in this manner.) If the Web application assumes that a unique domainname consists of only two components, site.com.au would be incorrectly parsed as com.au.Restricting access based upon such an incorrectly parsed domain name would still alloworganizations in Australia to hijack the connection. This is because the connectionsuccessfully meets the access control requirement of com.au. Examples of domain names thatwould meet this access control restriction include site2.com.au and site3.com.au).

❏ Mitigate the risk of IP hopping through Secure Socket Layer (SSL) encryption. SSL sessionsgenerate a session ID as part of the process of establishing connections. Applications canassociate their own session IDs with the SSL session ID to ensure that, even if a user’s IPaddress has changed, it is still the same user accessing the Web application. This assumesthat the SSL session ID has not changed.

Session Tracking -- Threats and Attacks Best Practices

❏ Employ strong session IDs (see Session ID Best Practices above).

❏ Perform session tracking over a secure path, such as SSL, to prevent eavesdropping wheneverthe session ID is associated with an authenticated user.

❏ Implement session inactivity timeouts (see the section Physical Access by UnauthorizedIndividuals below).

❏ Track the user’s IP address or domain to reduce the likelihood of session cloning wheneverthe session ID is associated with an authenticated user.

❏ Place the session ID within a secure, non-persistent cookie whenever functionality permits.

Page 33: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

28

Logout Threats and AttacksHaving covered how to establish and track a user’s session, security issues relating to thetermination of the user’s session also need to be considered.

The concept of terminating the user’s session may immediately beg the question, "Why end thesession at all?"

Terminating sessions helps recycle server resources, since a server can only track a finite numberof active sessions. Terminating sessions also protects the user from physical security concerns.(Users often log into Web application from public kiosks, then walk away before logging out,permitting internal intruders to take over their sessions.)

This section discusses the following logout threats and attacks:

• Cached Logout Pages• Physical Access by Unauthorized Individuals• Cached Data Remains After Log Out

Cached Logout Pages

By default, Web browsers cache or store data from Web sites to improve performance. When aremote resource is requested, the browser first determines if it has a cached version in memory oron disk before generating a request to the server. Intruders can make use of cached logout pagesto easily resume a browser session that a previous user assumes has ended. This is best explainedthrough an example.

Imagine the following scenario:

1. User A logs on, thus beginning session X.

2. After performing a few transactions, user A logs out, thus ending session X.

3. Using the same browser (which has not been shut down since session X), user B logs on, thusbeginning session Y.

4. After performing a few transactions, user B then attempts to log out. However, since thebrowser cached the logout page from session X, this page is taken from memory rather thanrequested from the server. The cached page is then displayed to user B. User B sees the "Youare now logged out" page, and mistakenly thinks he is logged out from session Y.

An intruder with access to that browser could simply hit the Back key to resume session Y.

Best Practices❏ It is essential that the browser does not cache Web pages containing sensitive or security

information, such as passwords and session IDs. See the section Cached Data Remains AfterLogout for server techniques to prevent Web browsers from caching.

Physical Access by Unauthorized Individuals

Users who forget to log out of the Web application, and then leave the browser unattended, couldhave their sessions resumed by unauthorized individuals who have access to the browser.

The server should automatically terminate the user’s session after a period of inactivity. For someonline banking Web applications, this "session inactivity timeout" is seven minutes in length.

In addition to protecting users from unauthorized access, session inactivity timeouts help remove"hung sessions." Hung sessions occur when the user is disconnected and there is no way for theuser to resume the session. For example, the user accidentally closes her browser, and the session

Page 34: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

29

ID is in a non-persistent cookie that was erased when the browser closed. In this case, without thesession ID, the user is unable to resume the particular session. Terminating inactive sessions helpsthe server clean up these hung sessions, and make better use of server resources.

Best Practices❏ The server should automatically terminate the user’s session.

Cached Data Remains After Logout

During a user session, sensitive account information is sometimes displayed. Depending on howthe user’s browser is configured, and how the Web server marked those sensitive pages (forexample, the use of tags within the HTTP and/or HTML), the information could remain on the user’scomputer, either in memory or stored in a temporary file. This raises the possibility ofunauthorized disclosure by those with physical access.

Best Practices❏ The server can use various anti-caching techniques, such as setting the Pragma HTML header

to "no-cache", and shutting down the user browser to clear memory, to prevent the browserfrom caching sensitive data.

❏ For browsers that may not be fully compliant with the anti-caching techniques, the Web sitecould display a warning to users after they log out, as follows:

You are now logged off of Credit Union Online.

The account information you have just seen remains in your Web browser's memory until youclear your browser's cache or close the browser. To protect the confidentiality of your accountinformation, before you leave this Internet account access service make sure you clear yourbrowser's memory cache to prevent someone else from being able to view your accountinformation temporarily stored on your computer. You can either: 1) shut your browser downwhich will, in effect, clear your cache; or 2) you can clear your cache, using the instructionsprovided in your browser's online help system.

Such a warning would instruct users on how to manually remove this cached data.

For more information on how the Web server can prevent browsers from caching sensitive data, seethe section Browser Caching in chapter 4, Transaction-Level Issues.

Session Logout Best Practices

❏ Implement a session inactivity timeout.

❏ Prevent the browser from caching the logout page.

❏ Prevent the browser from caching sensitive data after the session is terminated. Use anti-caching techniques or advise the user on how to clear his browser’s cache.

❏ As with all client-submitted data, perform proper filtering at the server level (see chapter 4,Transaction-Level Issues).

Page 35: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Session Issues

30

Session Issues Best Practices❏ Employ a session ID that uniquely identifies the user and distinguishes the session from all

other active sessions.

❏ Employ a session ID that is random, temporary, has a large alphanumeric string, and does notcontain sensitive data in clear text.

❏ Implement session inactivity timeouts.

❏ Prevent the browser from caching sensitive data after the session is terminated. Use anti-caching techniques or advise the user on how to clear the browser’s cache.

❏ For browsers that may not be fully compliant the anti-caching techniques, the Web site coulddisplay a warning to users after logout.

❏ Perform proper filtering at the server level.

❏ Ensure the session ID is not placed on the end of non-encrypted URLs.

❏ Use an encrypted session ID.

❏ Avoid non-encrypted links to other Web servers whenever the last URL requested contains thesession ID.

❏ Use the POST method for all ACTION statements.

❏ Do not rely on hidden fields to store sensitive information.

❏ Mark cookies as SECURE.

❏ Limit the PATH and DOMAIN, whenever possible, to only systems and areas where cookies areneeded. Encrypt or cryptographically sign the contents of the DATA field.

❏ Use non-persistent cookies.

❏ Prevent the browser from caching the logout page.

❏ Do not rely solely on the user’s IP address as a form of session tracking.

❏ Track the user’s IP address or the domain name it is coming from to reduce the threat ofsession cloning.

❏ Ensure that the session ID cannot be predicted, intercepted, or stolen.

❏ Prevent the user from changing his IP address in mid-session.

❏ Perform session tracking over a secure path such as SSL.

❏ The server should automatically terminate the user’s session.

Page 36: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

31

After the user logs onto a Web application, and has established a session, he can then performtransactions1. We define a transaction as the process by which a user supplies input that isprocessed by a Web application in order to yield some result, that is, an output or action.Therefore, this chapter covers all three aspects of a transaction:

• User input sent to the Web application• The processing of user input by the Web application• The output sent by the Web application as a result of the user’s transaction2

This broad definition of transaction applies to the process of user logon and logout. Even sessiontracking could be thought of as a transaction, as the session ID is sent by the user and processedby the Web application throughout the session, albeit this is done automatically and transparentlyto the user. Therefore, the issues covered here should be applied as well to matters covered inchapter 2, Logon and Authentication, and chapter 3, Session Issues.

Many recommendations within this chapter also apply to Web application components where thesource code is available. However, with applications developed off site the source code will not beavailable. (See the section Commercial Off the Shelf (COTS) Products).

Transaction-Level Issues4CGIASP

Servlet

Logic

User I

/O

DB I/O

Session Tracking

Log On Log Off

Database

User

Web Application

Network Security

Web Server Configuration

OS Configuration

1 This is true in most cases. However, many sites allow some transactions such as a site search to beperformed by unauthenticated users or visitors. The chapter also applies to such situations.

2 Technically, the Web application may need to call a back-end database in order to complete thetransaction. Given the importance of that topic, it has its own chapter (see chapter 6, DatabaseIssues).

Page 37: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

32

Transaction-Level Issues -- Threats and AttacksThis section discusses the following transaction-level threats and attacks:

• Unexpected User Input• Client-Side Filtering -- Active Content and HTML• GET vs. POST• Improper Application Flow• Verbose Error Messages• Disclosure of Client Data• Commercial Off the Shelf (COTS) Products

Unexpected User Input

The main threat from user input occurs when it is different than what was expected, and thisdeviation causes inappropriate responses from the Web application.

User input can differ from what was expected in several ways. These deviations may be divided intothree basic categories:

• Size -- Too big or small• Content -- Alternate or inappropriate choices• Type -- Special characters

Each category is discussed in the sections that follow.

We refer to user input that intentionally employs one of the techniques outlined below as malicioususer input.

SizeUser input can be much larger than expected. This can create problems for the process or server-side executable. An example is active server pages (ASPs) that are attempting to store the inputinto a buffer that is smaller than the input, resulting in a condition known as a buffer overflow.Buffer overflows can cause unpredictable actions, including the execution of user-suppliedcommands that can grant a malicious user full administrative access to a Web server, or verboseerror messages, which can provide too much useful information to a would-be intruder (see thesection Verbose Error Messages).

ContentSometimes the user submits data selected from a list of possible choices, such as a drop-down list of cities. A malicious user can easily add options to such lists. For example, if the Web applicationis expecting a number from 1 to 10, the user could submit 11. As a second example, if the Webapplication requests a funds transfer amount, a user might enter a negative amount.

TypeSpecial characters are characters that have significance to the command or application receiving the data, and that cause unexpected results when received. This is due to the fact that somescripts perform a run-time evaluation of an expression that contains user-supplied input. Carefulplacement of special characters within the user-supplied input can disrupt the run-time evaluation,allowing a malicious user to execute commands at the operating system level.

Table 4-1 has examples of special characters.

Page 38: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

33

Best Practices❏ The most important security-related principle to remember when developing a Web

application is:

The user can manipulate any and all input being sent to the Web application or Web server.

This principle holds for various kinds of user input. These include:

• Cookies, which the server originally defined• Normal form elements that had bounds checking done by JavaScript embedded in the

HTML, or restrictions set by HTML• Hidden form elements originally defined by the server• Browser elements, such as User Agent, which the typical user normally does not define

but which are defined automatically by their browser• Anything transmitted in the HTTP protocol header itself

❏ Another principle to remember is:

Ultimately, the user has final control over all data sent from his browser.

Therefore, the most critical step in any Web application is for all user input to be filtered atthe server. Client-side techniques, such as JavaScript, cannot be relied upon to preventmalicious user input. (Refer to the following section, Client-Side Filtering -- Active Content andHTML. Code-level techniques to sanitize user input at the server are discussed in chapter 5,Server-Side Coding Techniques.)

Client-Side Filtering -- Active Content and HTML

Active content applications -- for example, JavaScript or VBScript -- can be embedded in the HTMLthat is served to the browser. JavaScript can be used to ensure required user input is given. Anexample of this is to detect when the user left blank a required form element. JavaScript can alsocheck if the supplied input meets certain requirements, such as validating a user’s e-mail addressby asking the user to enter it twice, and then comparing the two entries to ensure that both entriesare identical. This provides a convenient way to filter user input. However, since the user controlsthe client, an intruder can bypass these client-side filters to submit malicious input.

Another option is to use HTML parameters to restrict the size of user input. For example, <INPUTMAXLENGTH=10> would restrict the user’s input to 10 characters. However, a malicious user can

Newline character (in hexadecimal)

Pipe (for putting VBA code within SQL statements)

Semicolon (useful for data passed to shells)

Double quote

Single quote

VB Script terminators

Server-side includes

%0A

|

;

"

<% %>

<!--#exec cmd="cat /etc/passwrd" -->

Symbol Meaning

Table 4-1: Special Characters

Page 39: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

34

easily circumvent such restrictions by editing the underlying HTML code to increase or entirelyremove the MAXLENGTH limitation.

Best Practices❏ Use client-side filters to stop users from accidentally submitting incorrect data. Such data

would otherwise take the server time to process before returning an error message. Webapplication performance will be enhanced. For example, a client-side JavaScript filter coulddisplay an error message to the user if he tries to submit too short a password, for example,less than six characters. Since the filter is running on the client, this is faster than transmittingthe data, processing it on the server, and then finally returning an error message to the user.This is especially true for transactions that require heavy computations or database calls.

❏ Client-side techniques are useful for improving performance by preventing accidental inputerrors, but cannot be relied upon for security functions, such as blocking malicious user input.Therefore, all user input must be filtered and validated at the server.

GET vs. POST

The Hyper Text Transfer Protocol (HTTP) has various methods for allowing users to submit data tothe Web server. The two most popular methods are called GET and POST.

The GET method places all user input sent by the browser onto the URL. The following exampleshows what the browser sends with a GET when the user searches for the phrase "Web security" atYahoo (www.yahoo.com):

GET http://search.yahoo.com/bin/search? p=Web+security HTTP/1.0Accept: image/gif, image/jpeg, */*Referer: http://www.yahoo.com/Accept-Language: en-usUser-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows 95)Host: search.yahoo.comCookie: B=4336h7iu1biig

The user-supplied input ("Web security") is placed into the URL requested.

With the POST method, user input is placed into the body of the HTTP message, not the requested URL.

The following example shows what the browser sends with a POST when a user searches for thephrase "Web security" at Amazon (www.amazon.com).

POST http://www.amazon.com/exec/obidos/search-handle-form HTTP/1.0Accept: image/gif, image/jpeg, */*Referer: http://www.amazon.com/exec/obidos/subst/home/home.html/Accept-Language: en-usContent-Type: application/x-www-form-urlencodedUser-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows 95)Host: www.amazon.comContent-Length: 63

url=index%3Dblendedandfield-keywords=Web+securityandGo.x=12andGo.y=13

The user-supplied input is placed within the body of the HTTP message.

Security threats derive from the fact that URLs get stored in several insecure places. These include:

• Browser history files• Web server access logs• Proxy server logs

Page 40: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

35

Using the GET method with sensitive data, such as an account number, may expose the data tothird-party disclosure. For example, a malicious user may remotely compromise a victim’s personalcomputer and steal the browser history file, which is typically stored in a well-known place and isnot encrypted.

Best Practices❏ Use the HTTP POST method whenever the user sends sensitive data.

Improper Application Flow

When performing a transaction, the composition of the user’s input may not in itself be malicious.For example, it may not be too big nor contain special characters. However, it could still be amalicious request in the sense that it asks for the transaction in the first place. For example, anauthenticated user can sometimes perform unauthorized transactions just by knowing the rightURLs to request, or parameters to submit. This security issue becomes a matter of authorization: Isthe user authorized to perform the requested transaction? If the Web application does not verifyauthorization for each transaction, and in the proper sequence, then the Web application could beat risk.

Here’s another real-world example of a flaw in application flow. While assessing the security of anonline banking application, METASeS discovered that users could exploit a glitch in theapplication’s logic flow to reveal the account balances of other users. The scenario is describedbelow:

When user U tried to transfer amount X from account A to account B, the proper sequence ofevents to verify the application would have been:

1. Does user U have permission to take funds from account A?

2. Does user U have permission to transfer funds into account B?

3. Does account A have enough funds to cover the transaction?

For the application METASeS assessed, step 3 was performed first. This allowed malicious users torequest a large funds transfer from an account they didn’t own. Their aim was to see the accountbalance in the resulting error message:

Sorry, we cannot complete the transfer because account A only has a balance of Y.

Best Practices❏ Perform code logic analysis.

❏ Write clean code. (An obvious but essential technique!) For information on softwaredevelopment best practices, refer to the METASeS report, Secure System Development LifeCycle.

Verbose Error Messages

At times, the Web application encounters an error state, caused by something the user submitted,or for some other completely different reason such as a failed database call. What the Webapplication displays to the end user as an error message can have a big impact on security.

A primary reason to show any type of error message is to inform the user that her transaction orrequest could not be completed. Secondarily, the error message can help developers track downpersistent problems, especially when the user is instructed within the error message to contacttechnical support with a specific error code.

The danger with error messages is that they may reveal too much information about the underlyingcode or architecture of various Web application components. In the hands of a malicious user, this

Page 41: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

36

information can be used to leverage weaknesses in the Web application. Error messages are one ofthe more difficult areas to address.

For example, the following error message, taken from a real Web application, was displayed whenthe malicious user intentionally input the wrong format for his e-mail address:

Error Occurred While Processing RequestError Diagnostic Information

ODBC Error Code = 37000 (Syntax error or access violation)[Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near‘a’.Data Source = "someDB"SQL = "SELECT * FROM request WHERE userID = personx AND email = '1a'"The error occurred while processing an element with a general identifier of(CFQUERY), occupying document position (6:1) to (6:50) in the template fileD:\Inetpub\victim\credit\new_user\credit_access.cfm

This error message shows the SQL statement with which the Web application attempted to query adatabase. It also shows the e-mail address (which is submitted by the user) enclosed in singlequotes. A malicious user could use this information to insert special characters into the e-mailaddress when submitting this same request. This would modify how the SQL statement is parsed onthe server, causing the Web application to retrieve more account information from the databasethan the user is authorized to access.

Best Practices❏ Most COTS products, such as Cold Fusion, can be configured to return either verbose or terse

error messages. In these cases, it is a matter of understanding the product features andconfiguration settings.

❏ For custom Web application components, proper error handling and input filtering areimportant considerations that require typical software development best practices.

Disclosure of Client Data

Invariably, many Web applications handle sensitive customer data. While securing this data on theserver side is important, it is also important to consider security issues for this data when it resideson the client side.

These issues include

• Eavesdropping• Downloaded files• Browser caching

EavesdroppingWhile data is in transit across untrusted networks, such as the Internet, it is vulnerable to eavesdropping.

Best Practices❏ Encrypt data in transit using session-level techniques such as SSL (Secure Sockets Layer).

This is the most obvious way to prevent eavesdropping. The Web server can be configured toserve pages to the client only via an encrypted session.

❏ Configure the server to only support strong ciphers and large bit-strengths, therebypreventing users from unintentionally using weak encryption (for example, 40-bit RC4).

Page 42: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

37

Downloaded FilesFor some Web applications, the user is allowed to download account information as a spreadsheetfile or in some other format such as Quicken files. Once on the user’s system, these files are likelyto be kept unencrypted on operating systems that offer little or no access controls to preventunauthorized access.

Best Practices❏ Where the user is permitted to download sensitive data, for example, Quicken files, the Web

application should warn users to store such files in a secure location, such as on a floppy diskthat can be kept offline.

Browser CachingBy default, Web browsers cache data from Web sites to improve performance. When a remoteresource is requested, the browser first determines if it has a cached version, in memory or on disk,before generating a request to the server. The cached files can be stored unencrypted on the user’shard drive for several days, depending on the browser’s settings. Therefore, sensitive data viewedby the user during his session is vulnerable to theft. In many cases, the user is unaware that herbrowser has created these cached files.

Best Practices❏ To prevent Web browsers from caching sensitive account data, the server can employ three

basic techniques:

1. Use a meta tag inside the HTML <HEAD> section:

<HEAD><META HTTP-EQUIV="Pragma" CONTENT="no-cache"></HEAD>

2. Use the Hypertext Transfer Protocol (HTTP) "Pragma" header:

Pragma: no-cache

3. Use the HTTP "Expires" and "Date" headers.

Expires: Monday 01-Jan-80 12:00:00 GMTDate: Monday 01-Jan-90 12:00:00 GMT

The Expires header field gives the date/time after which the entity, for example, an HTMLpage, should be considered stale. This allows information providers to suggest the date afterwhich the information may no longer be valid. Web browsers must not cache the Expiresentity beyond the date given. However, to prevent the browser from caching the page in thefirst place, the date given in the Expires header should be equal to or earlier than the dategiven in the Date header.

❏ Alternatively, you can warn your users about clearing their caches manually. Using servertechniques to prevent caching is preferred. The following sample shows what a site coulddisplay to users after logout:

You are now logged off of Credit Union Online.

The account information you have just seen remains in your Web browser's memory until youclear your browser's cache or close the browser.

To protect the confidentiality of your account information, before you leave this Internet accountaccess service, make sure you clear your browser's memory cache to prevent someone else frombeing able to view the account information temporarily stored on your computer. You can eithershut your browser down which will, in effect, clear your cache; or, you can clear your cache, usingthe instructions provided in your browser's online help system.

Page 43: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

38

Note further that, although it is a good practice to disallow proxy servers and browsers fromcaching sensitive data, compliance may be otherwise. Proxy servers and some browsers canbe set to ignore "Pragma: no-cache" and other, similar directives.

Commercial Off the Shelf (COTS) Products

Often, Web application developers rely on closed-source programs (for example, Cold Fusion) toimplement or support their Web application where the source code is not available formodification. We refer to these programs generically as third-party products (TPPs) or commercialoff the shelf (COTS) products. Because by their nature COTS products are developed outside theorganization, an organization may have less control over the security holes contained in them.

Best Practices❏ Employ write wrappers to accept and filter input going from the user to the COTS, or to

intercept inappropriate replies going to the user from the COTS.

❏ Research public security forums and relevant vendor Web sites for known security issues withthe COTS. (See the appendix for Web sites and other sources of information on securing Webapplications.)

❏ Register with the product vendor to stay informed about security bulletins and softwareupdates on such items as patches for the COTS.

❏ Contact the vendor and ask if an independent third-party review of security issues has beenperformed on the product.

❏ Use available COTS configuration options to implement other best practices where possible.

❏ Perform a security assessment on the COTS product.

Page 44: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Transaction-Level Issues

39

Transaction-Level Best Practices❏ Keep in mind that the user can manipulate any and all input being sent to the Web application

or Web server.

❏ Remember that the user has final control over all data sent from his browser.

❏ Filter all user input at the server for proper size and content. Do not rely solely on client-sidefiltering techniques for security.

❏ Determine proper authorization levels before processing user input.

❏ Ensure transactions with sensitive information are submitted using the HTTP POST method.

❏ Perform code logic analysis; write clean code.

❏ Employ client-side filtering techniques, such as JavaScript, for enhancing performance andfunctionality.

❏ Ensure error messages revealed by the application contain an appropriate level of detail, notan excessive and revealing level of detail.

❏ Encrypt session traffic between the client and the Web application when sensitive data, forexample, account information, is being viewed or transmitted.

❏ Configure the server to only support strong ciphers and large bit strengths.

❏ Warn users to secure downloaded files.

❏ Employ anti-caching techniques to prevent browsers from storing sensitive information on theclient system.

❏ Employ write wrappers to accept and filter input and output.

❏ Research public security forums and relevant vendor Web sites for known security issues withthe COTS.

Page 45: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

40

The Common Gateway Interface (CGI) is a standard mechanism that allows designers a means fordeveloping interactive Web applications. Originally specified as part of the HTTP/1.0 protocol, CGIprovides a straightforward, yet flexible interface for creating applications that range from simpleHTML form processing to complex portals offering personalization and dynamic content.Unfortunately, vulnerabilities can result from the ease of implementing CGI programs withoutappropriate security controls, the capabilities that CGI provides for accessing potentially all systemresources, and the assumption that users always only use an application in the manner intended.These vulnerabilities can compromise the overall integrity of every Web site running on a givensystem.

The CGI specification provides a defined set of interfaces for exchanging information with Webbrowsers using the Web server as an intermediary. Writing to the CGI specification, however,is not limited to a specific programming language. Any language that is capable of accessingoperating system environment variables and writing information to standard output (that is,the screen) can be used to write CGI programs. Common choices include interpretedlanguages such as Perl, TCL, and UNIX shell scripts, as well as compiled languages such as Cand C++.

Although this chapter talks generically about CGI, many of the same security considerations andcoding techniques that apply to CGI programs also apply to the technologies that have replaced orsupplemented CGI over the years. Examples of these technologies include Active Server Pages(ASP), Cold Fusion, Internet Server Application Programming Interface (ISAPI), Java Server Pages(JSP), Netscape Server Application Programming Interface (NSAPI), PHP3, Server Side Includes (SSI)

Server-Side Coding Techniques5CGIASP

Servlet

Logic

User I

/O

DB I/O

Session Tracking

Log On Log Off

Database

User

Web Application

Network Security

Web Server Configuration

OS Configuration

Page 46: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

41

and a slew of other server-based interfaces. In many ways, the added complexities of thesetechnologies due to cross-platform support and closed-source implementation can make them moreinsecure than CGI itself.

This chapter does not cover all possible secure CGI coding techniques for all possible CGIprogramming languages. Instead, it provides explanations and illustrative code for some of the CGIcoding practices that are most critical for developing secure CGI applications.

Page 47: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

42

Secure Coding PracticesMany CGI programs in use on the Web today were not designed to be secure, much less resistant toattack by a persistent, malicious user. Instead, these programs were created to serve a specificpurpose based upon a set of requirements and assumptions about functionality and userinteraction. Testing of these programs, if performed at all, is commonly done to check expected useof the program and "honest" input errors such as a user entering an incorrect password or perhapsentering an alphabetic character into a numeric input field. Very rarely are programs tested for theunintended or unexpected, such as a malicious user submitting one megabyte of binary data in lieuof a ten-digit phone number.

This section identifies common mistakes, misconceptions, and assumptions that are often madewhen implementing CGI programs, as well as steps to mitigate the resultant risks.

The following areas are covered:

• The principles of least privilege and compartmentalization• Never trust user input• User input and shell evaluation• Check all system function return values• Protecting the application from its environment, and vice versa• Verbose error messages • Memory allocation and buffer overflows• External application dependencies and messages of arbitrary length

Principles of Least Privilege and Compartmentalization

The principle of least privilege is the idea that each application, whether Web server, CGI program,or other application, is run with the minimum set of permissions necessary to perform the requiredtasks. While it may be easier to run every application with system-level privileges (for example,root or administrator privileges), doing so virtually guarantees that an attacker would compromisethe entire system were he to locate a single vulnerability.

On the other hand, if each application runs with the absolute minimum set of privileges required,an attacker that compromises one application would at worst be able to compromise otherapplications sharing the same set of privileges. To limit the damage that one compromisedprogram could potentially do to other applications, it often makes sense to have each applicationrunning under its own distinct set of limited privileges. This is known as compartmentalization.

Best Practices❏ To minimize the possibility of total system compromise as a result of a single application

vulnerability, run applications in a compartmentalized manner with the minimum set ofpermissions required to operate them.

❏ Note that compromising one application may still compromise the entire system if othervulnerabilities or configuration issues are present. Nonetheless, operating with leastprivileges possible in a compartmentalized environment makes an attacker’s objective muchmore difficult.

Never Trust User Input

As discussed in chapter 4, Transaction-Level Issues, user-provided input cannot be trusted to bewhat the system designer anticipated.

Simply put, since the user controls the Web browser on his desktop, any and all client-side controlsor validation can be bypassed or modified. Further, full access to, and manipulation of, theunderlying HTTP protocol is possible.

Examples of the many items under the user’s control that can be altered or bypassed include:

Page 48: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

43

• Form input fields, even when pre-populated selection lists are provided (for example, adding afifty-first state called ZZ to the pull-down list of valid states)

• Hidden fields contained within forms• Client-side filtering of form input done via JavaScript, VBScript, or other language• Cookies, whether disk- or memory-based• Session identifiers• Authentication credentials• Referer tags• User agent identifiers• Any and all information conveyed by the HTTP protocol

Trusting user input in Web-based applications has caused many organizations to fall victim tovarying degrees of system compromise. Real-world examples include:

• The ability to crash a major publishing firm’s Web servers by executing resource-intensivequeries. This organization used client-side JavaScript to "prevent" users from executing thesequeries. The queries were executed by bypassing the organization-provided HTML query formand by POSTing complex queries directly to the search engine’s CGI application.

• Numerous shopping cart applications that calculate product-pricing information based uponso-called hidden fields contained within HTML forms. Altering the values of the hidden fieldsallowed users to purchase items for whatever price they desired – even for no cost at all.

• A portal software provider that uses easily guessable session IDs embedded within URLs.Guessing session IDs and entering them into the URL allowed one user to "become" anotheruser, with full access to that user’s personal profile, e-mail, etc.

• A software vendor that provides electronic software product upgrades based on the userpossessing a valid serial number. Serial number validation was enforced using client-sideJavaScript, allowing the verification routine to be easily bypassed. Prior to allowing thedownload, the vendor "verified" that the user had come from the page containing theJavaScript validation routine by checking the HTTP Referer tag. This check was easilybypassed by manually providing the appropriate value in the HTTP Referer tag.

Best Practices❏ Expect the unexpected when writing CGI applications. Be very selective of what portions of

user-provided input that action is taken upon.

❏ Validate all input for correctness, and reformat as necessary for the proper operation ofCGI applications. An example of validating user input can be found in the followingsection.

User Input and Shell Evaluation

As previously discussed, trusting user input in Web-based applications can lead to unfortunateconsequences. This is particularly true where user input is supplied to programs that invoke acommand shell interpreter. The Perl example demonstrates the potential ill effect of using a shellto execute dependent programs from within a CGI application. Although this example is UNIX-centric, similar vulnerabilities exist when using Windows-based command shell interpreters suchas cmd.

In this example, the CGI program mails the contents of the /path/to/file file to the user identified bythe variable $email_address. Either an HTTP POST or GET request could be used to populate the$email_address variable:

system("/usr/lib/sendmail -t $email_address < path/to/file");

Because this command is executed using a system shell, a malicious user could provide additionalcommands in addition to an e-mail address to the variable $email_address, and have the shell

Page 49: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

44

execute those commands. For example, the malicious user could provide input such that$email_address is set as follows:

[email protected] < /some/file; malicious_command

Since UNIX shells use the semicolon character to separate commands, a shell evaluates the input tothe CGI program as two separate commands. Effectively, the two commands would look like:

/usr/lib/sendmail –t [email protected] < /some/filemalicious_command < /path/to/file

The "malicious_command" could be virtually anything, ranging from additional mail commands thatmight send the malicious user system password and configuration files, to commands that providethe attacker with an interactive command prompt on the Web server.

Letting system shells evaluate arbitrary user input is clearly not a good idea.

Best Practices❏ Ideally, avoid using the shell at all. Depending on the task at hand, it may indeed be possible

to do so. For example, instead of using the system( ) call to invoke a shell, have the shellevaluate the $email_address variable and then invoke SENDMAIL. It is possible to invokeSENDMAIL directly from Perl, as follows:

open(SENDMAIL, "|/usr/lib/sendmail –t");open(FILE, "/path/to/file");print SENDMAIL "To: $email_address\n";@filedata = <FILE>;foreach $line (@filedata) {

print SENDMAIL $line;}

Note that this may not be a satisfactory solution, if the potentially malicious input is nowpassed directly to another program which may itself pose problems similar to a shellinterpreter.

When coding CGI applications, it is best to avoid any function that uses the command shell toevaluate input. When using Perl, these include certain invocations of system( ), as well asexec( ), and the so-called back ticks (``). When using C, these include function calls such asexeclp( ), popen( ), and system( ).

❏ If user input absolutely must be passed to a command shell for evaluation, it is imperative tofirst screen the input and only pass safe characters to the shell. The meaning of "safecharacters" varies with the application. However, safe characters usually refer to standardalphanumeric values (that is, a-z, A-Z, 0-9), as well as certain punctuation marks or specialsymbols that have no special meaning to the operating environment. Beware that manypunctuation marks have special meaning to UNIX operating systems, and can be used to starta command shell prompt or execute arbitrary commands.

The following Perl fragment1 is an example of a validation routine that only allows known validinput. Specifically, it checks to ensure that user-provided input has the syntax of a validInternet e-mail address:

$mail_to = &get_name_from_input; # read the address from formunless ($mail_to =~ /^[\w.+-]+\@[\w.+-]+$/) {die 'Address not in form [email protected]';}

1 Adapted from The World Wide Web Security FAQ, by Lincoln Stein,http://www.w3.org/Security/Faq/wwwsf4.html#Q37.

Page 50: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

45

In this code, characters that appear in a valid Internet e-mail address consist of one or morealphanumeric words (including the ., -, and _ characters), followed by the @ character,followed by one or more alphanumeric words.

❏ It is preferable to pass only known safe values to the shell, versus eliminating known badvalues. It is quite likely that bad values can be expressed in unanticipated ways (for example,in hexadecimal).

❏ As an additional precaution, configure network-level security controls, such as firewalls, torestrict inbound and outbound traffic to the smallest number of hosts, protocols, and ports aspossible. This way, even if a shell exploit is successful, network security controls may preventan attacker from ever seeing the successful results of his attack.

This underscores the importance of a layered approach to security. A layered approach helpsmitigate the risk that a single compromise of one layer does not lead to a full compromise ofthe entire application, system, or network.

Check All System Function Return Values

A potential source of system vulnerabilities can arise from CGI applications making system functioncalls and not checking the function return status to see if an error has occurred. The possibleconsequences of not checking for error conditions and handling errors appropriately are many. Anattacker may repeatedly call a CGI program to cause a Denial of Service (DoS) attack, exploit raceconditions2, cause programs to fail so that they reveal sensitive information, or cause programs todeadlock and grant access that might otherwise be denied.

Take, for example, the following sample of C code:

char* query_string = (char*) malloc(query_size);fread(query_string,query_size,1,stdin);query_string[query_size]='\0';

In this example, the malloc( ) system call is used to allocate memory. However, the return value ofthe malloc( ) system call is not checked to verify that it was actually possible to allocate therequested amount of memory. If insufficient memory is available, then subsequent operations uponquery_string could cause the program to crash, or provide a means for launching a buffer overflowattack (see below).

Best Practices❏ Check return values after calling all system functions, and handle any error conditions

appropriately. For the above example, an appropriate manner to handle an out-of-memorycondition might be to terminate the program gracefully, attempt to reuse previously allocatedmemory, or allocate as much memory as possible and truncate user input to fit the availablememory.

❏ The appropriate response to an error condition will vary by operation and error condition.

Protecting the Application from Its Environment, and Vice Versa

Many CGI applications rely upon the security of their underlying environment for much of their ownsecurity. However, assumptions cannot and should not be made about the overall security of theCGI applications environment. An environment that is as secure as it can possibly be today doesnot imply that it will be secure tomorrow.

System upgrades, unintentional modifications, and seemingly unrelated changes can have an impact

2 In security parlance, a "race" is an attempt by an intruder to rapidly guess and enter user credentialssuch as a password before a legitimate user finishes entering them.

Page 51: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

46

upon CGI applications. Attackers can also intentionally or unintentionally modify the environmentto negatively impact the secure operation of CGI programs by forcing them to run in an unexpectedmanner.

One classic technique for subverting systems is to alter the location where applications look forother dependent applications. Modifying the PATH statement of a CGI program’s executionenvironment is the typical method of doing this. When a program is run or otherwise referencedusing only its unqualified file name (for example, filename.exe), the PATH statement tells theoperating system which directories it should look in to find the program. On Windows-basedplatforms, the operating system will also always look in the current directory for the requested file.

Take, for example, a CGI program that sends e-mail notification messages to its user. To accomplishthis task, the CGI relies upon the following support library:

mapi32.dll

Mapi32.dll can normally be found in:

c:\winnt\system32

When run, the CGI program has the following PATH statement as part of its execution environment:

PATH=c:\winnt\system32;[other entries]

Because c:\winnt\system32 is defined as part of the CGI program’s PATH, referencing mapi32.dllcauses Windows to search the current directory, as well as all of the directories listed in the PATHstatement, in an attempt to find the support library. Under normal circumstances, Windows findsmapi32.dll in the c:\winnt\system32 directory and allows the CGI program to execute properly.

Imagine, however, if a malicious user exploited a weakness in the Web server or another applicationto create and place a copy of mapi32.dll in the CGI program’s current directory. Imagine furtherthat the directory, instead of sending mail, really provided the user with an interactive commandprompt on the Web server. In that case, the CGI program would not find its support library in thedesired c:\winnt\system32 directory, but would instead find it in its current directory. Invokingthe CGI program’s mail routine would cause the malicious user’s program code to execute on theWeb server, likely leading to a system compromise.

In brief, relying upon the server’s default environment to provide security is insufficient.

Best Practices❏ As a first course of business, remove CGI programs from all aspects of the execution

environment that they have inherited from the operating system, and replace them with theirown, trusted configuration. This is especially critical for any element in the environment uponwhich the CGI program is dependent, such as PATH statements, temporary directories, orapplication run-time environments.

❏ In addition, make all references to dependent program names, configuration files, and supportlibraries by fully qualified path name (in the above example, for instance,c:\winnt\system32\mapi32.dll). This will cause the CGI application to look in that one andonly location for the requested file.

❏ Other environment-specific considerations may also apply, such as defining the UNIX shellInternal Field Separator (IFS) variable that specifies what characters the shell uses to delimitfields (for example, new line, space, and tab).

Following these measures helps ensure that intentional or accidental modifications to theenvironment do not adversely affect the security of the CGI applications. In addition, they allowCGI-specific environment changes to be localized, and minimize the possibility of these CGI-specificchanges from having an adverse impact on other applications.

Page 52: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

47

It should be noted, however, that hard-coding PATH and similar items into an application has thepotential to create a maintenance headache. For example, the PATH statement would need to beupdated within the CGI program if an application it relies on were relocated to another directory.Awareness and planning can help minimize such an impact, however.

Verbose Error Messages

Verbose error messages can provide an attacker with additional information to compromise asystem. In addition to the system-critical error messages discussed in chapter 4, Transaction-LevelIssues, other less severe or application-specific error messages can also provide an attacker withuseful information.

One common source of information is error messages generated in response to user errors. Oftenthese error messages present clear, concise information to the user. Their aim is to help a usersolve a problem without having to call the support hotline or help desk. Unfortunately, andironically, these concise error messages may reveal too much information. This is particularly truein applications whereby a user needs to authenticate to the system but has not yet successfullydone so.

A real-world example of this is an error message generated in response to a failed login attempt. Inthis case, the user entered an invalid user ID:

You have entered an incorrect user ID. Please try again or contact customer support at 555-1212.

Note that the user was specifically told that she entered an invalid user ID.

Similarly, when the user enters a correct user ID but an incorrect password, this error message isgenerated:

You have entered an incorrect password. Please try again or contact customer support at 555-1222.

Again, the user was specifically told what is wrong. In this case, the user entered an invalidpassword.

Based upon these error messages, an attacker interested in guessing valid user IDs and passwordswould have a much clearer indication whether he guessed correctly.

Best Practices

❏ Do not provide overly verbose error messages customized to a specific error condition, suchas specifically telling users that they’ve entered an invalid user ID. A more secure practice isto provide a general error message that applies to a related class of error conditions.

Continuing with the failed login example, it would be better to first prompt the user for bothhis ID and password prior to generating an error message. Once an error message isgenerated, it should be only as specific as necessary, for example:

You have entered an incorrect user ID or password. Please try again or contact customersupport at 555-1222.

This error message is more generic. It indicates that the user has entered either an invaliduser ID or password, as opposed to stating specifically whether it was the user ID or passwordthat was entered incorrectly.

Legitimate users are not unduly inconvenienced by receiving less specific error information.However, such measures make it significantly harder for an attacker to guess a correct user IDand password combination.

Page 53: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

48

Memory Allocation and Buffer Overflows

While the following description of buffer overflows may sound esoteric, it is important to be awareof the significant security risk that buffer overflows can pose. According to a Defense AdvancedProjects Agency (DARPA)-funded research paper, buffer overflows are the most common form ofprogramming-related security vulnerability of the past 10 years.

Buffer overflows occur when a section of memory is overwritten that wasn’t meant to beoverwritten. This most commonly occurs in programming languages such as C and C++ where theprogrammer must explicitly allocate memory to hold user input. If the amount of data entered bythe user exceeds the memory allocated to hold that data, and the programmer doesn’t truncateinput to fit the allocated memory, a buffer overflow occurs. For CGI and other server-sideprograms, the buffer overflow occurs on the server.

The result of a buffer overflow varies based on the area of memory overwritten and the contentof the information that overflowed. At the very least, a buffer overflow can corrupt data inmemory, with a more usual result that the application accepting the user input terminatesabnormally, that is, crashes. The reason that the program abnormally terminates is that the Webserver attempts to execute once-valid program code that previously existed in the now-overwritten memory location. Since valid program code no longer exists in this location, an erroroccurs.

A malicious user, however, can overflow the buffer with carefully crafted program code thatreplaces the original program code. Since this replacement code is valid, though malicious, it toowill be executed by the Web server. Once a malicious user has the capability to execute hisprogram code on the Web server, it usually becomes a trivial task to circumvent other securitymeasures such as firewalls and Secure Socket Layer (SSL) encryption.

The following example3 shows a portion of a C program that is susceptible to buffer overflow:

static char query_string[1024];char* read_POST() {int query_size;query_size=atoi(getenv("CONTENT_LENGTH"));fread(query_string,query_size,1,stdin);return query_string;}

In the example the programmer has assumed, by allocating a static buffer of 1024 bytes, thatuser input would not exceed 10244 bytes of data. Should the user enter 1025 bytes or more ofdata, however, a buffer overflow occurs. This is a poor coding practice and should beavoided.

Best Practices❏ If static buffers are used, it is important to check that input does not exceed the amount of

allocated buffer space. In the event that input does exceed the amount of allocated bufferspace, then the input should be truncated, and/or error messages should be returned to theuser.

To illustrate, the following example builds off of the previous example. However, instead ofassuming that the length of user input does not exceed 1024 bytes, input longer than 1024bytes is truncated to 1024 bytes, the size of the static buffer. Note the need to terminate thetruncated string with a NULL (\0) byte:

3 Adapted from: The World Wide Web Security FAQ, by Lincoln Stein,http://www.w3.org/Security/Faq/wwwsf4.html#Q36.

4 1023 bytes of data plus a terminating NULL (‘\0’) string terminator. Under certain circumstances,entering exactly 1024 bytes of data could also lead to the program abnormally terminating, or to asystem compromise.

Page 54: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

49

#define MAXSTRINGSIZE 1024static char query_string[MAXSTRINGSIZE];char* read_POST() {int query_size;query_size=atoi(getenv("CONTENT_LENGTH"));if (query_size > MAXSTRINGSIZE) {

query_size = MAXSTRINGSIZE;query_string[query_size - 1]=‘\0’;

}fread(query_string,query_size,1,stdin);return query_string;}

❏ An alternate method of avoiding buffer overflows is to dynamically allocate memory toaccommodate whatever amount of input a user provides. While this avoids buffer overflowsin the CGI program, it can lead to other undesirable effects, such as causing buffer overflowsin other dependent programs, or contributing to a resource exhaustion attack like consumingall available memory or filling up log files.

The following example5 illustrates dynamic memory allocation. Note the need to terminate thestring with a NULL (\0) byte:

char* read_POST() {int query_size=atoi(getenv("CONTENT_LENGTH"));char* query_string = \(char*) malloc(query_size + 1);if (query_string != NULL) {fread(query_string,query_size,1,stdin);query_string[query_size]='\0';}return query_string;}

❏ When coding CGI applications, avoid any function call that blindly and without limit copiesone buffer to another, as this can easily and unintentionally introduce buffer overflowsinternal to the CGI programs. C functions to avoid include strcpy( ), strcat( ), puts( ),fputs( ), and other similar functions. Instead, use functions that do support buffer lengthlimits such as strncat( ) and strncpy( ).

External Application Dependencies and Messages of Arbitrary Length

As indicated above, CGI applications may depend on other applications, such as mail programs, databaseaccess routines, or system logging functions. Much as malformed user input can lead to systemcompromise, even "cleansed" output that comes directly from your CGI applications and is fed into adependent application can cause buffer overflows, Denial of Service (DoS) attacks, or system compromise.

Recent audits of common applications have revealed such deficiencies. One such example is thepassing of arbitrarily long log messages to a system logging facility that is not capable of handling suchlong messages. The following example shows how this deficiency might manifest itself in C source code:

char *log_message="Really, really long message here...";syslog (priority, log_message);

Even though the CGI program may be able to assemble log entries each of an unlimited length, thesystem logging facility may only be able to log messages up to 1K in length. Passing a 2K logmessage could cause a buffer overflow.

5 The World Wide Web Security FAQ, by Lincoln Stein,http://www.w3.org/Security/Faq/wwwsf4.html#Q36.

Page 55: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

50

Buffer overflows are not the only possible result of passing arbitrarily long data to dependentapplications. Other impacts include filling up available log file disk space, causing applications toblock (that is, hang while processing input), or even system crashes.

Best Practices❏ Pay particular care when providing input to dependent applications so as not to exceed the

amount of data that they can successfully handle. To follow up on the above system logexample, a correct implementation could include a limitation on the amount of data that isactually passed to the system logging facility:

char *log_message="Really, really long message here...";syslog (priority, "%.250s", log_message);

In this example, a format string (that is, "%.250s") limits the amount of data passed to thesystem logging facility to a maximum of 250 characters.

❏ In cases where the full, arbitrary length of a message is needed, it may be necessary to breakthe large message into smaller units, and to send several small messages to the system loggingfacility or other dependent application.

Page 56: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

51

Server-Side Coding Best Practices❏ Compartmentalize applications.

❏ Run each application with the absolute minimum set of privileges.

❏ Validate and reformat all user input.

❏ Avoid passing user input directly to a command shell. If user input must be passed to acommand shell, screen the input and only pass safe characters to the shell.

❏ Configure network-level security controls, such as firewalls, to restrict inbound and outboundtraffic to the smallest number of hosts, protocols, and ports.

❏ Check return values after calling all system functions, and handle any error conditionsappropriately.

❏ Remove from CGI programs all aspects of the execution environment inherited from theoperating system.

❏ Make all references to dependent program names, configuration files, and support libraries byfully qualified path name.

❏ Do not provide overly wordy error messages customized to specific error conditions.

❏ Check that input does not exceed the amount of allocated buffer space. As an alternate,dynamically allocate memory to accommodate whatever amount of input a user provides.Further, avoid any function call that blindly and without limit copies one buffer to another.

❏ Take care to provide input to dependent applications that does not exceed data handlinglimits.

Page 57: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Server-Side Coding Techniques

52

Additional ResourcesThere are many excellent secure programming resources on the Web. Some of these resourcesapply generally to a given programming language, some are specific to CGI programming, whileothers apply to vendor-specific products.

A few of the resources available are:

http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txtSafe CGI Programming, by Paul Phillips

http://www.perl.com/pub/doc/FAQs/cgi/perl-cgi-faq.html#Q5.1Perl CGI Programming, by Shishir Gundavaram and Tom Christiansen

http://phrack.infonexus.com/search.phtml?view&article=p49-8CGI Security Holes, by Gregory Gilliss

http://www.rstcorp.com/its4/ITS4: An Open Source Software Security Tool for C and C++, Reliable Software Technologies

http://stars.com/Authoring/Scripting/SecuritySecurity Issues When Installing and Customizing Pre-Built Web Scripts, by Selena Sol

http://www.w3.org/Security/Faq/www-security-faq.htmlThe World Wide Web Security FAQ, by Lincoln Stein

Page 58: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

53

All but the simplest Web applications use databases in one form or another, makingdatabases a critical foundation of most e-Business systems. The roles of databases are many,including storing system configuration parameters and credentials, raw content for use indynamic page generation, and customer data such as shipping addresses and credit cardnumbers.

For some applications, the database may consist of a flat file, a hierarchical directory structure, oran unmanaged database structure such as Microsoft Access or UNIX DBM. More sophisticatedapplications typically employ a Relational Database Management System (RDBMS), such as InformixDynamic Server, Microsoft SQL Server, or Oracle 8 i.

Regardless of the specific product or application, the security and integrity of the datacontained within the database is of great concern -- or it should be if it isn’t already. After all,this information keeps an e-Business running. Unauthorized modification of even a singlepiece of information within a database could lead to bad publicity, lawsuits, or a shutteredbusiness.

Despite the critical system, business, and customer information typically contained withindatabases, both first-hand experience and recent media coverage of compromised Web sitesindicate that databases are at risk due to insufficient security measures.

This chapter discusses the following broad areas of database security:

Database Security6CGIASP

Servlet

Logic

User I

/O

DB I/O

Session Tracking

Log On Log Off

Database

User

Web Application

Network Security

Web Server Configuration

OS Configuration

Page 59: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

54

• Database servers• Databases • Encryption and performance• Disaster recovery

Page 60: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

55

Protecting Your Database ServerA critical aspect of maintaining the security and integrity of the data within a database is the overallsecurity of the system and network that run the database server. An attacker that gains access tothe operating system or physical server that a database runs on can gain full access to all of thedata1 contained within that database, regardless of the access controls enforced by applications orthe database itself.

This section identifies some common vulnerabilities that can lead to compromise of the databaseserver, and steps to mitigate these vulnerabilities. This section is by no means exhaustive, butillustrative.

The following topics are discussed:

• Disable Unnecessary Network Services• Physically Separate Web and Database Servers• Address Platform and Vendor Security Vulnerabilities• Correct File and Device Permissions

Disable Unnecessary Network Services

Database software, like most operating systems and complex applications, provides a number ofservices that allow for remote system management, distributed processing, and other network-related functions. In many cases, these services are enabled by default and are often "protected" byusing either no password or a default password. These services can provide attractive targets foran attacker, potentially allowing easy access to the system and database.

Best Practices❏ Disable unnecessary services to block an attacker from using them as an entry point into the

system. For required services, restrict access through filtering mechanisms, such as firewallsand routers, as described below.

Physically Separate Web and Database Servers

Many Web sites place all of their servers, including Web, application, and database servers, behinda single, dual-interface firewall or choke router. While this prevents, with appropriate configuration,Internet traffic from reaching your database servers, it does not stop a malicious user attackingyour database server from your Web server. Should any single server be compromised, it can beused to subject the other servers to a full barrage of attacks.

Best Practices❏ Isolate database servers, particularly those containing sensitive information, from the Web

site’s De-Militarized Zone (DMZ). Locate them on a network segment physically separate fromthe Web servers that support your e-Business. Ideally, partition off the database server fromthe Web servers by a dedicated firewall. This firewall, illustrated in Figure 6-1, should onlyallow database traffic between the Web server and database server. Deny and log all trafficfrom any other location, or all other types of traffic from the Web server such as Telnet.

Separating the database server from the rest of the servers in the DMZ adds another layer ofprotection to your database, and protects your database from a full attack should your outerfirewall be compromised. More importantly, this separation protects your database serverfrom an all-out attack from your Web server, should your Web server be compromised. In thiscase, the second firewall would ensure that your database could only be attacked by using itsnative database protocols.

1 Encrypted data stored within the database may be an exception if a strong encryption algorithm isused, and the attacker is not able to locate, guess, or brute force the encryption keys.

Page 61: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

56

Granted, exploiting weaknesses in the database communication protocols can still lead to asystem compromise. However, this firewall can prevent non-database protocol attacks fromreaching your database. Appropriately configured, the firewall can also provide protectionfrom attacks that target deficiencies in your system’s TCP/IP network stack, such as thosebased on IP fragment reassembly, malformed packets, or invalid option flags. Without thisfirewall, your database server could be assaulted using any and every attack known to thehacker community.

❏ In cases where it is not possible to place a dedicated firewall between the Web and databaseservers, it is still possible to receive some of the same benefit by implementing firewall-likefilters directly on the database server. For UNIX servers, you may be able to use IP Chains2,IP Filters3, or TCP Wrappers4. For Windows NT or Windows 2000 servers, the filteringcapability within the Network Connections "TCP/IP Security" configuration screen can beused.

Although the preceding information refers to distributed systems, the same principles can beapplied to e-Businesses deployed on a trusted operating system, such as Hewlett-Packard’sVirtual Vault.

Address Platform and Vendor Security Vulnerabilities

Invariably, applications and operating systems have vulnerabilities that can lead tounauthorized data access, loss of integrity, or total compromise of the system and itsinformation. Databases and database servers are no exception, and also suffer fromvulnerabilities. Some vulnerabilities can be exploited by any user who can establish a networkconnection with the database service, while others require the attacker to first gain access to aserver command prompt.

Several versions of Oracle 8 for UNIX, for example, include an incorrect permission setting on the$ORACLE_HOME/bin/oratclsh TCL command interpreter used in conjunction with the IntelligentAgent option. This incorrect setting easily allows any attacker able to open a command shell -- evenoperating with unprivileged guest access -- to gain root or administrative access to the entiresystem. Once an attacker gains administrative access to a database server, he can gain full accessto all of the data. A defense against this threat is to use a strong encryption algorithm and encryptsensitive data stored within the database.

Specifically, the oratclsh command interpreter is owned by the root user, and has the setuid bit set.In UNIX, the setuid bit indicates that a program always runs with the permissions of the program’sowner, regardless of who actually runs the program. Once run, the oratclsh command shell givesthe attacker a command prompt with an effective user ID (euid) equal to that of the root user. Thisis illustrated in the example below, where the id command shows the user’s actual and effectiveuser ID before and after running the oratclsh script:

InternetWeb Server

Database Server

FirewallFirewall Firewall

Firewall allows only Web-specifictraffic from the Internet to theWeb server.

Firewall allows only database-specific traffic from the Webserver to the database server.

Figure 6-1: Logical Depiction of Physically Separate Web and Database Servers

2 IP Chains, by Rusty Russell, et al., http://www.samba.org/netfilter/ipchains

3 IP Filter, by Darren Reed, http://coombs.anu.edu.au/~avalon/ip-filter.html

4 TCP Wrappers, by Wietse Venema, ftp://ftp.porcupine.org/pub/security/index.html

Page 62: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

57

$ iduid=1000(metases) gid=100(users)$./oratclsh% iduid=1000(metases) gid=100(users) euid=0(root)

Other vulnerabilities can be exploited directly over the network, eliminating the need for anattacker to first gain access to an account local to the database server. One such vulnerability thatis particularly devastating is the Remote Data Services (RDS) bug contained within certain versionsof Microsoft’s Active Data Objects (ADO) architecture. This bug has led to the compromise of manyWeb servers and their supporting databases, reportedly including that of Microsoft and US federalagencies.

Best Practices❏ An important step in minimizing the impact of vulnerabilities is to keep your products and

systems up-to-date with security patches released by vendors. As we have seen time and timeagain, security patches on production systems are often not kept up-to-date. Microsoft’s RDSbug, for example, was still being actively exploited more than one year after it was discoveredand fixes to it were posted.

❏ Despite the best efforts of vendors to stay current with vendor-provided security patches,vulnerabilities are often exploited for days, weeks, or, in some cases, even years beforevendors release fixes. To protect against these situations, a layered security model providesyour best, interim defense. Erecting multiple layers of defense, such as strong session IDs,compartmentalizing your network, and encryption, can deter all but the most determinedattacker if implemented appropriately.

Correct File and Device Permissions

Incorrect file permissions can lead to loss of confidentiality, loss of data integrity, or, as illustratedwith the Oracle oratclsh example above, complete system compromise. The number of examples ofthe damage that incorrect file and device permissions can cause is limitless. They include overlyliberal permission settings on a device that can undermine the security of an entire file system ordatabase, and inappropriate permissions on Windows NT systems that allow backup copies of theSecurity Account Manager (SAM) password database to be read by everyone.

Best Practices❏ To protect against attacks that leverage inappropriate file permissions, the database or

system administrator should investigate the nature of all critical files supplied with, or reliedupon by, the database. In addition, database applications should be run under the principle ofleast privilege, as described in chapter 5, Secure Server-Side Coding Techniques.

Page 63: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

58

DatabasesDatabases, particularly RDBMS’s, can be very complicated systems, adding to the overallcomplexity of Web applications. At times, simply getting Web applications to reliably communicatewith an RDBMS and to return expected results can be a challenge. In part because of thiscomplexity, often combined with the unfamiliarity of developers or security practitioners with adatabase, database security precautions are often inadequate.

This section outlines the following major database-related threats:

• Permissions and Access Controls• Restriction of Data Access Through Database Views• Stored Procedures• Encrypted Communication Between Servers• Database Encryption• Performance Impact of Encryption• Disaster Recovery

Permissions and Access Controls

Without the ability to selectively grant and restrict access to a database and its data, any arbitraryuser can add and delete information at will. Even if access controls are enforced by Webapplications, data contained within the database is still at risk if a malicious user circumvents theWeb applications and accesses the database directly.

Unfortunately, it is quite common for Web application developers to place all access controls withinthe application itself, and leave the underlying database exposed to modification. This practice istypically reflected in the use of a generic application user ID that has full rein over the databasetables and, in some cases, the entire database.

If such a generic user ID had full control over a database and its contents, a malicious user couldcircumvent the Web application and execute this SQL database command:

DROP DATABASE WEBDB;

This one simple command would erase the complete contents of the WEBDB database. Unlesscurrent backups were available, all data would be lost.

Best Practices❏ To mitigate the risks presented by all-powerful, generic database IDs, most databases support

some form of access controls that restrict what users, groups of users, or applications canaccess or change in the data. In their simplest form, database access controls may leveragethe underlying operating system’s file permission capabilities.

More sophisticated databases, such as an RDBMS, provide multiple layers of access controlsas described in the next few sections. Generally speaking, RDBMS access controls arecentered on a user’s ability to perform four main functions: Delete, Insert, Update, and Select.These permissions can be applied to database objects for relatively fine-grained accesscontrol, and minimize or eliminate the need to rely upon the Web application for accesscontrol enforcement.

Database authentication and access controls can restrict database access based on user nameand password or other credentials such as digital certificates. The Web application server canbe given a specific database account that has restrictions (for example, read-only access) onthe functions it can perform on the database and the data it contains. The databaseadministrator or application developer specifies which permissions are granted. For anRDBMS, these permissions are granted on a per-user or per-group basis using the GRANT andREVOKE commands.

Page 64: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

59

Restriction of Data Access Through Database Views

Databases that support e-Business applications often contain a significant amount of sensitiveinformation. This data may include customer or business partner personal information, orderhistories, stock information, etc. Despite the vast amount of information contained within adatabase, very rarely does anyone within an e-Business require full access to all of it. Instead,different internal groups may require access to different subsets of the information. For example, adepartment manager may require most customer order information, while a customer servicerepresentative may only require information on the specific products purchased by customers.

The following example illustrates a query that might be run against a database from a Webapplication. In the example, the application directly queries the database for the user and enforceswhat the user can and cannot see, based upon the columns in the query and the restrictive WHEREclause.

SELECT PRODUCT_ID, QUANTITY, PRICEFROM ORDERSWHERE PRODUCT_CLASS="BOOKS";

The above query selects only three columns from a much larger table called ORDERS that containsfull details on customer orders. In addition, the query restricts the data returned to only includerecords with a product class of BOOKS.

Since the application itself enforces what the user can and cannot see, it is possible for a malicioususer to see more data than permitted if he can circumvent the application restrictions. Dependingon the access restrictions placed upon the individual columns in the ORDERS table, it isconceivable that a malicious user could access the full contents of the table by executing thisquery:

SELECT *FROM ORDERS;

Even if the database enforces column restrictions by using the access controls described above, themalicious user can still see data across all product classes, as table-level access controls cannot beapplied on a row-by-row basis. Depending upon the application, this could provide the malicioususer with a considerable amount of sensitive information.

Best Practices -- Restriction of Data Access Through Database Views

A view is a virtual database object derived from a query against one or more database tables. A view itself containsno data, but can be thought of as a window into a subset of rows and/or columns from the underlying tables that itrepresents. Figure 6-2 illustrates the logical representation of a view. Users only have access to the data allowed bya view; the rest of the data is neither visible nor accessible.

Views are generally best suited to enforcing read-only access controls for the underlying data that is represented.(Some databases, however, such as Informix Dynamic Server, also support modification to the underlying data undercertain circumstances.)

Most databases provide the ability to define a different set of access privileges to a view than the underlying tables.By creating views and assigning user permissions to those views but not to the underlying tables, you can restrictaccess to selected columns and rows.

To illustrate, two views are created in the following example, both of which draw their information from a tablecalled ORDERS. The first view allows customer service representatives to see specific information related tocustomer orders, including who the customer is. The second view allows employees in the publications departmentto track book sales, but does not provide customer-specific information.

CREATE VIEW ORDER_INFO ASSELECT ORDER_ID, CUSTOMER_ID, ORDER_ITEM,

Page 65: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

60

PRODUCT_ID, QUANTITY, PRICEFROM ORDERS;

GRANT SELECTON ORDER_INFOTO CUSTOMER_SERVICE;

CREATE VIEW BOOKS ASSELECT PRODUCT_ID, QUANTITY, PRICEFROM ORDERS

WHERE PRODUCT_CLASS="BOOKS";

GRANT SELECTON BOOKSTO PUBLICATIONS_DEPT;

Since access can be granted to views independent of the underlying ORDERS table, robust security can be enforced.In addition, because views are actual database objects, a malicious user in the publications department, for example,cannot circumvent the restrictions enforced by the view to gain access to the underlying customer information, or toproduct classes other than books. Compare this to the relative insecurity of the application-enforced queryrestrictions described in the second example at the start of this section.

It should be noted that the preceding examples offer a very simplistic description of the capabilities of views. Viewscan make use of many powerful capabilities of SQL, including inner, outer, and equijoins of tables, as well asaggregated data and computed fields.

PRODUCT_ID

QUANTITY PRICE

PRODUCT_ID

PRODUCT_CLASS

PRODUCT_AD_CODE

ORDER_ID CUSTOMER_ID

ORDER_ITEM

QUANTITY PRICE DISCOUNT

Books View

Orders Table

Contains only records where PRODUCT_CLASS="BOOKS"

Figure 6-2: An Example of a View

Page 66: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

61

Best Practices – Stored Procedures

A stored procedure is a compiled program, consisting of one or more statements, that is executed directly by thedatabase engine and saved in the database. The statements within a stored procedure may be SQL statements orcontrol flow statements such as IF-THEN or loop statements. Stored procedures may be run either locally from agiven system, or executed remotely across a network.

In addition to performing database operations, stored procedure programming languages typically provide forevaluating conditional and mathematical expressions, as well as performing string operations. Prior to being executedby the database server, stored procedures are typically compiled to optimize execution speed.

Whereas views are best suited for enforcing read-only access controls, stored procedures work well for applicationswhere information must be deleted, inserted, or updated. Like views, most databases provide the ability to define adifferent set of access privileges to a stored procedure than the underlying tables. By creating stored procedures andgranting users permission to execute those procedures, while at the same time denying all permissions to theunderlying tables, it is feasible to safely perform sensitive operations.

It is possible to convert update and delete procedures as in the example above into parameterized storedprocedures that accept very specific user input, internally validate that input, and then execute one or more SQLstatements as defined in the procedure. For example:

execute UPDATE_E-MAIL(12345, ‘[email protected]’);

execute DELETE_CUSTOMER(12345);

In such examples, if the input is not valid, and for example contains other embedded SQL statements, wildcardcharacters, or too few parameters, either the procedure itself or the database engine halts execution of theprocedure and returns an error message to the user.

Since the required database information, including table and column names, is encapsulated in the storedprocedures, a malicious user is not able to modify a query and submit it to the database for execution. In addition,since the user only needs to have permission to execute the stored procedure and does not require permission to

Stored Procedures

Database views provide a robust mechanism for enforcing read-only access controls, but fall farshort in deleting, inserting, or updating information. When performing these operations, viewsoften provide very little additional protection against conducting operations against the actualunderlying table itself. Granted, potential damage is limited to the records represented by the view,but the amount of damage can still be great.

Take for example the following two SQL statements. The first statement changes a customer’s e-mail address in either a table or view called CUSTOMER_INFO. The second statement deletes acustomer’s information in the same CUSTOMER_INFO table or view. In each case, the only recordsupdated or deleted are those containing a customer ID equal to 12345.

UPDATE CUSTOMER_INFOSET E-MAIL="[email protected]"WHERE CUSTOMER_ID=12345;

DELETE *FROM CUSTOMER_INFOWHERE CUSTOMER_ID=12345;

Imagine, however, what would happen if a malicious user eliminated the WHERE CUSTOMER_ID=12345clause, and executed the remainder of these statements against the database. In the first case, the e-mailaddress for all customers represented by the table or view would be updated to [email protected] the second case, all customer information represented by the table or view would be deleted.

Page 67: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

62

Encrypted Communication Between Servers

In much the same way that intercepting and potentially altering sensitive communications betweenWeb browsers and Web servers is a concern, intercepting and altering the communication betweenWeb application servers and database servers may also be an issue. Depending upon the nature ofthe e-Business, intercepting server-to-server communication may pose an even greater risk thancapturing a database access password. For example, the integrity of the data in transit could becompromised through virtually untraceable, and perhaps seemingly random, on-the-fly modifications.

This concern may be heightened in cases where the server-to-server communication occurs acrossan untrusted network such as an organization’s Demilitarized Zone (DMZ) or the Internet itself.

Best Practices❏ Use basic network security principles to secure the path that data is travelling. This is an

important first step. For example, the use of a switched network, network compartmentalization,and physical security for the network equipment helps reduce the opportunities for eavesdropping.(However, these measures are not sufficient to protect data that traverses untrusted networks.)

❏ Similar to the use of Secure Sockets Layer (SSL) encryption to protect data transmittedbetween Web browsers and Web servers, employ encryption between Web application serversand database servers. Depending upon your network architecture and the products deployedat your site, server-to-server encryption can encrypt all data transmitted using a mechanismsuch as IPSec, or only encrypt database-specific data using encryption-enabled databaseprotocols. Oracle SQL*Net V2.0 and Net8, for example, support data encryption betweensystems. In addition, freely available tools like stunnel can be used to provide SSL encryptionand authentication to otherwise insecure protocols.

Database Encryption

Even with all the above mitigation strategies, it is still possible that an attacker could access thecontents of your database, particularly if the attack originates from the inside and not over theInternet. Methods for gaining such access include exploiting misconfigured security perimeters,impersonating a janitor and sitting down in front of the actual database server computer, orsalvaging an inappropriately disposed hard drive or backup tape. These examples are by no meansall-inclusive, but hopefully illustrate the point that even the most stringent network safeguards,including the use of firewalls and SSL, are insufficient to stop a determined cracker.

Virtually all e-Businesses store sensitive or confidential information, such as passwords, credit cardnumbers and, perhaps, competitive information, in the databases that support their Web applications. Forsuch organizations, the risk of data theft is very real, as demonstrated by the November 1999 compromiseof CD Universe’s customer database. This compromise was reported to have divulged sensitive customerinformation, including credit card numbers, for over 300,000 customers. Once compromised, these creditcard numbers were then freely given out or sold to make fraudulent purchases.

operate on the underlying tables, data within the underlying table can be protected.

Stored procedures can be far more complicated than a single SQL statement and accompanying input validation. Infact, a single stored procedure can encapsulate the execution of dozens of individual SQL calls. This could, forexample, allow a parameterized stored procedure call to populate the dozen tables required to create a newaccount at an e-Commerce Web site.

In addition to their security benefits, stored procedures can also lead to enhanced application and databaseperformance. These performance enhancements occur through a stored procedure’s ability to encapsulate multiplefunctions in one parameterized call, potentially saving dozens of back-and-forth communications between the Webapplication and database servers. Further, the pre-compiled nature of stored procedures eliminates the need toevaluate each SQL statement contained within the procedure at runtime.

5 http://mike.daewoo.com.pl/computer/stunnel

Page 68: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

63

Best Practices❏ Encrypt sensitive – if not all – data that is stored within the database. The is the only way to

protect fully sensitive information from the compromise of sensitive information on Webapplication databases. Encrypting the data using a strong encryption algorithm such as 3DES,Blowfish, or RC4, combined with a strong key, makes it virtually impossible that an attackercan access the encrypted data without knowing the encryption key. For a proven symmetricencryption algorithm such as these, a key of at least 112-bit strength is recommended.

❏ Avoid using a single key to encrypt the data contained within the database, particularly if thatkey must be embedded within the Web application to retrieve the encrypted information. Ifyour application can access that key, it is a sure bet that a determined attacker can also locateand use that single key. Ideally, a unique key protects each customer’s sensitive informationor a single set of related information, thereby minimizing the damage that can be done shouldan attacker guess or brute force a single encryption key. Guessing one key should reveal onlyone customer’s information or related set of information. Note, however, that someapproaches to using individual keys may raise significant key management issues. Such issuesneed to be thoroughly evaluated and understood prior to implementation. Having acryptographic expert help design or verify your cryptographic and key management plans isalso recommended.

Traditionally, encryption of database information had to be performed external to thedatabase using encryption algorithms and libraries obtained from third parties. (Somealgorithms, such as Blowfish, are free for commercial use, while others such as RC4 have to belicensed from their providers.) Recently, database vendors such as Oracle have bundledcryptographic algorithms into their products to make for "one stop shopping." Oracle 8irelease 2, for example, includes a package called the DBMS_OBFUSCATION_TOOLKIT thatprovides symmetric cryptography services.

Performance Impact of Encryption

Despite its benefits, encryption does exact a performance penalty against e-Business applicationsand servers. This performance penalty increases with the amount, type, and strength of encryptionperformed. Generally speaking, asymmetric, public key encryption has a greater performanceimpact than symmetric encryption. Further, stronger keys -- that is, more bits -- for a given type ofencryption have a greater performance impact than smaller keys.

Striking the proper balance between acceptable performance and acceptable security can be tricky.Unfortunately, offering blanket guidance on the appropriate balance isn’t possible because thatbalance must be evaluated case by case.

Best Practices❏ Data can typically be encrypted at multiple layers, for example, at both the transport layer for

all communications between the Web and database servers, and at the application layer forselected pieces of sensitive information. Depending upon your application and networkinfrastructure, it may not be necessary to encrypt at both layers. Instead, it may be sufficientto strongly authenticate the Web server to the database server, and then perform an integritycheck on all transmitted data to ensure that it has not been altered in transit.

❏ When encrypting at the transport layer, minimize the amount of data that is transmitted orreceived to lessen the performance impact of encryption. The amount of data that must beencrypted is reduced. Two common methods of reducing data transmission are compressionand stored procedures. Compression, unfortunately, can have a negative performance impactof its own. Using stored procedures, however, can speed overall application performance asdiscussed above in the section Stored Procedures.

❏ Another method for minimizing the impact of encryption is to offload the encryption process tospecialized hardware that is optimized for performing the complex mathematical computationsthat support various cryptographic algorithms. Several vendors make hardware-basedcryptographic accelerators, including Intel, nCipher, and Rainbow Technologies.

Page 69: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

64

❏ Finally, it may be acceptable to have back-end communications without encryption if thenetwork infrastructure has adequate network-level security to ensure the infrastructure’sintegrity.

Disaster Recovery

Given the critical nature of e-Business databases, disaster recovery is critical to ensure data isavailable in the event of component or system failure, natural disaster, or attacks designed todestroy information.

Numerous techniques mitigate the risk of data loss. These techniques include redundant storage,transaction and database backups, and geographically dispersed fail-over locations. The mitigationtechniques appropriate for your data depend upon your specific situation. These techniques arenot mutually exclusive.

Best Practices❏ Place multiple copies of your live data on disk in redundant storage. This makes the data

immediately and transparently accessible to the database server should a disk failure occur.In the event of a disk failure, data can still be accessed using a redundant copy of the data, orreconstructed on the fly through the use of parity information stored on disk in conjunctionwith the actual data. In this case, data is typically stored on a Redundant Array of InexpensiveDisks (RAID).

A common method is to install the database software and related data files on a separate diskpartition or separate disk, which is replicated to provide redundancy. This eliminates the riskof "putting all your eggs in one basket."

This method protects the database partition or drive from attacks launched against thepartition containing the operating system (OS) Attacks include attempts to fill up the diskspace by appending data to the system’s log files.

Another aspect of the database file location is the relative location of the files and theiraccessibility by users. Maintain the database files in a directory separate from any othersoftware, and restricted to administrators through OS-level access controls.

❏ Database backups can restore a database to the state it was in at the time of backup. Anytransactions executed since the last backup would typically be lost. To prevent this loss,transaction logs can also be backed up and later replayed, that is, restored, once the primarydatabase backup is restored. It is not uncommon for copies of critical data to be stored off-site in a secure facility to mitigate the risk of a disaster to your database and to other servers.

❏ Geographically dispersed fail-over locations provide for protection against all but the mostcatastrophic disasters. They allow, for example, the primary database server to be located inNew York, and a backup database server in Arizona. In the event the database server in NewYork goes down, the server located in Arizona takes over. Distributed database replicationtechnologies allow both servers to maintain an up-to-date view of all data prior to the failureof the primary server, and then re-synchronize once the primary server is back online.

Page 70: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

65

Database Security Best Practices❏ Disable unnecessary services.

❏ Erect multiple layers of defense.

❏ Deploy network-level access controls to permit only the Web or application servers to accessdatabase servers. In addition, restrict access to the specific protocol(s) needed to supportdatabase communication.

❏ Physically separate database servers from other servers in the DMZ, and restrict access to thedatabase server using a firewall or similar mechanism.

❏ Install security patches.

❏ Use database access controls, such as user accounts, to restrict access.

❏ Use minimum privileges for database accounts, for example, read-only, whenever possible.

❏ Double-check file permissions on executable database files.

❏ Use database stored procedures and views to enforce access control.

❏ Filter all user input before passing it to the database.

❏ Configure the database system to log administrative transactions such as logon failures andmaintenance transactions, especially those that add, delete, or modify content. Review thelogs periodically for suspicious activity.

❏ Use server- and database-level encryption.

❏ Use multiple keys to encrypt data.

❏ Minimize the effect of encryption on performance through techniques such as reducing theamount of encrypted data and offloading the encryption process to specialized hardware.

❏ Configure the database server to eliminate or restrict access to database-related networkservices.

❏ Implement a disaster recovery plan appropriate for your database.

Page 71: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

66

Additional ResourcesApplied Cryptography, by Bruce Schneier, ISBN #0471117099.

SQL: The Complete Reference, by James Groff and Paul Weinberg, ISBN #0072118458.

Page 72: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Database Security

67

ConclusionThis report has outlined many of the application security vulnerabilities that exist in businesssystems, as well as steps to mitigate them. It is hoped that application developers and securitypersonnel can use the report to make security – the "weakest link in the organizational chain." –considerably stronger. Updates to this report will discuss new issues in this rapidly changing field,and provide more detail on assorted Web/e-Commerce development environments.

Page 73: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

68

This appendix contains links to some relevant sites on building secure Web applications

There are many excellent secure programming resources available on the Web. Some of theseresources apply generally to a given programming language, some are specific to CGI programming,while yet others apply to vendor-specific products.

Web Siteshttp://coombs.anu.edu.au/~avalon/ip-filter.htmlIP Filter, by Darren Reed

ftp://ftp.porcupine.org/pub/security/index.htmlTCP Wrappers, by Wietse Venema

http://mike.daewoo.com.pl/computer/stunnel

http://phrack.infonexus.com/search.phtml?view&article=p49-8CGI Security Holes, by Gregory Gilliss

http://stars.com/Authoring/Scripting/SecuritySecurity Issues When Installing and Customizing Pre-Built Web Scripts, by Selena Sol

http://www.cs.princeton.edu/sip/pub/spoofing.htmlWeb Spoofing: An Internet Con Game

http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txtSafe CGI Programming, by Paul Phillips

http://www.perl.com/pub/doc/FAQs/cgi/perl-cgi-faq.html#Q5.1PERL CGI Programming, by Shishir Gundavaram and Tom Christiansen

http://www.samba.org/netfilter/ipchainsIP Chains, by Rusty Russell, et al.

http://www.w3.org/Security/Faq/www-security-faq.htmlThe World Wide Web Security FAQ, by Lincoln Stein

Appendix:Useful Links

and Reference Material

Page 74: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Useful Links and Reference Material

69

BooksApplied Cryptography, by Bruce Schneier, ISBN #0471117099.

SQL: The Complete Reference, by James Groff and Paul Weinberg, ISBN #0072118458.

Page 75: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

70

Access Controls ................................................................................................................................................58Attack

Example of an e-Commerce..........................................................................................................................6Audience ..............................................................................................................................................................3Authentication ....................................................................................................................................................9

Basic ..............................................................................................................................................................12Digital certificates........................................................................................................................................10Form-Based authentication ........................................................................................................................11

Authentication and logon best practices......................................................................................................19Authentication threats and attacks ...............................................................................................................16

Brute-force access attempts ......................................................................................................................16Brute-force lockouts....................................................................................................................................16Concurrency .................................................................................................................................................17Multiple authentication disorder...............................................................................................................17Resource exhaustion...................................................................................................................................18User name harvesting .................................................................................................................................17

Basic authentication ........................................................................................................................................12http ................................................................................................................................................................13

Books ...........................................................................................................................................................66, 69Browser caching ...............................................................................................................................................37Brute-Force access attempts ..........................................................................................................................16Brute-Force lockouts........................................................................................................................................16Buffer overflows ...............................................................................................................................................48Business to Business (B2B) ..............................................................................................................................1Business to Consumer (B2C) ............................................................................................................................2Cached data remains after logout..................................................................................................................29Cached logout pages........................................................................................................................................28Challenge of e-Commerce application security..............................................................................................5Client-side filtering ...........................................................................................................................................33Commercial Off the Shelf (COTS) products..................................................................................................38Common Gateway Interface (CGI)..................................................................................................................40Compartmentalization .....................................................................................................................................42Conclusion.........................................................................................................................................................67Concurrency......................................................................................................................................................17Consumer to Consumer (C2C)..........................................................................................................................2Cookies...............................................................................................................................................................24Database best practices ..................................................................................................................................65Database encryption........................................................................................................................................62Database security.............................................................................................................................................53

Database server ...........................................................................................................................................55

Index

Page 76: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Index

71

Database server................................................................................................................................................55Databases ..........................................................................................................................................................58Device permissions ..........................................................................................................................................57Digital certificates ............................................................................................................................................10Disable Unnecessary Network Services....................................................................................................... 55Disaster recovery .............................................................................................................................................64Disclosure of client data..................................................................................................................................36Downloaded files ..............................................................................................................................................37Eavesdropping ..................................................................................................................................................36Encryption...................................................................................................................................................62, 63Environment......................................................................................................................................................45Exploits ................................................................................................................................................................6External application dependencies................................................................................................................49File permissions................................................................................................................................................57Form-Based authentication.............................................................................................................................11GET .....................................................................................................................................................................34Goals.....................................................................................................................................................................5Hidden form elements .....................................................................................................................................23Hypertext Transfer Protocol (HTTP)

Session Ids ....................................................................................................................................................20Improper application flow...............................................................................................................................35Intranet Web Site ................................................................................................................................................1IP addresses ......................................................................................................................................................25IP hopping .........................................................................................................................................................26Introduction ........................................................................................................................................................1Least privilege...................................................................................................................................................42Links .............................................................................................................................................................52, 68Logon....................................................................................................................................................................9Logon and authentication .................................................................................................................................9Logout threats and attacks .............................................................................................................................28

Cached data remains after logout .............................................................................................................29Cached logout pages ...................................................................................................................................28Physical access by unauthorized individuals..........................................................................................28

Memory allocation and buffer overflows......................................................................................................48Messages of arbitrary length ..........................................................................................................................49Multiple authentication disorder ...................................................................................................................17Network services

Disable unnecessary ...................................................................................................................................55Never trust user input .....................................................................................................................................42Organization of report .......................................................................................................................................3Performance impact of encryption................................................................................................................63Permissions .......................................................................................................................................................58Physical separation of Web and database servers......................................................................................55Platform vulnerabilities ...................................................................................................................................56POST.................................................................................................................................................................. 34Premise ................................................................................................................................................................5Public Web Presence..........................................................................................................................................1Purpose................................................................................................................................................................1Reference material .....................................................................................................................................52, 66Resource exhaustion..................................................................................................................................18, 68Scope....................................................................................................................................................................1Secure coding practices ..................................................................................................................................42

External application dependencies and messages of arbitrary length................................................49Memory allocation and buffer overflows .................................................................................................48Never trust user input.................................................................................................................................42Principles of least privilege and compartmentalization ........................................................................42Protecting the application from its environment....................................................................................45System function return values ...................................................................................................................45User input and shell evaluation.................................................................................................................43Verbose error messages .............................................................................................................................47

Page 77: Building Secure e-Commerce Applications · 2012-07-23 · 1 T his research report from METASeS, Building Secure e-Commerce Applications, provides guidance to organizations that are

METASeS™ Index

72

Server-Side coding best practices..................................................................................................................51Server-Side coding techniques .......................................................................................................................40Session cloning .................................................................................................................................................26Session IDs

Hypertext Transfer Protocol (HTTP) ........................................................................................................20Session issues ...................................................................................................................................................20Session issues best practices .........................................................................................................................30Session tracking................................................................................................................................................26

Threats and attacks.....................................................................................................................................26Session tracking techniques ...........................................................................................................................22

Cookies..........................................................................................................................................................24Hidden form elements.................................................................................................................................23IP addresses .................................................................................................................................................25URL rewriting ...............................................................................................................................................22

Sessions and session Ids .................................................................................................................................20Shell evaluation ................................................................................................................................................43Stored procedures............................................................................................................................................61System function return values........................................................................................................................45Tokens................................................................................................................................................................14Transaction-Level best practices ...................................................................................................................39Transaction-Level issues .................................................................................................................................31Transaction-Level issues -- threats and attacks ...........................................................................................32

Client-Side filtering ......................................................................................................................................33Commercial Off the Shelf (COTS) products .............................................................................................38Disclosure of client data .............................................................................................................................36GET vs. POST .............................................................................................................................................. 34Improper application flow..........................................................................................................................35Unexpected user input................................................................................................................................32Verbose error messages .............................................................................................................................35

Unexpected user input ....................................................................................................................................32URL rewriting ....................................................................................................................................................22User input

Content..........................................................................................................................................................32Size.................................................................................................................................................................32Type...............................................................................................................................................................32

User input and shell evaluation .....................................................................................................................43User name harvesting......................................................................................................................................17Vendor vulnerabilities......................................................................................................................................56Verbose error messages ............................................................................................................................35, 47Views ..................................................................................................................................................................59Vulnerabilities .....................................................................................................................................................6Web sitesTypes of ...............................................................................................................................................................1