ASP.NET includes new functionality named Web Server Controls, which contains five controls that can be used to validate user input.. Client-side validation code is contained in a script,
Trang 1Contents
Overview 1
Lesson: Types of User Input Attacks 8
Lesson: Performing Validation 23
Lesson: Revealing As Little Information
Review 46
Module 3: Validating User Input
Trang 2Information in this document, including URL and other Internet Web site references, is subject to change without notice Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred Complying with all applicable copyright laws is the responsibility of the user Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property
2002 Microsoft Corporation All rights reserved
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, Active Directory, Authenticode, Hotmail, JScript, Microsoft Press, MSDN, PowerPoint, Visual Basic, Visual C++, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries
The names of actual companies and products mentioned herein may be the trademarks of their respective owners
Trang 3Instructor Notes
This module provides students with an explanation of how to manage user input
in a Web application in a secure way The methods for checking user input, and
a discussion of the consequences of not performing those checks, are the focus
of this module After completing this module, students will be able to secure
their Web applications by validating user input
After completing this module, students will be able to:
! Identify the sources of user input in a Web application
! Describe the different types of user input attacks
! Implement user input validation
! Use communications analysis and coding best practices to avoid providing information that can be used for security attacks
To teach this module, you need the following materials:
! Microsoft® PowerPoint® file 2300A_03.ppt
! HTML and Flash animation files: 2300A_03_A05_1640.htm, 2300A_03_A05_1640.swf
To prepare for this module:
! Read all of the materials for this module
! Complete the lab
! Practice the steps for the demonstrations
! Review the multimedia demonstration
! Read the TechNet articles, “Cross-site Scripting Overview,” “Cross-Site Scripting Security Exposure Executive Summary,” and “Cross-Site Scripting: Frequently Asked Questions,” which are available at http://www.microsoft.com/technet/treeview/default.asp?url=/TechNet/ security/topics/csoverv.asp
! Read the Microsoft MSDN® article, “HOWTO: Prevent Cross-Site Scripting Security Issues in CGI or ISAPI,” which is available at http://support.microsoft.com/directory/
article.asp?ID=KB; EN-US;Q253165&
! Read the MSDN article, “RequiredFieldValidator Control,” which is available at http://msdn.microsoft.com/library/default.asp?url=/library/ en-us/cpgenref/html/cpconrequiredfieldvalidatorcontrol.asp
! Read the MSDN article, “RegularExpressionValidator Control,” which is available at http://msdn.microsoft.com/library/default.asp?url=/library/ en-us/cpgenref/html/cpconregularexpressionvalidatorcontrol.asp
! Read Chapter 12, “Securing Against Attack,” in Designing Secure
Web-Based Applications for Microsoft Windows 2000 by Michael Howard
(Redmond, Microsoft Press®), 2000
Trang 4How to Teach This Module
This section contains information that will help you to teach this module
Lesson: User Input
This section describes the instructional methods for teaching each topic in this lesson
Discuss the various sources that can be used to accept user input in a Web application Explain how these sources can be maliciously used by an attacker
to enter a Web application
Discuss how accepting all user input without performing any validation can be detrimental to the Web application
User input can be validated at the server side or the client side Explain to the class that although performing client-side validation is important because it reduces round-trips to Web server, it is not secure Therefore, as a best practice, the validation must also be performed at the server side
This animation shows the procedure for client-side and server-side processing The sequence of steps that occur during this multimedia demonstration is as follows:
1 The client requests a Microsoft ASP.NET page from the Web server
2 The server returns a page that contains Hypertext Markup Language
(HTML) and script to the client The page includes TextBox and Button
controls The page also contains client-side script that validates the contents
of the text box
3 If the user types invalid information in the text box, the client-side script generates a message box
Because no information has been sent to the server, client-side processing reduces network traffic and response times
4 The user corrects the information in the text box, and then clicks Submit
5 The information is validated at the client side and is then sent to the server, where server-side processing can occur
6 The server repeats the validation and stores the information from the text box in a database
Because the client-side script cannot access server resources, server-side processing offers a greater range of flexibility in data processing
Identifying the Sources
Trang 5Lesson: Types of User Input Attacks
This section describes the instructional methods for teaching each topic in this lesson
Explain how canonical Uniform Resource Locator (URL) formats can become a weakness for a Web application for an attack Canonicalization mistakes are caused the Web application implements security decisions based on a name (such as a file name, a directory name, or a URL) and more than one representation of the resource name exists, which can lead to the security check being bypassed
Explain the two types of cookies that can be used in a Web application to store data: persistent and session Emphasize that cookies can be modified, and therefore, storing sensitive data in a cookie can prove to be dangerous for a Web application
Emphasize that Hypertext Transfer Protocol (HTTP) header values can be changed and therefore should not be trusted
Discuss the vulnerabilities that exist in accepting user input using a form Emphasize the best practices that must be used before accepting user input Use this demonstration to explain how data can be modified maliciously at the client side
This topic uses an animated slide to show how a script command injection attack occurs in four steps Cover the explanation for the corresponding step as
it appears on the slide
Use this demonstration to explain how a script command injection attack is performed on a Web application
Lesson: Performing Validation
This section describes the instructional methods for teaching each topic in this lesson
ASP.NET includes new functionality named Web Server Controls, which contains five controls that can be used to validate user input Use examples to explain when these Web Server Controls should be used
This topic describes the common properties of Web Server Controls and how these controls help in preventing user input attacks
Use this demonstration to explain how a RequiredFieldValidator control can
be used to verify that a TextBox control does not accept blank entries from
users
Explain the need for regular expressions and briefly discuss the elements of regular expressions that are covered in this topic Inform students that this topic covers only the commonly used regular expression elements and that the complete list of regular expression elements can be located in Microsoft Visual Studio® NET Help Open Visual Studio NET Help and search for regular expressions Open the page that provides a comprehensive list of regular expression elements and show that list to the students in the class
URL Format Attacks
Trang 6Explain how students can use regular expressions to secure their ASP.NET Web applications by matching the string with the pattern that is defined in regular expressions ASP.NET uses two different classes that are used for
creating and using regular expressions: RegularExpressionValidator and Regex Show the code examples for implementing both of these classes by
clicking the code example link that is provided on the bottom of the slide Explain how students can use regular expressions to secure their Active Server Pages (ASP) Web applications by matching the string with the pattern that is defined in regular expressions Use the code example link that is provided on the bottom of the slide to show the two different implementations of regular expressions in ASP Web applications
In this demonstration, students will see how a regular expression can be used to verify that an input control has a properly formatted social security number
In this practice, students will attempt to find all of the possible security weaknesses on an existing Web page
Lesson: Revealing As Little Information As Possible to Users
This section describes the instructional methods for teaching each topic in this lesson
Discuss in the class how revealing information to users can benefit attackers Explain why it is important to conceal private and implementation details in the messages that are sent back to users You can use the example that a Web application might use a user logon name to greet users, which is a bad security practice If the students need to provide personalization in their Web
application, they should use the user’s first name or nickname to address the user, rather than using the user’s logon name
A Web application interacts with users to provide them feedback on their actions Feedback is provided under normal conditions, such as a verification message and a success message, or under error conditions, such as an error message Emphasize to the class that the feedback message should be generic, and concise
Detailed error messages can help attackers to find out the implementation details of an organization’s Web application and can also help the attackers to determine the vulnerabilities in the Web application Therefore, it is important
to obscure error details in the messages
This topic covers obscuring error details in ASP Web applications and ASP.NET Web applications Emphasize to the class that detailed error messages are helpful during Web application development because they help Web developers in debugging Therefore, most of the Web applications may be configured to display detailed error messages during the Web application development phase However, it is then important to ensure that detailed error messages are obscured before moving the Web application to the production server
Discuss how storing literal values in script or source code can be dangerous for
a Web application Inform students that they must never store the literal values
in script or source code Instead, they must store literal values in secured configuration files or in the Microsoft Windows® registry
Trang 7Lab 3: Verifying User Input
Introduce the lab by stating that the labs for Course 2300, Developing Secure
Web Applications, create two Web applications, TailspinToys and
TailspinToysAdmin By accessing the TailspinToys Web application, users will
be able to get a list of the products that are created by Tailspin Toys, and resellers will be able to view the status of their orders By accessing the TailspinToysAdmin Web application, employees will be able to create new reseller accounts and update the status of reseller orders
This lab edits the logon page of the Tailspin Toys Web application to use a strong password For this lab, a strong password must have at least one number, one lowercase letter, and one uppercase letter, and must be at least 8 characters long, but not more than 20 characters long
Customization Information
This section identifies the lab setup requirements for a module and the configuration changes that occur on student computers during the labs This information is provided to assist you in replicating or customizing Microsoft Official Curriculum (MOC) courseware
You will use the 2300Labs.NET solution and the TailspinToys.NET and TailspinToysAdmin.NET Web applications to complete the ASP.NET exercises
in this lab
Trang 8You must assign each student a TailspinToys account to use for the labs The following is a list of the accounts that exist in the TailspinToys database These names correspond to the student computer names, so you can tell each student
to use his or her respective user name when accessing the TailspinToys Web
application throughout the labs in the Course 2300, Developing Secure Web
Applications
User name Password
Acapulco P@ssword8 Auckland P@ssword8 Bangalore P@ssword8 Bonn P@ssword8 Brisbane P@ssword8 Caracas P@ssword8 Casablanca P@ssword8 Denver P@ssword8 Glasgow P@ssword8 Khartoum P@ssword8 Lima P@ssword8 Lisbon P@ssword8 London P@ssword8 Manila P@ssword8 Miami P@ssword8 Montevideo P@ssword8 Moscow P@ssword8 Nairobi P@ssword8 Perth P@ssword8 Santiago P@ssword8 Singapore P@ssword8 Stockholm P@ssword8 Suva P@ssword8 Tokyo P@ssword8 Tunis P@ssword8 Vancouver P@ssword8
Lab Results
There are no configuration changes on student computers that affect replication
or customization
Trang 9Overview
! User Input
! Types of User Input Attacks
! Performing Validation
! Revealing As Little Information As Possible to Users
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this module, you will learn how to manage user input in a secure way An important security best practice that you must follow is to never trust user input
If you trust a user’s input in a Web application, you are making your Web application vulnerable to attack If your Web application accepts input from users, it is imperative that the Web application validate the input before processing it The methods for checking user input, and an explanation of the consequences of not performing those checks, are the focus of this module After completing this module, you will be able to:
! Identify the sources of user input in a Web application
! Explain the different types of user input attacks
! Implement user input validation
! Use communications analysis and coding best practices to avoid providing information that can be used for security attacks
The code samples in this module are provided in both Microsoft®
Visual Basic® NET and C#
Introduction
Objectives
Note
Trang 10Lesson: User Input
! Identifying the Sources of User Input
! Why Validate User Input?
! Types of User Input Validation
! Multimedia: Client-Side and Server-Side Processing
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this lesson, you will learn about the sources of user input in a Web application You will also be introduced to the reasons for validating user input and the various ways to perform input validation
After completing this lesson, you will be able to:
! Identify the sources of user input
! Decide when user input validation is necessary
! Describe the different types of user input validation methods
Introduction
Lesson objectives
Trang 11Identifying the Sources of User Input
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
All Web applications receive most of their input from users and then perform some actions on that user input The user input can be as simple as Hypertext Transfer Protocol (HTTP) GET requests for pages or can include uploaded data from the user The user input has five forms: Uniform Resource Locators (URLs), GET data, POST data, cookies, and HTTP headers
URLs are used to request the individual resources of a Web application URL formats can range from simple htm file requests to complicated formats that include GET parameters, as shown in the following example:
http://www.tailspintoys.com/products.aspx?id=4&view=detail
The URL shown in the preceding example passes two GET parameters, id and
view, with values 4 and detail, respectively, to the Web application
GET data contains parameters and values that a user passes to a Web application to satisfy a GET request These parameters and values appear in the URL for the GET request Often, a Hypertext Markup Language (HTML) form
is used to request the data from the user
POST data contains parameters and values that a client passes to a Web application to satisfy a POST request These parameters and values are sent in the body portion of the request and are not visible in the URL Often, an HTML form is used to request the data from the user
Introduction
URLs
GET data
POST data
Trang 12Cookies are used to store data on the client computer A cookie is associated with a URL A server can request a browser to store particular data in a cookie, for a URL, by using an HTTP Set-Cookie header If a client browser has a cookie that is already associated with a URL, each time a request is made to that URL, the client browser includes the cookie as the part of the HTTP request Cookies can also be read and written from the HTML script that runs
on the client browser
Client browsers provide numerous HTTP request header values to describe the client environment to the server These request headers include the fields that are shown in the following table
HTTP request header name Description
Authorization Contains the authentication credentials for the
requesting user
From Contains the e-mail address of the requesting user Referer Contains the address of the resource where the
current URL was obtained
User-Agent Contains the information about the requesting
user’s browser and local computer environment
Cookies
HTTP headers
Trang 13Why Validate User Input?
! User input can be used to attack a Web application to:
! To avoid a user input attack:
valid range
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
User input can potentially be used to attack a Web application The reason for the attack can be to reveal implementation details about the Web application, to cause the Web application to create malicious data, to execute malicious script
on the Web application, or to access restricted resources on the Web application Any implementation details that are revealed can then be further used to attack the Web application repeatedly Malicious data can be used to gain unauthorized access to the Web application Malicious script can be used
to manipulate the Web application or to attack the users of the Web application User input attacks can also target restricted resources to gain access to secured information on the Web application
You must deal with all user input as if it is potentially part of an attack
Whenever you receive input from the user, you must clearly define a narrow range of valid input values You then must write code to accept only data within that valid range
It is important to validate input by allowing only the known valid values, rather than explicitly rejecting known invalid values In the former case, you are guaranteed to reject all invalid formats, whereas in the latter case, you are rejecting only those invalid formats that you are aware of
Introduction
Countermeasures
against user input attack
Trang 14Types of User Input Validation
resulting in more server round-trips
! ASP.NET validation controls
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Validation code that is needed to check the user input can be executed either at the client side or at the server side
Client-side validation code is contained in a script, which is included with the HTML that is sent to the client This client-side validation code then runs on the browser on the client computer The client-side validation code validates the user data, typically from field values, before sending the data to the server Any errors in the validation must be resolved by the user before the data is sent to the server Client-side validation code minimizes server round-trips for data validation
Server-side validation code runs on the Web application server, and it validates the data that the user sent as part of a request Any validation errors necessitate sending a response, with the corresponding validation error messages, to the client Server-side validation requires several server round-trips for data validation errors
Microsoft ASP.NET includes special Web controls for validation One of the best features of these controls is that they support both client-side and server-side validation If the client browser supports script execution, the ASP.NET validation controls generate the HTML that includes client-side validation script Regardless of the client browser capabilities, the ASP.NET validation controls also always perform validation at the server side
Introduction
Client-side validation
Server-side validation
Trang 15Multimedia: Client-Side and Server-Side Processing
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
This multimedia presentation describes the differences between client-side and server-side processing
Introduction
Trang 16Lesson: Types of User Input Attacks
! URL Format Attacks
! HTTP Cookie Attacks
! HTTP Header Attacks
! Form Data Attacks
! Demonstration: A Form Data Attack
! Script Command Injection Attacks
! Demonstration: A Script Command Injection Attack
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this lesson, you will learn about the types of user input attacks that you must secure Web applications against
After completing this lesson, you will be able to:
! Describe the types of user input attacks against a Web application
! Use best practices for securing a Web application against user input attacks
! Avoid script command injection attacks
Introduction
Lesson objectives
Trang 17URL Format Attacks
! Different URL formats are referred to as canonical forms
! Canonical forms for URLs can become a weakness for
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
URLs are used to name resources within a Web application, and they can have many formats You have already learned about the URL format that contains GET parameters at the end Different URL formats are referred to as canonical forms A canonical form for a name is a standard or conventional format for that name For example, a computer name has three canonical forms: the Domain Name System (DNS) name (for example, tailspintoys.com), the network basic input/output system (NetBIOS) name (for example,
\\tailspintoys), and the Internet Protocol (IP) address (for example, 192.168.0.1) The term canonicalization can also be used for referring to the process of transferring a name to a canonical form
Canonical forms for URLs can become a weakness for a Web application because some URL formats are vulnerable, and therefore, can become a security threat Attackers can exploit the URLs to gain access to the Web application’s resources For example, if you allow parent paths or special characters at the end of the URL, an attacker might enter one of the following URLs and gain access to a command prompt or the c:\boot.ini file:
! http://www.tailspintoys.com/scripts/ / /winnt/system32/cmd.exe
! http://www.tailspintoys.com/samples/showcode.asp?file= / / /boot.ini Microsoft Internet Information Services (IIS) version 4.0 and earlier had a weakness that allowed URLs ending in special characters or character sequences to return the script source instead of the HTML response The URLs had formats such as:
! http://www.tailspintoys.com/default.asp::$DATA
! http://www.tailspintoys.com/default.asp
Notice the trailing "::$DATA" in the first example and the trailing "." in the second example These weaknesses permitted anyone with a browser to view the script source for a Web application
Introduction
::$DATA
Trang 18An IP address has two forms: the dotted notation (for example, 192.158.0.1) and the dotless notation (for example, 3231580161) The canonical form for an
IP address is the dotted notation, because it is more easily read by humans The dotless notation is a valid form, but it is not a canonical form
To convert a dotted IP address of the form a.b.c.d to the dotless form, use the following formula:
dotlessIP = (a * 16777216) + (b * 65536) + (c * 256) + d Microsoft Internet Explorer version 4 and earlier had a vulnerability with dotless IP addresses Those versions of Internet Explorer considered a dotless
IP address to be part of the intranet zone, and therefore, ran that address under more lax security restrictions Microsoft Internet Explorer version 5 and later consider dotless IP addresses to be part of the Internet zone
Dotless IP addresses
Trang 19URL Format Attacks (continued)
! Parent paths
! Do not use a parent path in a Web application; instead, use an absolute path
! Configure IIS to disable parent paths
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Parent path URLs contain " " characters, which refer to the parent folders of a Web application Parent path URLs can be used to navigate between virtual roots or folders that are outside a virtual directory in IIS
Parent paths can also be used to attack a Web application There are many forms of URLs that use parent paths to access files that are outside a virtual root The following URL attempts to access the Microsoft Windows® 2000 command prompt:
http://www.tailspintoys.com/scripts/ / /winnt/system32/cmd.exe The preceding URL assumes that the /scripts folder is in the default location, namely C:\Inetpub\wwwroot This relative URL is then trying to access cmd.exe within its default location, namely C:\WinNT\System32\ This URL format can also be used to send arguments and commands to cmd.exe
IIS 4.0 included a sample application that would return the source code of a file
to the client Parent paths, as shown below, can also be used to exploit such applications:
http://www.tailspintoys.com/samples/showcode.asp?file= / / /boot.ini
Parent path
Trang 20Do not use parent paths within your Web application Instead, use absolute paths to reference Web pages
To secure IIS version 5.0 against parent path attacks, you should configure IIS
to not permit " " to appear in URLs To configure a virtual root directory:
1 Click Start, point to Programs, point to Administrative Tools, and then click Internet Services Manager
2 Right-click the virtual root directory, and then click Properties
3 In the Properties dialog box, on the Virtual Directory tab, click Configuration
4 In the Application Configuration dialog box, on the App Options tab, clear the Enable parent paths check box, as shown in the following illustration, and then click OK
5 Click OK to close the Properties dialog box
In the rare case when you write code that makes execution choices based on the format of a URL, you must first parse the URL into a standard format Then, you can reject any URLs that cannot be parsed into that format
Disable parent paths
Canonicalize URLs
Trang 21HTTP Cookie Attacks
! Two types of cookies: persistent and session
! Persistent cookies can be edited with Notepad.exe
! All cookies can be edited in client-side script
! Do not store sensitive data in a cookie
! Encrypt cookie data if necessary
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Cookies store per-user information for a Web page A server requests a browser
to store particular information in a cookie by using the Set-Cookie HTTP header The browser stores that information by page URL and individual user
If a browser has a cookie associated with a page URL, the browser sends that cookie data every time it requests that page
There are two types of cookies:
! Persistent cookies Persistent cookies are useful for information that must be used every time that the user visits a page, such as user identification data Persistent cookies are saved between browser sessions in text files in the following folder:
C:\Documents and Settings\username\Cookies
! Session cookies Session cookies remain in memory only for the duration of the current user session When the current user session expires, session cookies are deleted These cookies are not stored in a file
Session cookies are useful for information that is related only to a single user session Active Server Pages (ASP) and ASP.NET use session cookies
to associate a request with a programmatic session
All cookies can be edited by a malicious user Persistent cookies are text files that can be edited with any text editor, such as Microsoft Notepad The format
of the data in the text file is dependent on how the server is configured to represent the data Some cookie formats are obvious to determine, whereas other formats are more opaque If you can determine the format, you can then edit the data
Both session and persistent cookies can be read and modified in HTML script
by using the cookie property of the document object in Microsoft JScript®
Introduction
Types of cookies
Vulnerabilities
Trang 22Do not store sensitive data in cookies Any data in a cookie can potentially be compromised
Here is an example that illustrates the weakness of storing data in a cookie A catalog Web application might store the entire user shopping cart in a persistent cookie The shopping cart includes product prices and the Web application does not validate these prices Using Notepad.exe, a malicious user could change the price of any product in his or her shopping cart, and those new prices would then be accepted Malicious users could effectively give themselves any discount that they want on any of the Web application’s products
Instead of storing sensitive data in a cookie, store a lookup key, such as a globally unique identifier (GUID), and keep the sensitive data on the server, in
a file, or in a database You can then use the lookup key from the user request to find the sensitive data in your database If users change the lookup key in the cookie, they will lose the cookie data instead of causing malicious changes You can also encrypt cookie data before sending it to the client browser Encrypting cookie data renders the cookie data opaque to the client
To learn more about encryption, see Module 9, “Encrypting, Hashing,
and Signing Data,” in Course 2300, Developing Secure Web Applications
Best practices
Note
Trang 23HTTP Header Attacks
! Do not trust the header values sent by the client
! Do not trust header values for important decisions
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
HTTP header values are sent from the client to the server, as well as from the server to the client The headers that are sent by the client cannot be trusted because a malicious client can change the header values
You should not rely on client header values for sensitive information or for decision-making One example of relying on client header values might be to use the Referrer header to pay affiliates for generating traffic to your Web application A malicious client could modify the Referrer header value to always refer to their Web application
Introduction
Trang 24Form Data Attacks
! Form values
" GET method includes the field values in the URL
" POST method includes the field values in the body of the request
! Form fields
" All form fields and field names are visible in source code
" Hidden fields are not secure
! Validate field values and field names
! Validate field value type and length
! Use forms for the minimum required data
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
HTTP forms are used to send client data to a Web application Forms consist of fields, field types, field values, and a sending method The following code is an example of an HTML form that uses the GET method and includes two text
boxes (named Field1 and Field2) and one Submit button:
<FORM method="GET"
action="http://www.tailspintoys.com/demo.aspx">
<INPUT type=text name=Field1>
<INPUT type=text name=Field2>
<INPUT type=submit value=Submit>
</FORM>
Forms are rendered in client browsers as collections of fields that are represented by controls, including text boxes, combo boxes, list boxes, and buttons Users typically enter values into the controls and then click a button to send the data to the Web application
Hidden form fields can also be used for data-like product identifier (IDs) that do not need to be displayed to the user However, these product IDs are visible to the user in the source code
Form data can be sent to a Web application by one of two methods: GET and POST A form that is sent by the GET method includes the form field names and values in the URL, as shown in the following example:
http://www.tailspintoys.com/demo.aspx?Field1=val1&Field2=val2
A form that is sent by the POST method includes the form field names and values in the body of the request With the POST method, the form data is not visible in the URL
Introduction
Form fields
Trang 25All form fields and their names are visible in the HTML source of a page Any hidden form fields can also be accessed in the source Form field names and values can be manually edited
When form values are sent to the Web server by using a GET or POST method, form values can easily be edited by anyone Any user of the Web application can save the HTML response that contains the form to a file A user can then manually modify that HTML file before submitting the data
The types and lengths of form fields can be modified by attackers If a Web application uses a particular data type for a form field, an attacker can attempt
to use other data types to attack For example, an attacker can save the form locally and change the values for the form field to be other than what is specified in the Web application Similarly, if a Web application has a particular maximum length that is assigned for a form field, an attacker can save the form and enter a value that is longer than the specified maximum length to attack a Web application
You must validate the field values in a form for the GET or POST method If you create scripts from field names or use them in Web application code, you must also validate the field names
Do not put unnecessary information in forms and do not assume that hidden fields are secure from modification by the user
For example, a catalog Web application could use a hidden form field for the price of a product This price can easily be modified by a malicious client If you do not validate that price when the form is submitted, you are open to accepting any price that the user chooses Therefore, you must validate that field Alternatively, as a best practice, do not include the price in the form at all Display the price to the user, but rely only on the price that you store in a database when accepting an order on a product
Vulnerabilities
Best practices
Trang 26Demonstration: A Form Data Attack
1 Demonstrate a GET form modification
2 Demonstrate a POST form modification
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this demonstration, you will see how the form data that is submitted by using the GET and POST methods can be maliciously modified at the client side
! Demonstrate a GET form modification
1 Open the 2300Demos solution in Microsoft Visual Studio® NET and build the Mod03 project
2 Open Internet Explorer and browse to the http://localhost/2300Demos/ Mod03/RangeGet.htm page
3 On the View menu, click Source
Notice that the page uses the GET form method to send the entered number
to the Received.aspx page The page also uses client-side validation to ensure that the value that is entered is from 1 through 10
4 Close the source window
5 On the RangeGet.htm page, type a value of 2300 in the text box, and then click Submit
Notice that the client-side validation prevents an invalid value from being sent to the server
6 On the RangeGet.htm page, type a value from 1 through 10 in the text box,
and then click Submit
The response page returns your value
7 Modify the URL in Internet Explorer to be http://localhost/2300Demos/ Mod03/Received.aspx?Number=2300, and then press ENTER
Because there is no server-side validation, the response page returns the value 2300 Users can modify the URL to easily affect the value that is sent
Introduction
Trang 27! Demonstrate a POST form modification
1 Open Internet Explorer and browse to the http://localhost/2300Demos/ Mod03/RangePost.htm page
2 On the View menu, click Source
Notice that the page uses the POST form method to send the entered number
to the Received.aspx page The page also uses the same client-side validation to ensure that the value that is entered is from 1 through 10
3 Close the source window
4 On the RangePost.htm page, type a value of 2300 in the text box, and then click Submit
The client-side validation prevents an invalid value from being sent to the server
5 On the RangePost.htm page, type a value from 1 through 10 in the text box,
and then click Submit
The text box value is not visible in the URL for a POST method form The response page returns the valid input
6 Return to the RangePost.htm page
7 On the File menu, click Save As
8 In the Save Web Page dialog box, save the file to the local disk as
c:\HackedPost.htm
9 Open the HackedPost.htm file in Notepad and make the following changes:
a Delete the onSubmit handler from the widget_order form, so that the
FORM tag looks like the following:
<FORM NAME="widget_order" ACTION="Received.aspx"! METHOD="POST">
b Change the action attribute of the FORM tag to the following:
action="http://localhost/2300Demos/Mod03/Received.aspx"
10 Save your changes to the HackedPost.htm file, and then close Notepad
11 Open Windows Explorer, and then, using a drag-and-drop operation, open the HackedPost.htm file in Internet Explorer
12 Type a value of 2300 in the text box, and then click Submit
The response page returns the invalid input because there is no server-side validation and because you modified the HTML file to circumvent the client-side validation
Trang 28Script Command Injection Attacks
Malicious Source
1 2 3
Client Browser
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Whenever you use user data to build scripts for execution, you must be careful Malicious clients may be able to replace the user data with embedded script to affect the script that you ultimately execute You should validate all values that are used in script or returned to the user
A common example of a script command injection attack is cross-site scripting
In a cross-site scripting attack, malicious users do not attack the Web server, but rather they attack the other users of the Web server This type of attack depends on a Web application that creates dynamic pages from user data Cross-site scripting permits the malicious user to execute script on another user’s computer, in the other user’s context This script can then access cookies, run other scripts, or call native code components
In the preceding illustration, a Web application accepts user data from a form, such as search criteria The Web application then returns the nonvalidated search criteria in the response A malicious client can set the search criteria value to embedded script, thus executing that script on another client browser
In the preceding illustration, a malicious source includes a link that contains a script to upload to the target, which is a trusted Web application This malicious source could be an e-mail message, a newsgroup posting, or a Web application that includes a link to a trusted site
In this example, the www.tailspintoys.com Web application is a trusted site that has a page named home.aspx, which includes a GET form variable named
search The search variable’s value is returned to the user in the response The malicious source uses the search form variable to include embedded
HTML script in the link
A user receives the malicious link and clicks it The user’s browser sends the form data, which includes the malicious embedded script, to the trusted Web application
Trang 29For example, the www.tailspintoys.com Web application receives the request from the user and executes the search with the malicious search criteria In its response, the Web application includes the original search criteria This response causes the malicious script to be included in the HTML response that
is sent back to the user
The user receives the HTML response from www.tailspintoys.com The user’s browser then executes the malicious script The malicious script can cause a lot
of damage on the user’s computer, including reading any cookies that the user has for the www.tailspintoys.com Web application, running other script, and calling ActiveX® controls or plug-ins
If you use form fields to generate script or to return their values back to the user, you must validate all form fields to ensure that they do not include embedded script
Step 3: Malicious script
is included in the HTML
response
Step 4: User executes
the malicious script
Best practice
Trang 30Demonstration: A Script Command Injection Attack
1 Inject HTML script into a form field
2 Show the injected script within the Label1 span tag
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this demonstration, you will see how a script command injection attack works
! Inject HTML script into a form field
1 Open Internet Explorer and browse to the http://localhost/2300Demos/ Mod03/RangeGet.htm page
2 Type a value of <script>alert(document.cookie);</script> and then click Submit
The injected script is run on the response page
3 Click OK to dismiss the alert dialog box
4 On the View menu, click Source
Show that the injected script appears within the Label1 span tag
Introduction
Trang 31Lesson: Performing Validation
! ASP.NET Validation Controls
! Using ASP.NET Validation Controls
! Demonstration: Using Validation Controls
! Regular Expressions
! Using Regular Expression Validation in ASP.NET
! Using Regular Expression Validation in ASP
! Demonstration: Using Regular Expressions
! Practice: Break This Page
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this lesson, you will learn how to perform validation on user data for both ASP and ASP.NET Web applications
After completing this lesson, you will be able to:
! Describe ASP.NET validation controls
! Use ASP.NET validation controls to validate user input
! Describe the regular expression validation
! Use regular expressions, in the Microsoft NET Framework code and ASP code, to validate user input
Introduction
Lesson objectives
Trang 32ASP.NET Validation Controls
! Five Web Server Controls used for validating user input
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
ASP.NET includes five Web Server Controls that validate user input in different ways All of the validation controls are in the
System.Web.UI.WebControls namespace and are derived from the BaseValidator control
The following table describes the ASP.NET Web server validation controls that are used for validating user input
Validation control Description RequiredFieldValidator Checks that a given field has a value This control is
useful for ensuring that a user enters values for all of the required fields in a form
RegularExpressionValidator Checks that a given field’s value matches a regular
expression pattern This control is useful for checking for known patterns in field values, such as telephone numbers, social security numbers, postal codes, and so
on
CompareValidator Checks that a given field’s value compares to a constant
or another property This control supports less than, greater than, equal, not equal, less than or equal, greater than or equal, and data type checks The last
comparison type validates that the field’s value can be represented as a particular data type The data type comparison check is useful for comparing fields to one another
CustomValidator Supports user-defined validation logic Useful for any
validation that is not supported by the existing validation controls The user-defined logic can be created in script or code
RangeValidator Checks that a given field’s value is within a range of
values The supported range types are numbers, characters, and dates
Introduction
ASP.NET Web Server
Controls
Trang 33Using ASP.NET Validation Controls
! Server validation is always performed by the controls
! Client validation is controlled by the EnableClientScript property
! All validation controls support ControlToValidate and ErrorMessage properties
! Validate length by using RegularExpressionValidator
! Validate type by using CompareValidator
<asp:Textbox id="pwd" runat="server"/>
<asp:RequiredFieldValidator id="Required"
runat="server" ErrorMessage="Password required." ControlToValidate="pwd"/>
<asp:Textbox id="pwd" runat="server"/>
<asp:RequiredFieldValidator id="Required"
runat="server" ErrorMessage="Password required." ControlToValidate="pwd"/>
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The ASP.NET validation controls support both server-side and client-side validation Whereas server-side validation is always performed by all of the
controls, client-side validation is performed only when the EnableClientScript property of the controls is set to True and the client browser supports script The default value for the EnableClientScript property is True Remember that
although client validation is not secure, it can reduce the number of server round-trips that are required to get valid user input
The validation controls, like other Web controls, are placed in an aspx page
Validation controls support the ControlToValidate and ErrorMessage
properties, and they also individually support properties that are specific to their
type of validation The ControlToValidate property is used to specify the control that is being validated The ErrorMessage property is used to specify
the text message that will be presented to the user if validation fails
For programmatic control, the Page class has an IsValid property that can be
queried to determine whether all of the validation controls on the page succeeded or whether one or more of the validation controls failed
Introduction
Common properties of
validation controls
Trang 34The RangeValidator and RegularExpressionValidator controls accept a
blank entry as valid input If you want to prevent blank entries with validation
controls, you must use a RequiredFieldValidator control You can use the RequiredFieldValidator control to provide a different error message to
address blank entries
The following aspx code example uses a RequiredFieldValidator control to
ensure that a value is typed in a password field:
<asp:Textbox ID="pwd" runat="server"/>
<asp:RequiredFieldValidator id="Required"
ControlToValidate="pwd"
ErrorMessage="Password required."
runat="server"/>
The RegularExpressionValidator control can be used to validate that a field is
within a particular length range
The format of regular expressions is covered in the topic “Regular Expressions” in Module 3, “Validating User Input,” in Course 2300,
Developing Secure Web Applications
The CompareValidator control can be used to validate that a field is of a particular type When a CompareValidator object’s Operator property is set
to DataTypeCheck, the field is validated to be of the CompareValidator object’s Type property value The following aspx code segment uses a CompareValidator control to ensure that a date is typed in a form field:
<asp:Textbox ID="date" runat="server"/>
<asp:CompareValidator id="DateType"