Quick Recap on Forms Authentication 192 Understanding Persistent Tickets 192How Forms Authentication Enforces Expiration 194 Securing the Ticket on the Wire 198 Setting Cookie-Specific S
Trang 2Professional ASP.NET 2.0 Security, Membership, and Role
Management
Stefan Schackow
Trang 3Professional ASP.NET 2.0 Security, Membership, and Role
Management
Stefan Schackow
Trang 4Professional ASP.NET 2.0 Security, Membership, and Role Management
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc.,
10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http:// www.wiley.com/go/permissions
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OFTHE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDINGWITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTYMAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE ANDSTRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK ISSOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERINGLEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE ISREQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE-FROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS ACITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THATTHE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION ORWEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BEAWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEAREDBETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ
For general information on our other products and services please contact our Customer Care Departmentwithin the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002
Trademarks:Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related tradedress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the UnitedStates and other countries, and may not be used without written permission All other trademarks are theproperty of their respective owners Wiley Publishing, Inc., is not associated with any product or vendormentioned in this book
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not
be available in electronic books
Trang 5Mary Beth Wakefield
Vice President & Executive Group Publisher
Quality Control Technicians
Amanda BriggsJohn GreenoughJoe Niesen
Proofreading and Indexing
TECHBOOKS Production Services
Trang 7To the ASP.NET group that gave me the opportunity to work
on a great product with a great team!
Trang 9About the Author
Stefan Schackow currently works as a program manager at Microsoft on the ASP.NET product team
He has worked extensively with the new application services delivered in ASP.NET 2.0, includingMembership and Role Manager Currently he is working on future directions for extending these fea-tures via Web Services and the Windows Communication Foundation Prior to joining the ASP.NETproduct team, he worked in Microsoft’s consulting services designing web and database applications for various enterprise clients
Trang 11I started out writing this book with the intent of setting down in words a brain dump of some of themore esoteric areas of features I either “own” or work on in conjunction with other folks However, asthe book took shape I found myself diving into areas that were important from a security perspectivebut that dealt with aspects of features that very few people really understood (myself included) I wouldlike to thank the following folks for answering my sometimes off-the-wall security questions: Pat, Shai,Erik, Mike, Simon, Adam, Manu, Helen, Mark, Laura, Dmitry, Ting, DaveM, Sudheer, Richa, Smitha, andDavidE Now that it’s all written down I promise to stop pestering you, maybe
I would also like to thank Jim Minatel for walking up to me at a DevConnections conference in 2004 andbroaching the idea of writing a security book Without his suggestion and support this project neverwould have occurred!
Trang 13What Does This Book Cover? xix What You Need to Run the Examples xxi
How to Download the Sample Code for the Book xxiii
Dynamic versus Static Content 9
ASP.NET Per-Request Security 33
Where Is the Security Identity for a Request? 34 Establishing the Operating System Thread Identity 38
Thread Identity and Asynchronous Pipeline Events 43
Trang 14DefaultAuthentication and Thread.CurrentPrincipal 54
PostAuthorizeRequest through PreRequestHandlerExecute 65 Blocking Requests during Handler Execution 66 Identity during Asynchronous Page Execution 69
What Is an ASP.NET Trust Level? 78
The Default Security Permissions Defined by ASP.NET 105
Using the <location /> Element 143
Using the lock Attributes 146
Reading and Writing Configuration 153
Permissions Required for Reading Local Configuration 155 Permissions Required for Writing Local Configuration 157
Using Configuration in Partial Trust 161
Demanding Permissions from a Configuration Class 165 FileIOPermission and the Design-Time API 166
Selecting a Protected Configuration Provider 169 Defining Protected Configuration Providers 172
Trang 15Quick Recap on Forms Authentication 192 Understanding Persistent Tickets 192
How Forms Authentication Enforces Expiration 194
Securing the Ticket on the Wire 198
Setting Cookie-Specific Security Options 204
The Cookieless Ticket and Other URLs in Pages 216
Sharing Tickets between 1.1 and 2.0 222 Leveraging the UserData Property 224 Passing Tickets across Applications 226
Enforcing Single Logons and Logouts 247
Chapter 6: Integrating ASP.NET Security with Classic ASP 259
IIS5 ISAPI Extension Behavior 260
Using the DefaultHttpHandler 270 Authenticating Classic ASP with ASP.NET 272
Trang 16Will Cookieless Forms Authentication Work? 273
Authorizing Classic ASP with ASP.NET 276
Safely Passing Sensitive Data to Classic ASP 278
Does Session State Equal Logon Session? 287 Session Data Partitioning 290
Session ID Reuse and Expired Sessions 296 Session Denial of Service Attacks 297 Trust Levels and Session State 300
Serialization and Deserialization Requirements 302
Database Security for SQL Session State 304 Security Options for the OOP State Server 306
Request Validation and Viewstate Protection 309
Patterns Found in the Provider Model 332
Trang 17The MembershipUser Class 371
Why Are Only Certain Properties Updatable? 379
The MembershipProvider Base Class 382
Retrieving and Searching for Multiple Users 387
Supporting Self-Service Password Reset or Retrieval 390
The “Primary Key” for Membership 394
Using Custom Hash Algorithms 399
Understanding the Common Database Schema 404
Why Are There Calls to the LOWER Function? 414
The Membership Database Schema 415
SQL Server–Specific Provider Configuration Options 418
Working with SQL Server Express 419
Trang 18Sharing Issues with SSE 424
Database Schemas and the DBO User 428 Changing Password Formats 430 Custom Password Generation 432 Implementing Custom Encryption 435 Enforcing Custom Password Strength Rules 437
Unique Aspects of Provider Functionality 477 ActiveDirectoryMembershipUser 480
Working with Active Directory 482
Installing ADAM with an Application Partition 504
Using the Provider in Partial Trust 512
Trang 19Working with Multiple Providers during GetRoles 537
SqlRoleProvider Database Schema 553
SQL Server–Specific Provider Configuration Options 555
Trang 21This book covers security topics on a wide range of areas in ASP.NET 2.0 It starts with detailed coverage
of how security is applied when an ASP.NET application starts up and when a request is processed Thebook then branches out to cover security information for features such as trust levels, forms authentica-tion, session state, page security, and configuration system security You will also see how you can inte-grate ASP.NET security with legacy ASP applications Over the course of these topics, you will gain asolid understanding of many of the less publicized security features in ASP.NET 2.0
The book switches gears in Chapter 9 and addresses two new security services in ASP.NET 2.0:
Membership and Role Manager You start out learning about the provider model that underlies both
of these features Then you will get a detailed look at the internals of both features, as well as the and Active Directory–based providers that are included with them After reading through these topics,you will have a thorough background on how you can work with the new providers and how you canextend them in your applications
SQL-Who Is This Book For?
This book is intended for developers who already have a solid understanding of ASP.NET 1.1 securityconcepts in the area of forms authentication, page security, and website authorization Where the bookaddresses new functionality, such as Membership and Role Manager, it assumes that you have alreadyused these features and have a good understanding of the general functionality provided by both ofthem As a result, this book does not rehash widely available public information on various features orAPI reference documentation
Instead, you will find that the book has been written to “peel back the covers” of various ASP.NET rity features so that you can gain a much deeper understanding of the security options available to you.The book also addresses lesser known security functionality such as ASP.NET trust levels and ASP.NET-to-ASP integration so that you can take advantage of these approaches in your own applications
secu-If you are looking for a deep dive on general ASP.NET 2.0 security, then you will find Chapters 1–8 veryuseful If your initial focus is on the new Membership and Role Manager features, then Chapters 9–15will be immediately useful to you After you have read through these topics, you will definitely have athorough understanding of why ASP.NET security works the way it does, and you will have insightsinto just how far you can “stretch” ASP.NET 2.0 to match your application’s security requirements
What Does This Book Cover?
The subject of ASP.NET security can refer to a lot of different concepts: security features, best codingpractices, lockdown procedures, and so on This book addresses ASP.NET security features from thedeveloper’s point of view It gives you detailed information on every major area of ASP.NET security
Trang 22you will encounter while developing web applications And it shows you how you can extend or modifythese features.
❑ Chapter 1 walks you through the internal processing ASP.NET performs when it starts up anapplication domain You will see how control passes from IIS to ASP.NET, and you will learnabout the special processing ASP.NET performs during the very first request to an app domain
❑ Chapter 2 gives you a detailed walk through of the security processing ASP.NET performs in its pipeline for each HTTP request You will see how the default authentication and authoriza-tion modules work, as well as how ASP.NET blocks access to content with special handlers This chapter also describes subtleties in how request identity works with ASP.NET 2.0’s asyn-chronous pipeline events and asynchronous page model
❑ Chapter 3 describes what an ASP.NET trust level is and how ASP.NET trust levels work to vide more secure environments for running web applications The chapter goes into detail onhow you can customize trust levels and how to write privileged code that works in partial trustapplications
pro-❑ Chapter 4 covers the new security features in the 2.0 Framework’s configuration system It cusses new configuration options for locking down configuration sections as well as protectingconfiguration sections from prying eyes It also discusses how ASP.NET trust levels and config-uration system security work together
dis-❑ Chapter 5 explains new ASP.NET 2.0 features for forms authentication You will learn about thenew integrated cookieless support and the new support forms authentication has for passingauthentication tickets across web applications The chapter also presents an extensive example
of implementing a lightweight single sign-on solution using forms authentication, as well ashow to enforce a single login using a combination of forms authentication and Membership
❑ Chapter 6 demonstrates using IIS6 wildcard mappings and ASP.NET 2.0’s support for wildcardmappings to share authentication and authorization information with classic ASP applications.The sample code in the chapter also shows you how you can use these features to integrateMembership and Role Manager with classic ASP
❑ Chapter 7 covers security features and guidance for session state New session state security tures introduced in ASP.NET 2.0 are covered, as well as security options for out-of-process stateand the effect ASP.NET trust levels have on the session state feature
fea-❑ Chapter 8 describes some lesser known page security features from ASP.NET 1.1 It also
describes new ASP.NET 2.0 options for securing viewstate and postback events Chapter 8 also covers how the new dynamic compilation model can be used with code access security
❑ Chapter 9 gives you an architectural overview of the new provider model introduced in
ASP.NET 2.0 The chapter covers the various Framework classes that are “the provider model”along with sample code showing you how to write your own custom provider-based features
❑ Chapter 10 talks about the new Membership feature The chapter goes into detail about the coreclasses of the Membership feature as well as how you can extend the feature with custom hashalgorithms
❑ Chapter 11 delves into both the SqlMembershipProvideras well as general database designassumptions that are baked into all of ASP.NET 2.0’s new SQL-based features You will learnhow you can extend the provider to support automatically unlocking user accounts The samplecode also covers custom password encryption, storing password histories, and extending the
Trang 23❑ Chapter 12 covers the other membership provider that ships in ASP.NET 2.0: the
ActiveDirectoryMembershipProvider You will learn about how this provider maps its functionality onto Active Directory, and you will see how to set up both Active Directory and Active Directory Application Mode servers to work with the provider
❑ Chapter 13 describes the new Role Manager feature that provides built-in authorization supportfor ASP.NET 2.0 You will learn about the core classes in Role Manager The chapter also detailshow the RoleManagerModuleis able to automatically set up a principle for downstream autho-rization and how the module and Role Manager’s caching work hand in hand Chapter 13 alsocovers the WindowsTokenRoleProvider, which is one of the providers that ships with RoleManager
❑ Chapter 14 discusses the SqlRoleProviderand its underlying SQL schema You will learnabout using the provider in conjunction with Windows authentication, extending the provider
to support custom authorization logic, and how you can use its database schema for data layerauthorization logic Although not specific to just SqlRoleProvider, the chapter covers how toget the provider working in a partial trust non-ASP.NET environment
❑ Chapter 15 covers the AuthorizationStoreRoleProvider— a provider that maps RoleManager functionality to the Authorization Manager feature that first shipped in Windows Server
2003 You will learn how to set up and use both file-based and directory-based policy stores withthe provider The chapter covers special Authorization Manager functionality that is supported
by the provider, as well as how to use both the ActiveDirectoryMembershipProviderand
AuthorizationStoreRoleProviderto provide Active Directory based authentication andauthorization in your web applications
What You Need to Run the ExamplesThis book was written using various Beta 2 and RC releases of the 2.0 Framework on Windows Server
2003 SP1 The sample code in the book has been verified to work with late RC builds of the 2.0Framework To run all of the samples in the book, you will need the following:
❑ Windows Server 2003 SP1
❑ Visual Studio 2005 RTM
❑ Either SQL Server 2000 or SQL Server 2005
❑ A Windows Server 2003 domain running at Windows Server 2003 functional levelMost of the samples should also work when using Windows XP Note that the information in most of thebook refers to security credential configuration using IIS6 application pools as opposed to the older
<processModel />approach used in Windows XP and IIS 5.1
The book covers topics in Chapter 6 that require IIS6 features to work
Chapters 11 and 14 use the SQL-based providers You should have either SQL Server 2000 or SQL Server
2005 set up to use these samples Scattered throughout the book are other samples that rely on theMembership feature — these samples also require either SQL Server 2000 or SQL Server 2005
Trang 24To run the samples in Chapter 12, you will need either a Windows Server 2003 domain controller,
or a machine running Active Directory Application Mode (ADAM) Chapter 12 addresses using the
ActiveDirectoryMembershipProviderin both environments
The sample code in Chapter 15 uses the Authorization Manager functionality in Windows Server
2003 (both setting up policies as well as consuming them) As a result, to run most of the samples youwill need a Windows Server 2003 domain controller that has been set up to work with AuthorizationManager For file-based policy stores, you do not need your own domain controller if you just want totry out file-based policy stores with AuthorizationStoreRoleProvider
Conventions
Code has several styles If I am talking about a word in the text—for example, when discussing a
For Nextloop — it’s in this font If it’s a block of code that can be typed as a program and run, then it’s also in a gray box:
Private Sub mnuHelpAbout_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles mnuHelpAbout.Click
Dim objAbout As New AboutobjAbout.ShowDialog(Me)objAbout = Nothing
Sometimes you’ll see code in a mixture of styles, like this:
Private Sub mnuHelpAbout_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles mnuHelpAbout.Click
Dim objAbout As New AboutobjAbout.ShowDialog(Me)
Trang 25Customer Suppor t
We always value hearing from our readers, and we want to know what you think about this book: whatyou liked, what you didn’t like, and what you think we can do better next time You can send us your comments either by returning the reply card in the back of the book or by email to feedback@wrox.com.Please be sure to mention the book’s title in your message
How to Download the Sample Code for the Book
When you visit the Wrox site (wrox.com) simply locate the title through our Search facility or by clickingthe Download Code link at the top of the main page, then find the book in the title list Click the HTTP
or FTP link for the book to download the code
The files that are available for download from our site have been archived using WinZip When youhave saved the attachments to a folder on your hard drive, you need to extract the files using a decom-pression program such as WinZip or PKUnzip When you extract the files, the code is usually extractedinto chapter folders When you start the extraction process, ensure that your software (WinZip orPKUnzip) is set to use folder names
Errata
We’ve made every effort to ensure that there are no errors in the text or in the code However, no one isperfect and mistakes do occur If you find an error in one of our books, such as a spelling mistake or afaulty piece of code, we would be very grateful for feedback By sending in errata, you may save anotherreader hours of frustration, and, of course, you will be helping us provide even higher-quality informa-tion Simply email the information to support@wrox.com; your information will be checked and, if cor-rect, posted to the errata page for that title, or used in subsequent editions of the book
To find errata on the Web site, go to wrox.comand simply locate the title through our Advanced Search
or title list or by going to the Help Center using the link at the bottom of the main page Click the ViewErrata link, which is to the right of the book’s title
Email Support
If you wish to directly query a problem in the book with an expert who knows the book in detail, thenemail support@wrox.comwith the title of the book and the last four numbers of the ISBN in the subjectfield of the email A typical email should include the following things:
❑ The title of the book, the last four digits of the ISBN (8000), and the page number of the problem
in the Subject field
❑ Your name, contact information, and the problem in the body of the message
We won’t send you junk mail We need the details to save your time and ours When you send an emailmessage, it will go through the following chain of support:
❑ Customer Support — Your message is delivered to our customer support staff, who are the firstpeople to read it They have files on most frequently asked questions and will answer anythinggeneral about the book or the Web site immediately
Trang 26❑ Editorial — Deeper queries are forwarded to the technical editor responsible for that book.They have experience with the programming language or particular product, and is able toanswer detailed technical questions on the subject.
❑ The Authors — Finally, in the unlikely event that the editor cannot answer your problem, he orshe will forward the request to the author We do try to protect authors from any distractions
to their writing; however, we are quite happy to forward specific requests to them All Wroxauthors help with the support on their books They will email the customer and the editor withtheir response, and again all readers should benefit
The Wrox support process can offer support only for issues that are directly pertinent to the content ofour published title Support for questions that fall outside the normal scope of a book’s support is pro-vided via the community lists of our http://p2p.wrox.comforum
p2p.wrox.com
For author and peer discussion, join the P2P forums Our unique system provides programmer contact on mailing lists, forums, and newsgroups, all in addition to our one-to-one emailsupport system If you post a query to P2P, you can be confident that it is being examined by the manyWrox authors and other industry experts who are present on our mailing lists At p2p.wrox.com, youwill find a number of different lists that will help you, not only while you read this book, but also as youdevelop your own applications Particularly appropriate to this book are the Visual Basic and VBAforums, the Database forums, and the DotNet forums
programmer-to-To subscribe to a forum, just follow these steps:
1. Go to http://p2p.wrox.com
2. Register using the Register link from the left menu bar or log in if you are already a member
3. Navigate to the appropriate forum
4. Click the Subscribe to This Forum link for the forum you wish to join.
Why This System Offers the Best Support
You can choose to join the mailing lists, or you can receive them as a weekly digest If you don’t have the time, or facility, to receive the mailing list, you can search our online archives Junk and spam mail isdeleted, and your own e-mail address is protected by the unique Lyris system Queries about joining orleaving lists, and any other general queries about lists, should be sent to listsupport@p2p.wrox.com
Trang 27Professional ASP.NET 2.0 Security, Membership, and Role
Management
Trang 29Initial Phases of a
Web Request
Before the first line of code you write for an aspxpage executes, both Internet Information Services(IIS) and ASP.NET have performed a fair amount of logic to establish the execution context for aHyperText Transfer Protocol (HTTP) request IIS may have negotiated security credentials with yourbrowser IIS will have determined that ASP.NET should process the request and will perform a hand-off of the request to ASP.NET At that point, ASP.NET performs various one-time initializations aswell as per-request initializations
This chapter will describe the initial phases of a Web request and will drill into the various securityoperations that occur during these phases In this chapter, you will learn about the following stepsthat IIS carries out for a request:
❑ The initial request handling and processing performed both by the operating system layerand the ASP.NET Internet Server Application Programming Interface (ISAPI) filter
❑ How IIS handles static content requests versus dynamic ASP.NET content requests
❑ How the ASP.NET ISAPI filter transitions the request from the world of IIS into theASP.NET world
Having an understanding of the more granular portions of request processing also sets the stagefor future chapters that expand on some of the more important security processing that occursduring an ASP.NET request as well as the extensibility points available to you for modifyingASP.NET’s security behavior
This book describes security behavior primarily for Windows Server 2003 running IIS6 and ASP.NET Due to differences in capabilities between IIS5/5.1 and IIS6, some of what is described
is not available or applicable when running on Windows 2000/XP Differences in behavior between versions of IIS are noted in some cases.
Trang 30IIS Request Handling
The initial processing of an HTTP request on Windows Server 2003 occurs within both IIS and a ing protocol driver As a result, depending on the configuration for IIS, a request may never make it farenough to be processed by ASP.NET The diagram in Figure 1-1 shows the salient portions of IIS andWindows Server 2003 that participate in request processing
support-Figure 1-1
A request must first make it past the restrictions enforced by the kernel mode HTTP driver: http.sys Therequest is handed off to a worker process where it then flows through a combination of the internalrequest processing provided by IIS and several ISAPI filters and extensions Ultimately, the request isrouted to the appropriate content handler, which for ASP.NET pages is the ASP.NET runtime’s ISAPIextension
static content aspnet_isapi.dll
Worker processw3wp.exe
aspnet_filter.dll
ISAPI filters
http.sysRequest for
default.aspx
asp.dll
Trang 31When an HTTP request is first received by Windows Server 2003, the initial handling is actually performed
by the kernel-mode HTTP driver: http.sys The kernel mode driver has several Registry switches thatcontrol the amount of information allowed in a request URL By default the combined size of the requestURL and associated headers — any query string information on the URL, and individual headers sentalong with the request, such as cookie headers — must not exceed 16KB
Furthermore, no individual header may exceed 16KB So, for example, a user agent could not attempt tosend a cookie that is larger than 16KB (although for other reasons, a 16KB cookie would be rejected byASP.NET anyway) Under normal circumstances the restrictions on headers and on the total combinedsize of the request URL and headers is not a problem for ASP.NET applications However, if your appli-cation depends on placing large amounts of information in the URL — perhaps for HTTP-based asmxWeb Services — then the length limit enforced by http.sysmay come into play
Any application that depends on excessively long request URLs or request headers should, if at all ble, have its logic changed to transmit the information through other mechanisms For a Web Service,this means using Simple Object Access Protocol (SOAP) headers to encapsulate additional request data.For a website, information needs to be sent using a POSTverb, rather than a GETverb
possi-The kernel mode driver restricts the number of path segments in a URL and the maximum length forany individual path segment Examine the following URL:
http://yoursite/application1/subdirectory2/resource.aspx
The values application1, subdirectory2, and resource.aspxrepresent individual path segments Bydefault, http.sys disallows URLs that have more than 255 path segments and URLs where the length of anysingle path segment exceeds 260 characters These constraints are actually pretty generous, because in prac-tice developers normally do not need large number of path segments, even for applications with a fairamount of directory nesting The requested page in the previous example, resource.aspx, is considered apath segment and is subject to the same length restrictions as any portion of the URL However, if therewere query string variables after resource.aspx, the length of the query string variables would applyonly against the overall 16KB size restriction on the combined size of URL plus headers As a result, youcan have query string variables with values that are greater than 260 characters in length
One reason for these size limits is that a number of hack attacks against web servers involve encodingthe URL with different character representations For example, an attacker may attempt to bypass direc-tory traversal restrictions by encoding periods like this:
Trang 32The sequence 1234567890is repeated 26 times in the URL Because the path segment is exactly 260characters though, http.sysdoes not reject the request Instead, this URL results in a 404 from IISbecause there is no foo.htmfile on the system
However, if you add one more character to this sequence, thus making the path segment 261 characterslong, an HTTP 400 - Bad Request error message is returned In this case, the request never makes it farenough for IIS to attempt to find a file called foo.htm Instead, http.sysrejects the URL and additionalIIS processing never occurs This type of URL restriction reduces the load on IIS6, because IIS6 does nothave to waste processor cycles attempting to parse and process a bogus URL
This raises the question of how a web server administrator can track URL requests are being rejected.The http.sysdriver will log all errors (not just security-related errors) to a special HTTP error log file
On Windows Server 2003, inside of the %windir%\system32\LogFilesdirectory, there is an HTTPERR
subdirectory Inside of the directory one or more log files contain errors that were trapped by http.sys
In the case of the rejected URLs, a log entry looks like:
2005-03-13 22:09:50 127.0.0.1 1302 127.0.0.1 80 HTTP/1.1 GET /1234567890 htm 400
- URL
For brevity the remainder of the GETURL has been snipped in the previous example; however, the logfile will contain the first 4096 bytes of the requested URL In this example, the value URLat the end of thelog entry indicates that parsing of the URL failed because one of the path segment restrictions wasexceeded
If the URL is larger than 16KB, the log entry ends with URL_Length, indicating that the allowable URLlength had been exceeded An example of such a log entry is:
2005-03-13 23:02:53 127.0.0.1 1086 127.0.0.1 80 HTTP/0.0 GET 414 URL_Length
-For brevity, the URL that caused this is not included because a 16KB long URL would not be particularlyinteresting to slog through Remember that form posts and file uploads also include a message body thatusually contains the vast majority of the content being sent to the web server Because http.sysonlychecks the URL and associated headers, it does not perform any validation on the size of the messagebody Instead it is ASP.NET that is responsible for limiting the size of raw form post data or file uploads
A subtle point about the previous discussion is that some of the restrictions http.sysenforces are based
on number of characters, while other restrictions are based on byte size In the case of path segments, therestrictions are based on number of characters, regardless of the underlying character set However, forthe 16KB size restrictions, the actual URL or header allowed depends heavily on the characters in theURL or headers If a URL or header contains only standard ASCII characters, a 16KB size limit equates to
16384 characters However, if a URL or header contains characters other than standard ASCII characters,converting from byte size to character length becomes a bit murkier
Because http.sysprocesses URLs as UTF-8 by default, and UTF-8 characters consume between 1 and 3bytes in memory, an allowable URL length could be anywhere from roughly 5461 characters to 16384characters A general rule of thumb when using non-ASCII characters though is to assume 2 bytes percharacter if there is extensive use of Unicode characters, which equates to a maximum URL length(including query string variables) of 8192 characters
Trang 33The character length and byte size restrictions enforced by http.syscan be modified by adding DWORD
values underneath the following Registry key:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters
The specific Registry settings that govern the behavior just discussed are listed in the following table.Also, a server reboot is required after you change any of the following settings
Registry Setting Value Name Description
MaxFieldLength By default, an individual header can be up to 16KB in size
Change this setting to limit the size of any individual HTTPheader A request URL, including query string information, isalso restricted in size by this setting The allowed range ofvalues is 64–65534 bytes
MaxRequestBytes By default, the combined size of the request URL, including
query string, plus its associated HTTP headers cannot exceed16KB The allowed range of values is 256–16777216 bytes
UrlSegmentMaxCount By default, no more than 255 path segments are allowed in a
URL The allowed range of values is 0–16383 segments
UrlSegmentMaxLength By default, an individual path segment cannot be longer than
260 characters The slashes that delimit each path segmentare not included when computing a path segment’s characterlength The allowed range of values is 0–32766 characters
In earlier versions of IIS, the URLScan security tool (available by searching net) provides similar protections for restricting URLs Most of the security functionality of URLScan was incorporated into http.sysand IIS6 There are a few small features that are only available with URLScan though, the most interesting one being URLScan’s ability to remove the server identification header that IIS sends back in HTTP responses.
microsoft.com/tech-aspnet_filter.dll
After http.sysis satisfied that the request is potentially valid, it passes the request to the appropriateworker process In IIS6 multiple application pools can be running simultaneously, with each applicationessentially acting as a self-contained world running inside of an executable (w3wp.exe) Within eachworker process, IIS carries out a number of processing steps based on the ISAPI extensibility mecha-nism Even though ASP.NET is a managed code execution environment, it still depends on the ISAPImechanism for some initial processing
When ASP.NET is installed on a web server, it registers an ISAPI filter with IIS This filter (aspnet_filter.dll) is responsible for two primary tasks:
❑ Managing cookieless tickets by converting them into HTTP headers
❑ Preventing access over the Web to protected ASP.NET directories
5
Trang 34You can see the set of all ISAPI filters that are registered in IIS by using the IIS MMC, right-clicking theWeb Sites node, and then clicking on the ISAPI Filters tab in the dialog box that opens In Figure 1-2, youcan see that there is currently only one ISAPI filter registered by default — the ASP.NET filter.
Depending on your machine, you may see additional filters that provide services such as compression orthat support Front Page extensions
Figure 1-2
By default ASP.NET registers the filter with a Low priority, which means that other filters with higherpriorities will have the opportunity to inspect and potentially modify each incoming request This makessense because if, for example, you are running a filter that decompresses incoming HTTP content, youwould want this type of operation to occur prior to ASP.NET carrying out security logic based on therequest’s contents
The ASP.NET filter handles two ISAPI filter notifications: SF_NOTIFY_PREPROC_HEADERSand
SF_NOTIFY_URL_MAP This means the filter has the opportunity to manipulate the request prior to IISattempting to do anything with the HTTP headers, and the filter has the opportunity to perform someextra processing while IIS is converting the incoming HTTP request into a request for a resource located
at a specific physical path on disk
Processing Headers
The ASP.NET filter inspects the request URL, looking for any cookieless tickets In ASP.NET 2.0, cookielesstickets are supported for session state (this was also available in 1.1), forms authentication (previouslyavailable as part of the mobile support in ASP.NET) and anonymous identification (new in ASP.NET 2.0)
A sample URL with a cookieless session state ticket is shown here:
Trang 35ASP.NET reserves the path segment immediately after the application’s virtual root as the location on theURL where cookieless tickets are stored In this example, the application was called inproc, so the nextpath segment is where ASP.NET stored the cookieless tickets All cookieless tickets are stored within anouter pair of parentheses Within these, there can be a number of cookieless tickets, each starting with asingle letter indicating the feature that consumes the ticket, followed by a pair of parentheses that containthe cookieless ticket Currently, the following three identifiers are used:
❑ S— Cookieless ticket for session state
❑ A— Cookieless ticket for anonymous identification
❑ F— Cookieless ticket for forms authenticationHowever, the ASP.NET filter does not actually understand any of these three indentifiers Instead, the filter searches for the character sequences described earlier Each time it finds such a character sequence,
it removes the cookieless ticket, the feature identifier and the containing parentheses from the URL andinternally builds up a string that represents the set of cookieless tickets that it found The end result isthat all cookieless tickets are removed from the URL before IIS attempts to convert the URL into a physi-cal path on disk Therefore, IIS doesn’t return a 404 error even though there clearly is no directory ondisk that starts with (S)
After the filter removes the tickets from the URL, it still needs some way to pass the information on tothe ASP.NET runtime This is accomplished by setting a custom HTTP header called ASPFILTERSES-SIONID The name is somewhat misleading because it is a holdover from ASP.NET 1.1 when the onlycookieless ticket that was supported (excluding mobile controls and the cookieless forms authenticationsupport that was part of the mobile controls) was for session state With ASP.NET 2.0, though, there areobviously a few more cookieless features integrated into the product Because the underlying logicalready existed in the ISAPI filter, the old header name was simply retained
You can actually see the effect of this header manipulation if you dump the raw server variables associatedwith an ASP.NET request As an example, for an application that uses both cookieless session state andcookieless forms authentication, the URL after login may look as follows:
http://localhost/inproc/(S(sfeisy55occclkmlkcwtjz55)F(jbZ guo1))/Default.aspx
For brevity the majority of the forms authentication ticket has been removed However, the exampleshows cookieless tickets for session state and forms authentication in the URL If you were to dump outthe server variables on a page, you would see the following header:
HTTP_ASPFILTERSESSIONID=S(sfeisy55occclkmlkcwtjz55)F(jbZ guo1)
Hopefully, this sample makes it clearer how the unmanaged ISAPI ASP.NET filter transfers cookieless ticketsover to the ASP.NET runtime Within the ASP.NET runtime, the HTTP modules that depend on these ticketshave special logic that explicitly looks for this HTTP header and parses out the ticket information for furtherprocessing (for example, setting up the session, validating forms authentication credentials, and so on)
7
Trang 36Blocking Restricted Directories
After the filter processes any cookieless tickets, the filter has IIS normalize the request URL’s tion This is necessary because the filter enforces the restriction that browser users cannot request anytype of content from the protected directories in ASP.NET 2.0 Because ASP.NET 2.0 introduced new
representa-“content” that in reality consists of code, data, resources, and other pieces of information, it is necessary
to prevent access to this information via a browser The filter prevents access by scanning the normalizedURL, looking for one of the following paths:
❑ /bin— Compiled assemblies referenced by the application
❑ /app_code— Source code files with classes referenced elsewhere in an application
❑ /app_data— Data files such as xml, mdb, or mdffiles
❑ /app_globalresources— Resources that are globally accessible throughout an application
❑ /app_localresources— Resources that are applicable to a specific directory
❑ /app_webreferences— WSDL files and compiled artifacts for Web Services
❑ /app_browsers— Browser capability files for determining browser functionality
If the filter finds a path segment with one of these paths, the filter returns an error to IIS, which is convertedinto a 404 response and returned to the browser For example, if a web server has a directory immediatelyunder wwwrootcalled app_datawith an HTML file called foo.htm, requesting the following URL stillresult in a 404 even though the file does exist on the file system
http://localhost/app_data/foo.htm
There had been some discussion at one point around having the filter perform a broad blocking of anyURLs that contained the characters /app_at the beginning of a path segment However, this decision wasavoided because some developers may have already been using such a naming prefix in their directorystructures If at all possible, it is recommended that developers move away from naming any directorieswith the /app_ prefix In a future release of ASP.NET, the filter may support blocking any paths that start with these characters — not just the specific set of reserved directories in ASP.NET 2.0
If you have valid reasons for creating directory structures on disk with any of the reserved names notedearlier, you can disable the filter’s directory blocking behavior (although for security reasons this isclearly not recommended) Registry settings to control the directory blocking behavior can be added asDWORD values underneath the following Registry key:
Trang 37Registry Setting Value Name Description
StopBinFiltering Set this value to 1 to stop the filter from blocking
requests to paths that include /bin This settingwill affect all ASP.NET 1.1 and 2.0 applications onthe server
StopProtectedDirectoryFiltering Set this value to 1 to stop the filter from blocking
requests to reserved ASP.NET directories thatinclude a path starting with /app_ Because thissetting is new to ASP.NET 2.0, it will only affect allASP.NET 2.0 applications on the server
Setting either one of these Registry settings will affect all of your websites There is no mechanism to selectively turn off directory blocking for only specific applications or specific websites.
Dynamic versus Static ContentAfter a request has flowed through all of the ISAPI filters configured for a website, IIS decides whetherthe requested resource is considered static content or dynamic content This decision really depends onwhether a custom ISAPI extension has been configured and associated with the file extension of therequested resource For example, if you were to request http://localhost/foo.htm, in the defaultconfiguration of IIS, the htmextension is registered as a type of static content server directly by IIS.The configuration of static versus dynamic content is determined by a combination of settings in IIS6:
❑ MIME type mappings
❑ File extension to ISAPI extension mappings
❑ The presence of wildcard application mappings (if any)
MIME Type Mappings
IIS6 is configured with several well known static file extensions in its list of Multipurpose Internet MailExtensions (MIME) type mappings The reason that MIME type mappings are so important in IIS6 is thatwithout a MIME type mapping, an HTTP request for a file results in a 404 error, even if the file does exist
on the file system For example, if a text file, foo.xyz, exists at the root of a website, requesting
http://localhost/foo.xyzresults in a 404
However, the web server’s allowable MIME types can be edited to allow IIS6 to recognize xyzas avalid file extension In Figure 1-3, the IIS6 MMC is shown being used to register xyzas a valid fileextension
9
Trang 38Figure 1- 3
Right clicking the computer node and selecting Properties pulls up a dialog box that allows you to configure MIME types Click the MIME Types button to access the Mime Types dialog box, where youcan click the New button to add a new MIME type For this example, the xyzfile extension was added
as a being a text type
You need to iisresetfor the changes to take affect When the web server is running again, a request for
http://localhost/foo.xyz works, and IIS6 returns the file’s contents
ISAPI Extension Mappings
Because a web server that serves only static files would be pretty useless in today’s web, ISAPI extensionmappings are available for serving dynamically generated content However, ISAPI extensions can also
be used to carry out server-side processing on static file content For example, there are ISAPI extensionsfor processing server-side include files In practice though, ISAPI extensions are typically used for asso-ciating file extensions with Dynamic Link Libraries (DLLs) that carry out the necessary logic for execut-ing code and script to dynamically generate page output
Trang 39You can see the list of ISAPI extensions that are mapped to a website with the following steps:
1. Right-click the application’s icon in the IIS6 MMC.
2. Select properties
3. In the Directory tab of the dialog box that pops up, click the Configuration button
4. In the Mappings tab of the dialog box that pops up, a list box shows all application extensionscurrently mapped for the web application
In Figure 1-4, the current application has mapped the aspxfile extension to a rather lengthy path thatlives somewhere in the framework installation directory
Figure 1-4The path is too long to see without scrolling around, but it points at the following directory location:
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll
Depending on where you installed the operating system on your machine, the location of %windir%
will vary
11
Trang 40When IIS receives a request for a file, if the file extension for that request is mapped to an ISAPI sion, IIS routes the request to the mapped ISAPI extension instead of consulting the list of MIME typesand serving the file as static content In the case of the aspxfile extension, the request is routed to
exten-aspnet_isapi.dll, which contains the code that bootstraps the ASP.NET runtime and allows ASP.NETpages to run
If you scroll around a bit through the various application extensions, you can see that there are a largenumber of mapped extensions Clicking the Executable Path column sorts the extensions and makes iteasier to see which file extensions are currently mapped to the ASP.NET ISAPI extension Most of theextensions that start with the letter a should be familiar to varying degrees (everyone who writes HTTPhandlers raise your hand!) Several other file extensions are probably familiar to you from working withtools like Visual Studio or SQL Server, but it may not make sense why these file extensions are nowmapped to the ASP.NET ISAPI extension
For example, the various Visual Studio project extensions (.csproj, vbproj) are mapped to
aspnet_isapi.dll Simiarly, SQL Server database extensions (.ldfand mdf) are mapped to
aspnet_isapi.dll From experience though, you know that your ASP.NET web servers have not beenprocessing project files or opening database files and pretending to be a database engine
This leads to another approach of using ISAPI extensions Not only do ISAPI extensions parse and cess files that are mapped to them, but ISAPI extensions can also be configured to handle other file typesfor specific purposes When ASP.NET is installed, file extensions for files that commonly occur within adeveloper’s ASP.NET project are mapped to the ASP.NET ISAPI extension Because XCOPY deployment
pro-is an easy way to move an ASP.NET application from a developer’s desktop onto a web server, there can
be a number of files within the structure of an ASP.NET project that the developer does not want served
to the Internet at large By mapping these file extensions to aspnet_isapi.dll, IIS will pass requestsfor these file types to the ASP.NET runtime Because ASP.NET has a parallel configuration system thatmaps file extensions to specific processing logic (.aspxpages are executed by the ASP.NET page han-dler), ASP.NET can choose to do something other than executing the requested file In the case of fileextensions like csprojor mdf, ASP.NET has a special handler that will deny access to files of this typeand return an error to that effect This technique will be revisited later in the chapter when the defaulthandler mappings for ASP.NET are discussed
Throughout this discussion there has been the implicit assumption that after a mapping between a fileextension and an ISAPI extension is established, dynamic content will start working Although this wasthe case for IIS5 and IIS5.1, IIS6 introduced an extra layer of protection around ISAPI extensions OnIIS6, an administrator must take some kind of explicit action to allow an ISAPI extension to operate IfIIS6 is installed on a Windows Server 2003 machine in its most basic configuration, even though
ASP.NET bits exist on the machine, requests to aspxpages will always fail with a 404 error
The reason for this is that IIS6 has the ability to enable and disable individual ISAPI extension DLLs Ifyou use the Manage Your Server Wizard in Windows Server 2003, it will automatically reenable theASP.NET1.1 ISAPI extension for you when you configure the server in the Application Server role As aresult, when the 2.0 version of the framework is installed on top of it, the ASP.NET 2.0 ISAPI extensionwill be enabled as well
However, if you install the 2.0 version of the framework but are still receiving 404 errors, you need toenable the ASP.NET ISAPI extension Figure 1-5 shows the Web Service Extensions configuration win-dow in the IIS MMC Right-click the ASP.NET extension to access the option to enable the extension