246
MicrosoftSecurity Guidance Training for Developers

2806 Microsoft Security Guidance Training for Developers

Embed Size (px)

Citation preview

Page 1: 2806 Microsoft Security Guidance Training for Developers

Microsoft® SecurityGuidance Trainingfor Developers

Page 2: 2806 Microsoft Security Guidance Training for Developers

Information in this document, including URL and other Internet Web site references, is subject tochange 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 applicablecopyright laws is the responsibility of the user. Without limiting the rights under copyright, nopart of this document may be reproduced, stored in or introduced into a retrieval system, ortransmitted in any form or by any means (electronic, mechanical, photocopying, recording, orotherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectualproperty rights covering subject matter in this document. Except as expressly provided in anywritten license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

2004 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Windows Server, Active Directory, ASP.NET,Explorer, JScript, MSDN, Press, SQL Server, Visual Basic, Visual C++, and Win32 are eitherregistered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of theirrespective owners.

Clinic: 2806APart Number: X10-42504Released: 02/2004

Page 3: 2806 Microsoft Security Guidance Training for Developers

ContentsIntroductionPrerequisites ............................................................................................................2Clinic Outline ..........................................................................................................3Microsoft Learning..................................................................................................4Microsoft Learning Product Types..........................................................................5Microsoft Certified Professional Program...............................................................6Additional Reading from Microsoft Press...............................................................9Facilities ................................................................................................................10Session: Essentials of Application SecurityWhat We Will Cover ...............................................................................................1Session Prerequisites ...............................................................................................2The Importance of Application Security .................................................................3Secure Application Development Practices...........................................................13Security Technologies ...........................................................................................23Secure Development Guidelines ...........................................................................61Session Summary ..................................................................................................65Session: Writing Secure Code � Best PracticesWhat We Will Cover ...............................................................................................1Session Prerequisites ...............................................................................................2Secure Development Process...................................................................................3Threat Modeling ......................................................................................................8Risk Mitigation......................................................................................................22Security Best Practices ..........................................................................................27Demonstration 1: ASP.NET Applications Security...............................................29Session Summary ..................................................................................................51Clinic Evaluation ...................................................................................................55Session: Writing Secure Code � Threat DefenseWhat We Will Cover ...............................................................................................1Session Prerequisites ...............................................................................................2The Need For Secure Code......................................................................................3Defending Against Memory Issues .........................................................................8Defending Against Arithmetic Errors....................................................................15Defending Against Cross-Site Scripting................................................................21Defending Against SQL Injection .........................................................................29Defending Against Canonicalization Issues ..........................................................35Defending Against Cryptography Weaknesses .....................................................41Defending Against Unicode Issues........................................................................44Defending Against Denial of Service ....................................................................48Session Summary ..................................................................................................51

Page 4: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NETFrameworkWhat We Will Cover ...............................................................................................1Session Prerequisites ...............................................................................................2.NET Framework Security Features ........................................................................3Code Access Security ............................................................................................12Role-Based Security ..............................................................................................24Cryptography.........................................................................................................33Securing ASP.NET Web Applications ..................................................................40Securing ASP.NET Web Services.........................................................................48Session Summary ..................................................................................................52Clinic Evaluation ...................................................................................................56

Page 5: 2806 Microsoft Security Guidance Training for Developers

Contents

What We Will Cover 1

Session Prerequisites 2

The Importance of Application Security 3

Secure Application Development Practices 13

Security Technologies 23

Secure Development Guidelines 61

Session Summary 65

Session: Essentials of Application Security

Page 6: 2806 Microsoft Security Guidance Training for Developers

Information in this document, including URL and other Internet Web site references, is subject tochange 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 applicablecopyright laws is the responsibility of the user. Without limiting the rights under copyright, nopart of this document may be reproduced, stored in or introduced into a retrieval system, ortransmitted in any form or by any means (electronic, mechanical, photocopying, recording, orotherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectualproperty rights covering subject matter in this document. Except as expressly provided in anywritten license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

2004 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Windows Server, Active Directory, MSDN, andSQL Server are either registered trademarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of theirrespective owners.

Page 7: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 1

What We Will Cover

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this session, we will focus on security fundamentals. Specifically, we will discuss:

! Why application security matters.! Secure development practices.! The range of security technologies that are available.! How developers should consider security at all stages of the development process.

Page 8: 2806 Microsoft Security Guidance Training for Developers

2 Session: Essentials of Application Security

Session Prerequisites

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 9: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 3

The Importance of Application Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on the importance of application security. Specifically, we will discuss:

! Trustworthy computing.! Connection scenarios and security concerns.! Common types of attacks on software systems.! Examples of security intrusions.! Consequences of poor security.! The challenges involved in secure computing.! The role of developers in creating secure applications.

Page 10: 2806 Microsoft Security Guidance Training for Developers

4 Session: Essentials of Application Security

Trustworthy Computing

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Bill Gates issued a memo in July of 2002 that outlined a high-level strategy to deliver a newstandard of computer systems that are more secure and available.

! During February and March of 2002 all normal feature work on Microsoft Windows® stopped.The entire Windows team worked on improving the security of Microsoft Windows Server� 2003during this time.

! Trustworthy Computing is a serious initiative within Microsoft to improve the security andreliability of computers.

! Because computers are an important component of any business, they need to:

• Be reliable.

• Be able to withstand security attacks.

• Provide a feeling of confidence to both businesses and individuals that their data is secure.! It is important to be aware that not all attacks are external to your enterprise. A common estimate

by security experts is that between 70 and 80 percent of all attacks, security compromises, andmalicious actions originate from within an organization, either by disgruntled or misguidedemployees.

Page 11: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 5

Connection Scenarios and Security Concerns

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Workforce mobility is increasing, and consequently, the way in which employees connect to yourcompany�s network is evolving. Employees connect in a number of different ways, includingtraditional wired connections, new and evolving wireless network standards, and dial-up andbroadband virtual private network (VPN) connections.

! The variety of ways your mobile users connect to your company�s network introduces a number ofsecurity concerns, including:

• Wireless susceptibility. Although wireless networks can be as secure as wired networks ifadministered properly, by default, many wireless networks provide the opportunity for anycompatible device to connect in an ad-hoc manner.

• Employee home security. Many employees have wireless networks at home, and may not beaware of the issues that are involved with securing this type of network. Furthermore, always-on broadband connections make home networks (whether wireless or not) more susceptible toviruses and attackers. The potential susceptibility of home networks may result in viruses orattackers gaining access to your corporate network, either when the user connects over a VPNor when they physically plug their computers into the network on your company�s premises.Although virus checkers and firewalls can help secure home networks and broadbandconnections, it is often difficult for your network administrators to enforce the use of thesedefences.

! Employees increasingly use their laptop computers and other mobile devices to connect towireless networks run by third parties. For example, they might connect to WiFi hotspots in coffeehouses, airports, hotels, and other places to check their e-mail or to browse the Internet. Becauseyour company has no control over the security of these public networks, they provide a potentialroute for attackers or viruses. As with home networks, this may result in viruses or attackersgaining access to your corporate network, either when the user connects over a VPN or when theyphysically plug their computers into the network on your company�s premises.

Page 12: 2806 Microsoft Security Guidance Training for Developers

6 Session: Essentials of Application Security

! Applications are becoming increasingly dependant on connections to the Internet, for updateddata, Web services, and so on. The Internet is a potential route to your systems for attackers andviruses.

! Many businesses require a persistent connection to the Internet so that they can provide Web sites,File Transfer Protocol (FTP) site, and Web services. As already stated, the Internet is a potentialroute to your systems for attackers and viruses.

! Security attacks will also still happen from within your enterprise. This could be as simple as anemployee who writes down a password which then falls into the wrong hands, or it could bedeliberate actions from a disgruntled employee. It is important to remember that security is not justrequired for public facing connections.

Page 13: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 7

Common Types of Attacks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Organizational attacks involve one organization breaking into your network to try to accessconfidential information, thereby gaining a business advantage.

! Attackers like to exercise their skill in attempting to bypass security safeguards to gain illegalaccess to your network.

! Automated attacks use software to scan for network vulnerabilities, or to implement a brute forceattack. Brute force attacks involve trying many different usernames and passwords or othercredentials to gain access to your resources.

! Denial of Service attacks overwhelm a server with requests for action, thereby rendering itincapable of providing its normal service.

! Viruses, Trojan horse, and worms are harmful programs that act by exploiting some knownvulnerability to install themselves on a computer (perhaps by entering as an attachment to an e-mail). Once present on a computer, they distributes copies of themselves to other connectedcomputers, and these copies also replicate themselves, resulting in a viral-like infection of thecomputer network.

! Accidental breaches in security often result from poor practices or procedures. For example, theexposure of security information, such as usernames and passwords, can be exploited by anattacker to gain access to your network.

Page 14: 2806 Microsoft Security Guidance Training for Developers

8 Session: Essentials of Application Security

Examples of Security Intrusions

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! CodeRed is a worm that:

• Uses randomly generated IP addresses to spread. If the worm infects a vulnerable IIS server, itcreates 100 threads first. Out of those initial 100 threads, it uses 99 threads to spread the wormwhile the 100th thread checks to see if it is running on a English (U.S.) MicrosoftWindows NT® or Windows 2000 system. If the infected system is found to be an English(U.S.) system, the worm will proceed to deface the infected system�s website.

• Exploits an unchecked buffer overrun in Microsoft Index Server 2.0, a component of InternetInformation Services (IIS) servers.

• Includes code designed to overwhelm the www.whitehouse.gov website.! ILOVEYOU is a virus that:

• Is contained in an e-mail attachment called LOVE LETTER FOR YOU.TXT.VBS (a VisualBasic Script file).

• Relies on the e-mail recipient opening the attachment.

• Deletes image files and MP3 files.

• Corrupts the registry.

• Spreads by copying the e-mail to all users in the address book.

Page 15: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 9

! Nimda is a virus that:

• Spreads itself in e-mail attachments named README.EXE.

• Locates EXE files on the local computer and infects them by copying the virus file inside theirbody as a resource. These files then spread the infection when users exchange programs suchas games.

• Scans the Internet for vulnerable servers and defaces Web pages on those servers, leading tofurther propagation of the worm through users browsing the infected sites.

• Infects network shares, causing any user who opens a Word document on those shares tobecome infected.

• Reads e-mail addresses from your e-mail client and also searches local HTML files looking foradditional addresses. It then sends one e-mail to each address containing the README.EXEattachment.

Page 16: 2806 Microsoft Security Guidance Training for Developers

10 Session: Essentials of Application Security

Consequences of Poor Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Poor security will result in serious damage to your business.! Your competitors may gain knowledge of your systems or technology, denying you any

competitive advantage. Competitors may also be able to copy your ideas or technology and putthem to advantage in their own products.

! An attack may result in your systems being taken offline while the damage is assessed andrectified.

! All effort expended combating security attacks and repairing the damage is lost productivity. Thistime and effort could have been spent pursuing the business goals of your enterprise.

! Your business reputation will be damaged. When security lapses are reported, the assumption isthat if your systems security is bad, then many of your other practices will also be bad. It is easy tocome to the conclusion that your products and systems are equally poor.

! Consumers who are unable to use your website because it has been hacked, or who see a defacedwebsite, will visit your competitors� websites instead.

! The financial losses from security intrusions can be substantial. It is difficult to determine theexact cost of issuing a security fix, but the Microsoft Security Response Center believes a securitybug that requires a security bulletin costs approximately $100,000.

Page 17: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 11

Challenges When Implementing Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The challenges faced when implementing security include balancing the advantages that theattacker has over the defenders, and how the degree of security affect users, as well as conveyingthe message that security does add business value.

! Attackers vs. Defenders:

• The defender must protect all points; the attacker can choose the weakest point.

• The defender must be constantly vigilant; the attacker can attack at any time.! Security vs. Usability:

• Security can be taken to extremes, making the application too difficult to use. Securedevelopers should strive to make the system as secure as possible, but not to make itimpossible to use.

• Complex and strong passwords are those that must contain a mixture of uppercase andlowercase letters, and possibly punctuation characters. They must also be long � perhaps 9 ormore characters in length.

• However, there is often user resistance to strong passwords, because they are more difficult toremember. As soon as a user decides to write down a password so that they can remember it,your security is compromised.

! Security As An Afterthought:

• Security is often seen as a functionality disabler, as something that gets in the way. However,there is nothing more disabling than an attacker being able to get at your sensitive data. Thereis also a perception that the cost of implementing security is high and the business benefits areunclear. However, the cost of poor security can be very high, and in exceptional circumstances,could result in business failure.

• Building security in from the start is essential to ensure a robust solution. If security is the lastissue addressed, fixing of any security vulnerabilities that are discovered may break otherproduct functionality, and in common with any other late changes in the product developmentcycle, it is much more expensive than if security is designed in the first place.

Page 18: 2806 Microsoft Security Guidance Training for Developers

12 Session: Essentials of Application Security

The Developer Role in Application Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Solution architects, developers, and systems administration personnel must all work together andtake collective responsibility for security.

! Developers must adopt good practices that ensure the production of secure software. They must beknowledgeable about security vulnerabilities and how to avoid them, and must have both a broadand deep knowledge about security technologies and how to use them in order to create securesolutions.

Page 19: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 13

Secure Application Development Practices

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will cover how to adopt secure application development practices. Specifically, wewill discuss:

! A holistic approach to security.! Security throughout the project lifecycle.! The SD3 security framework.! Threat modeling.! Ongoing education.! Input validation.! How to improve security practices.

Page 20: 2806 Microsoft Security Guidance Training for Developers

14 Session: Essentials of Application Security

Holistic Approach to Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! A holistic approach to security is required. You must consider security at all project stages and fornetwork, host, and application layers.

! Even if you have the most secure network infrastructure possible, with completely hardenedservers, a simple vulnerability in your application (for example, failing to validate input) rendersall of that useless. A holistic approach to security is simply a mindset that developers should adopt.It forms the basis for specific architectures, such as Defense in Depth (DiD), which is explained inthe �Writing Secure Code � Best Practices� presentation.

! In short, you need to "bake security into your application development lifecycle". For step-by-stepguidance on how to achieve this, refer to the Patterns and Practices documentation athttp://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMFastTrack.asp

Page 21: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 15

Security Throughout Project Lifecycle

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! It is crucial that security is built into the entire development lifecycle from architecture and design,through development, testing, deployment, and operations.

! The activities shown on this slide are iterative and ongoing. These activities are not one-offactivities � they continue throughout the development lifecycle.

Page 22: 2806 Microsoft Security Guidance Training for Developers

16 Session: Essentials of Application Security

The SD3 Security Framework

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The Secure Windows Initiative team at Microsoft has adopted a simple set of strategies calledSD3. The SD3 framework has three core concepts: Secure by Design, Secure by Default, andSecure in Deployment. These concepts have shaped the development process to help deliversecure systems.

! Secure by Design means that you have taken the appropriate steps to ensure that the overall designof the product is secure from the outset. Include threat modeling at the design phase andthroughout the project to identify potential vulnerabilities. Use secure design, coding, and testingguidelines.

! Secure by Default means that the product is released so that it is secure out of the box. If featuresare optional, and you can turn them off by default. If a feature is not activated, then an attackercannot use it to compromise your product. Ensure that only the least amount of privilege isrequired by user accounts to run your application. Then a compromise can have less seriousconsequences than if an attacker is able to run malicious code under an account with administratorprivileges. Ensure that effective access controls are in place for resources.

! Secure in Deployment means that the system is maintainable after installation. If a product isdifficult to administer, it makes it more difficult to maintain protection against security threats asnew ones evolve. Ensure that users are educated to use the system in a secure manner. If a securityvulnerability is discovered and a patch is necessary, ensure that the fix is fully tested internally andthen issued in a timely manner.

Page 23: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 17

Threat Modeling

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! You cannot build a secure system until you understand your threats, because you will not knowwhat to defend against.

! Threat modelling is covered in more detail in the �Writing Secure Code � Best Practices�presentation.

! The threat modelling process is as follows:1. Assemble the threat-modeling team.

2. Decompose the application and analyze its operation by using data flow diagrams (DFD) orsimilar.

3. Examine the data flows and use cases and determine the threats to the system.

4. Rank the threats by decreasing risk.

5. Choose how to respond to the threats.

6. Choose techniques to mitigate the threats.

7. Choose the appropriate security technologies for the identified techniques.

Page 24: 2806 Microsoft Security Guidance Training for Developers

18 Session: Essentials of Application Security

Ongoing Education

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! An important part of delivering secure systems is raising awareness of the needs for secureprogramming and keeping all users up to date with ongoing security education.

! It is important for all team members to understand how security technologies work. Without thatknowledge, you cannot be an effective team member when taking part in threat modelling, or indoing security code reviews.

! However, understanding security technologies on their own does not mean that your application issecure. It is important not only to know how the technologies work, but how to use them to solvesecurity problems.

! It is essential that programmers know what flawed code looks like so that they can pick upvulnerabilities in code reviews.

! Developers need to be fully aware of common security mistakes and know how to avoid or rectifythem.

! Analysis of any vulnerable code is important so that the same mistake can be avoided in the future,and similar vulnerabilities elsewhere in the product can be identified and resolved.

Page 25: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 19

Input Validation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Many security vulnerabilities result from a failure to validate inputs. All too often, developersimplicitly trust users to type in the �right� thing and do not add software checks to ensure that theyhave done so.

! Buffer Overruns are one of the most common type of input vulnerability. It occurs when a bufferhas been reserved to store an input value, but the input value supplied exceeds the length of thebuffer. When the input value is copied into the buffer, it overwrites the memory around it. This canbe exploited by attackers to change the execution path of the running program, which can be usedto bypass security safeguards on the computer, allowing the intruder to run arbitrary code.

! An SQL injection occurs when an unchecked input string is used in an SQL statement directed to adatabase. For example, a program may ask for input of a name to look up in a database, and builda statement such as �Select * from authors where name = � + input. If the input entered is �Smith�then the statement executes as expected, but if the input is �Smith� drop table authors --�, thendeletion of the table in the database occurs.

! Cross-site scripting is a flaw that affects web pages. It can be used to steal data in cookies, whichan attacker can then use to spoof the user (pretend to be them) to then access personal data that isheld on websites that normally only that user could access. It can also be used to execute arbitrarycode on the victims computer.

! Developers must validate all user-input to avoid these types of security vulnerabilities.

Page 26: 2806 Microsoft Security Guidance Training for Developers

20 Session: Essentials of Application Security

Demonstration 1: Buffer Overruns

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will demonstrate how unchecked input can allow an attacker to bypassapplication security.

You will show the code for a class that is used to set and get personal details. You will point out thesecurity features written into the code for the class. You will then exploit a buffer overrun to showhow an attacker could bypass the security and retrieve details that they are not authorized to read.

Bypassing Security Checks1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, with a password of Passw0rd.

3. Start Notepad. Click Format � Font and switch to a 16 point font size.

4. Click File � Open and open the file C:\Courses\DeveloperSecurity\Democode\Session01\BufferOverrun\Bufferoverrun.cpp.

5. Open a Command Prompt window, and use the properties on the command menu to set theFont to 10x18.

6. At the command prompt, type cd c:\courses\developersecurity\democode\session01\bufferoverrun and press ENTER.

7. Type bufferoverrun and press ENTER.Note: All the following commands are case sensitive, so type them as shown.

8. At the prompt, type GetSensitiveData secret and press ENTER.

Page 27: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 21

9. Enter ChangeAddress 0123456789hacked

10. Enter GetSensitiveData hacked

11. Type exit and press ENTER to quit the program.

12. Switch to the Notepad window.

13. Close Notepad and the command window.

Page 28: 2806 Microsoft Security Guidance Training for Developers

22 Session: Essentials of Application Security

Practices for Improving Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Adopt threat modeling to identify security vulnerabilities at the design phase. This may also haveunexpected benefits, such as increased awareness of the internals of your application (not justsecurity internals) for all members of the team. It also serves as a good way of getting newmembers of the team up to speed.

! Ongoing education is a crucial component of a secure development infrastructure. Developersmust know how to recognize security defects and how to mitigate them. Developers must have agood working knowledge of security technologies and their correct application.

! Code reviews are also a crucial component of good security practice. Use your knowledge ofcommon security vulnerabilities to focus attention on anywhere untrusted input is used unverified,or accesses the network. Check that external connections are properly authenticated and check thatdatabases are accessed by using correct authentication (do not access the database server by usingthe sa account.) Also be aware of processes that are running with unnecessary elevated privileges.

! Use automated test tools to test for security vulnerabilities. Do not forget the best tool of all: yourexperience and intellect. Continuing threat modeling, code reviews, and security reviews help tofocus developers attention, and keep them focused on security issues.

! Secure communications solutions such as SSL/TLS or IPSec, and cryptographic libraries such asCAPICOM or the Microsoft .NET Crypto libraries are tried and tested. A solution built with thesewill, on the whole, be robust and reliable.

! Consider migrating to managed code if you have a large base of unmanaged C/C++ code. Many ofthe common security vulnerabilities such as buffer overruns are prevented by the commonlanguage runtime execution engine, and .NET offers additional benefits, such as additionalsecurity technologies like code access security.

! Use existing, proven solutions when implementing secure code. It is usually a mistake to do low-level cryptographic programming, since such solutions are always complex and often flawed.

Page 29: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 23

Security Technologies

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will review security technologies. Specifically, we will discuss:

! Encryption.! Hashing.! Digital signatures.! Digital certificates.! Secure communication.! Authentication.! Authorization.! Firewalls.! # $%&'&!()

! Service Packs and Updates.

Page 30: 2806 Microsoft Security Guidance Training for Developers

24 Session: Essentials of Application Security

Overview of Security Technologies

*****************************ILLEGAL FOR NON-TRAINER USE******************************

This section of the presentation reviews the different security technologies that are available. Abroad understanding of these technologies is important for you as a developer, so that you have thegrounding you need to take part in threat modeling, develop secure software, and to performeffective code reviews.

Page 31: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 25

Encryption

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Encryption protects data from being viewed or modified, and provides secure channels ofcommunication over otherwise insecure channels. For example, data can be encrypted by using acryptographic algorithm, transmitted in an encrypted state, and later decrypted by the intendedparty. If a third party intercepts the encrypted data, it is difficult to decipher the data.

! Encryption is used for:1. Confidentiality: Protect a user�s identity or data from being read.

2 Data integrity: Protect data from being altered.

3. Authentication: Verify that data originates from a particular party.

! There are two basic types of encryption:1. Symmetric.

2. Asymmetric.

! These types of encryption are described in the following slide.

Page 32: 2806 Microsoft Security Guidance Training for Developers

26 Session: Essentials of Application Security

Symmetric vs. Asymmetric Encryption

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Symmetric encryption performs a transformation on data, preventing third parties from reading thedata. This type of encryption uses a single shared, secret key to encrypt and decrypt data.Symmetric encryption is very fast and does not consume a tremendous amount of resources.

! Common algorithms for symmetric encryption include:1. Data Encryption Standard (DES).

2. Triple DES.

3. Advanced Encryption Standard (AES).

4. International Data Encryption Algorithm (IDEA).

5. RC2.

! Asymmetric encryption also performs a transformation on data, preventing third parties fromreading the data. With this type of encryption, a key pair is used to encrypt and decrypt data. A keypair consists of two parts: a public key and a private key. These two keys are mathematicallyrelated. Although asymmetric encryption consumes more resources than symmetric encryption, itis a far more secure approach.

! Common algorithms for asymmetric encryption include:1. Rivest, Shamir, and Adleman (RSA).

2. Diffie-Helman.

3. Digital Signature Algorithm (DSA).

Page 33: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 27

Verifying Data Integrity with Hashes

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Hashing differs from encryption. Put simply, encryption is the process of encoding data so that atsome point it will be decrypted. Hashed data, on the other hand is not designed to be decrypted.Instead, the hashed values are simply used to verify that that the data is valid.

! A hash is a unique, fixed-length string of bits. Hashing data involves matching an arbitrarily longstring of bits with a fixed-length string of bits. For example, matching a 50-kilobyte file with a160-bit hash value. Hashes must be one-way operations and collision-resistant.1. To be a one-way operation, it must be computationally unfeasible to determine the input

data from just the hash value.

2. To be collision-resistant, it must be computationally unfeasible to find two sets of input datathat result in the same hash value.

! As shown on the slide, when User A sends the hash value and the original data, User B can verifythe validity of the data by applying the same hash algorithm to the data and then comparing theresulting hash value to the hash value that is sent with the data. If the hash values match, User Bcan be assured that nobody has tampered with the data since it was first sent.

! Common hash functions include:1. Message Digest 4 (MD4).

2. Message Digest 5 (MD5).

3. Secure Hash Standard (SHA-1).

Page 34: 2806 Microsoft Security Guidance Training for Developers

28 Session: Essentials of Application Security

Digital Signatures

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Digital signing ensures that data originates from a specific party by creating a digital signature thatis unique to that party. This process also uses hash functions. Put simply, digital signaturescombine hashing (for the validation of the signature data) with asymmetric encryption forencoding that signature data.

! The following occurs when data is signed with a digital signature:1. A hash algorithm is applied to the data to create a hash value.

2. The hash value is encrypted with User A�s private key, thereby creating the digitalsignature.

3. The digital signature and the data are sent to User B.

! The following occurs when digitally signed data is decrypted:1. User B decrypts the signature by using User A�s public key and then recovers the hash

value. If the signature can be decrypted, User B knows that the data came from User A (orthe owner of the private key).

2. The hash algorithm is applied to the data to create a second hash value.

3. The two hash values are compared. If the hash values match, User B knows that the data hasnot been modified.

Page 35: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 29

How Digital Certificates Work

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Although digital signatures ensures that data originates from a party who have access to a privatekey, it does not guarantee that party's identity. For example, an attacker might have obtained aprivate key that belongs to Microsoft. They could then use that key along with a standard hashingalgorithm to sign some data, implying that the source of the data is Microsoft. A digital certificateprevents this electronic identity theft by verifying that the signature does indeed belong to thepublisher. The data and signature can now be verified as belonging to the authorized publisherbecause the trusted CA has verified the publisher owns both the public and private key.

! The following process occurs with digital certificates:1. A user, computer, service, or application creates the public/private key pair.

2. The public key is transmitted to the certification authority (CA) by using a secure networkconnection.

3. The certified administrator reviews the certificate request to verify the information.

4. Upon approval, the certified administrator signs the public key with the private key of theCA.

! Common uses of certificates include:1. 802.1x wireless communication

2. Digital certificates

3. Encryption File System (EFS)

4. Internet authentication

5. IP Security (IPSec)

6. Secure e-mail

7. Smart card logon

8. Software code signing

9. Software restriction policy

Page 36: 2806 Microsoft Security Guidance Training for Developers

30 Session: Essentials of Application Security

Secure Communication � Technologies

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Secure communication technologies are proven solutions that use encryption techniques to protectprivacy and integrity of data across a network.

! The following technologies and standards protect data across networks:1. IPSec (Internet Protocol security). IPSec is a framework of open standards that you can use

to ensure secure, private communications over IP networks by using a combination ofcryptographic security services that are negotiated between the client and server. IPSec isbuilt by using other encryption standards, including symmetric algorithms such as DES,Triple DES, and RC5, and hashes such as MD5 and SHA-1. IPSec provides a transport-levelsecure communication solution and can be used to secure the data that is sent between twocomputers, such as an application server and a database server.

2. SSL (Secure Sockets Layer). The advantage of SSL is that it lends itself to applications thatrequire a trust relationship, because each request or response is validated by the authority ofthe certificate. When you use SSL, either the server or the client has a digital certificate thatthey have obtained from a third party. This certificate is passed to your application withrequests.

Page 37: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 31

3. TLS (Transport Layer Security). TLS is the only security option available when serversneed to prove their identity to anonymous clients. This is important for websites that want toparticipate in e-commerce, because it allows the secure transmission of sensitiveinformation, such as credit card numbers.TLS requires that all servers prove their identity to clients. Additionally, TLS provides theoption of having clients prove their identity to servers.This mutual authentication can be used to restrict who has access to certain Web pages in alarge corporate intranet. TLS is the best choice for environments where you want the highestlevel of security for the data in transit.

4. Remote Procedure Call (RPC) Encryption protocol. Distributed Component Object Model(DCOM) used RPC protocol to provide packet-level privacy authentication, which causesevery packet of data sent between client and server to be encrypted. The RPC runtime stubsand libraries manage most of the details relating to network protocols and communication.This enables you to focus on the details related to the application rather than the detailsrelated to the network.

! IPSec and TLS are explained in the next two slides.

Page 38: 2806 Microsoft Security Guidance Training for Developers

32 Session: Essentials of Application Security

Secure Communication � How IPSec Works

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The primary goal of IPSec is to protect IP packets. IPSec is based on an end-to-end securitymodel, which means that the sender and the recipient are the only hosts that must know about theIPSec protection. Each computer handles its own security, under the assumption that the mediumover which the communication takes place is not secure. IPSec uses symmetric algorithms toencrypt data and transmits symmetric keys by using asymmetric algorithms.

! When a computer configured with an IPSec policy attempts to communicate with anothercomputer, the following occurs:1. The two computers agree on a set of algorithms and hashes.

2. The computers then exchange public keys and use them to exchange symmetric keyalgorithms that are used to encrypt packets at the network layer.

Page 39: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 33

Secure Communication � How SSL Works

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! SSL encryption relies on the server�s public key and private key. The private key exists only onthe Web server and it is used by the Web server to encrypt and decrypt secure messages. Thepublic key exists on any client computer that has installed a certificate for that Web server. Afterthe public key is installed, the user can send encrypted messages to, and decrypt messagesreceived from, the Web server.

! When SSL is used, the following occurs:1. The user browses to the secure Web server�s site.

2. The browser creates a unique session key and encrypts it by using the Web server�s publickey, which is generated from the root certificate. Each session key that the Web server�scertificate generates is unique. Therefore, even if an attacker has the same certificateinstalled on their browser, the attacker cannot decrypt the message. The browser where theencrypted message originated cannot decrypt the message. Only the Web server with theappropriate private key can decrypt the message.

3. The Web server receives the message and decrypts it by using its private key. This phase ofSSL communication is often called the SSL handshake. An attacker may intercept amessage protected with SSL. However, the attacker cannot decrypt the message, because theattacker does not have the Web server�s private key.

4. After the connection is established, all communication between the browser and the Webserver is secure.

! When the session ends, the session key is destroyed.

Page 40: 2806 Microsoft Security Guidance Training for Developers

34 Session: Essentials of Application Security

Demonstration 2: SSL Server Certificates

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will show how to request and install a trial server certificate.

IMPORTANT: This demonstration involves requesting an SSL Certificate from Verisign usingtheir Web site. Consequently, this demonstration requires that the host PC has a live Internetconnection and that you can access your mail with a Web browser.

Additionally, the certificate is sent by e-mail. To avoid the demonstration being dependant on thise-mail, you should run through the following sections of this demonstration before the live delivery:1. Generating a Certificate Request

2. Requesting a Trial Certificate

Run through these sections exactly, but provide your own e-mail details so that you can retrieve thee-mail sent from Verisign. When you receive the certificate by e-mail, store its contents in a textfile"c:\Verisign Trial server ID.txt" in the London virtual machine. The last part of this demonstration,Installing the SSL Certificate, will use this file. The trial certificates will last for 14 days, so youcan do this at any time in the 14 days prior to the delivery of the demonstration. If you re-run thedemo at a future date ensure that the trial certificate is still valid, otherwise step through this processagain to receive a new trial certificate.

Page 41: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 35

Viewing a Web Site on a Non-Secure Server1. If you are not already logged on, log onto London by using the OrdinaryUser account with a

password of Passw0rd.

2. Open Internet Explorer.

3. If you are prompted about enhanced security configuration, select the In the future, do notshow this message checkbox and click OK.

4. Browse to http://london/SecDev/SecureWebsite.

5. Change the URL to https://london/SecDev/SecureWebsite.If you are prompted with a security alert, select the In the future, do not show this warningcheckbox and click OK.

6. Close Internet Explorer.

Generating a Certificate Request1. Open Internet Information Services Manager. Do this by clicking Start � Run� and

entering:runas /env /user:London\Administrator "mmc %windir%\system32\inetsrv\iis.msc"

2. Enter a password of P@ssw0rd when prompted.

3. Expand your Web server and select Default Web Site.

4. Right-click the Web site, and then click Properties.

5. Click the Directory Security tab.

6. Click the Server Certificate button to launch the Web Server Certificate Wizard.

7. Click Next on the Welcome page.

8. Click Create a New Certificate, and then click Next.

9. Click Next.

10. Accept the default for the descriptive name for the certificate in the Name field.

11. Accept default of 1024 for the bit length for the key in the Bit length field, and then click Next.

12. TypeContoso <mm>_<dd>_<yy>_<hh>_<nn>_<initials> in the Organization field where:<mm> is the current month<dd> is the current day<yy> is the current year<hh> is the current hour<nn> is the current minute<initials> are your initials.For example Contoso 01_25_04_09_45_mh

13. Type Sales Department in the Organizational unit field, and then click Next.

14. Accept default of london for the Common name for your site, and then click Next.

15. Select US (United States) for Country/Region.

16. Enter Washington for State

Page 42: 2806 Microsoft Security Guidance Training for Developers

36 Session: Essentials of Application Security

17. Enter Redmond for City.

18. Click Next.

19. Accept the default of c:\certreq.txt for the filename. Click Next.

20. Click Next, then Finish.

21. Click OK in the main properties dialog box.

22. Open c:\certreq.txt in Notepad. (Set Font to Lucida Console, Bold 16 point).

23. Copy the contents of the text file to the clipboard

24. Do not close Notepad after viewing it.

Requesting a Trial Certificate1. SWITCH TO THE HOST MACHINE

2. Open Internet Explorer.

3. Enter www.verisign.com in the Address bar.

4. If Internet Explorer blocks the content from this site click Add, then on the Trusted Siteswindow, click Add again, then Close.

5. Click the SSL Trial ID link on the Verisign home page. If a warning window appears,informing that you are about to view information over a secure connection, click OK. If awindow appears warning that Revocation data is not available, click OK.

6. If prompted, add https:/www.verisign.com to the Trusted Sites list.

7. Fill in the requested information:

a. First Name: Secure,b. Last name: Developer,c. Email: <An Email Address that you can access using a Web browser, such as hotmail>d. Company: Contoso,e. Phone: 0123456789 ,f. State: Washington,g. Zip: 98052,h. Country: United States.i. Click Research Only for Your need for Server Security Is:j. Click Unknown for the budget question,k. Research Only for the Number of Servers question.

8. Finally uncheck the two checkboxes on the Web page, and then click Submit.

9. On the opening page of the Enrollment process, click Continue.

10. The page titled Step 1 of 5 appears. The next page asks if you have generated a CSR request.You have already done that, so click Continue.

Page 43: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 37

11. Paste the contents of the clipboard into the Textbox. Click Continue.

12. If prompted, add https://digitalid.verisign.com to the Trusted Sites zone in the same way asyou did previously.

13. Step 3 of 5. Do not fill in the Technical Contact details. Click Accept.

14. An error page appears.

15. Fill in imaginary data for the technical contact, following the rules shown next to each field.Click Submit again.

16. A page displays informing that the certificate will be sent by email.

17. If you are running this as the preparatory steps before presenting the demo, access your email toretrieve the certificate that Verisign will send you. Copy the entire contents of the email to a textfile and save it to the host machine in a text file called Verisign Trial Server ID.txt. Beforecommencing the demo for real, copy the text file to the root of the C:\ drive in the Londonvirtual machine. DO NOT complete the rest of the demo.

18. If you are running this demo for real, simply proceed to the next section.

Installing the SSL Certificate1. SWITCH TO THE LONDON VPC

2. In Notepad, open the file "c:\Verisign Trial server ID.txt" which contains the text of theemail you received from Verisign.

3. Select the certificate text near the end of the e-mail (including the Begin and End lines). PressCTRL+C to copy it to the clipboard.

4. Click File � New

5. Paste the copied text into the new file.

6. Click File � Save. Set the file type to AllFiles. Enter the filename certres.cer � note the errorwhen you try to save it to c:\.

7. Save the file in My Documents instead, using the filename of certres.cer

8. Switch to the Internet Information Services Manager window.

9. Expand your Web server and select the Default Website Web site.

10. Right-click the Web site and then click Properties.

11. Click the Directory Security tab.

12. Click the Server Certificate button to launch the Web Server Certificate Wizard.

13. Click Next on the Welcome page.

14. Select Process the pending request and install the certificate.

15. Click Next.

16. Click Browse.

17. Navigate to C:\Documents and Settings\OrdinaryUser\My Documents.

Page 44: 2806 Microsoft Security Guidance Training for Developers

38 Session: Essentials of Application Security

18. Select the certres.cer file and click Open.

19. Click Next.

20. Accept default of port 443 for SSL.

21. Click Next.

22. Click Next to install the certificate.

23. Click Finish.

24. Click OK.

Testing the SSL Certificate1. Open Internet Explorer and navigate to https://london/SecDev/SecureWebsite. The browser

shows a security alert warning.

2. Click View Certificate and point out that it has been issued for testing only.

3. Click the Certification Path tab, and show that the certificate is OK.

4. Click OK.

5. Click Yes. You do want to proceed for the purposes of this demo.

6. Close all applications

Page 45: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 39

Authentication � Purpose of Authentication

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Authentication is the process of obtaining user identification credentials, such as a name and apassword, and then validating those credentials against some authority, such as a database. If theidentification credentials are valid, the user that submitted the credentials is considered to be anauthenticated user.

! If you provide a secure communications channel, but then do not check who is using it, you couldsimply be creating an effective, hidden channel for an attacker to use to attack you, with theencrypted communications channel effectively concealing what the attacker is doing.

Page 46: 2806 Microsoft Security Guidance Training for Developers

40 Session: Essentials of Application Security

Authentication � Authentication Methods

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The following are the most commonly used methods of authentication:1. Basic authentication: Users submit user names and passwords in clear text.

2. Digest authentication: Similar to basic authentication, but a hash of the password is sentacross the network, and not the password itself.

3. Digital signatures and digital certificates: Allow servers and clients to authenticate eachother.

4. Integrated Authentication: Uses a cryptographic exchange to confirm the identity of the useras an authenticated Windows principal.

a. Kerberos authentication: Supports mutual authentication and enables credentials to bedelegated across processes. Also provides improved reconnection time; If a user isauthenticated by a server and then disconnects but reconnects in the default time of eighthours, the user does not need to be re-authenticated.

b. NTLM: Used for computers that are not participating in a domain, such as stand-aloneservers and workgroups, or for pre-Windows 2000 computers.

5. Microsoft Passport: Passport authentication is a centralized authentication service providedby Microsoft that offers a single logon and core profile services for member sites. Thisbenefits the user, because they no longer have to log on separately to access new protectedresources or sites.

6. Biometrics: This includes devices that recognize particular biological features of a user,such as finger prints, voice recognition, and retina scans.

! Basic authentication, digest authentication, client digital certificates, integrated authentication, andKerberos v5 are covered in more detail in the following slides.

Page 47: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 41

Authentication � Basic Authentication

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Basic Authentication is a simple authentication protocol defined as part of the HTTP 1.0 protocoldefined in RFC 2617 (see http://www.ietf.org/rfc/rfc2617.txt).

! It is used to authenticate the client, but not the server.! Supported by nearly all Web servers and Web browsers.! Basic Authentication is easily set up on an IIS server. It is enabled by checking the Basic

Authentication check box in the Authentication Control settings in the website properties.! By default, IIS validates the username and password against Windows user accounts that are

stored in the local store or in the Microsoft Active Directory® directory service. However, it ispossible to write custom Basic Authentication handlers that validate credentials against data in adatabase or some other custom store.

! Used on its own, it is extremely insecure, since the username and password are transferred fromthe client to the server using base-64 encoding, which is trivial to decode. Consequently, thistechnique is only of value when combined with a secure communications channel, typicallySSL/TLS.

! Resources: http://msdn.microsoft.com/library/en-us/vsent7/html/vxconIISAuthentication.asp

Page 48: 2806 Microsoft Security Guidance Training for Developers

42 Session: Essentials of Application Security

Authentication � How Digest Authentication Works

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Digest authentication, introduced with IIS 5.0, is similar to Basic authentication except that insteadof transmitting the user's credentials unencrypted from the browser to the Web server, it transmitsa hash of the credentials. As a result, it is more secure, although it requires an Microsoft InternetExplorer 5.0 or later client and specific server configuration.

! When a client makes a request for content that is authenticated by using Digest authentication, thefollowing sequence of events takes place:1. The client browser requests the content.

2. The server responds with a challenge for the client to supply a digest.

3. The client requests a username and password from the user. The client concatenates thepassword with data known to both the server and the client in order to create a string that isthe correct number of characters required by the digest algorithm (also called a hashalgorithm). The client then applies a digest algorithm (specified by the server) to thecombined data.

4. The client sends the resulting digest to the server as the response to the challenge.

5. The server uses the same process as the client to create a digest by using a copy of theclient's password it obtains from Active Directory, where the password is stored by usingreversible encryption.

6. If the digest created by the server matches the digest created by the client, IIS authenticatesthe client.

! Digest authentication requires that the IIS 5.0 server also be a Windows 2000 domain controller. Italso requires that you use Internet Explorer 5.0 as your browser.

! Digest authentication encrypts client-supplied passwords in compatible browsers, but it does notencrypt the content and data in the same way as Secure Sockets Layer (SSL).

Page 49: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 43

! Digest authentication works across proxy servers and firewalls.! By itself, Digest authentication is only a slight improvement over Basic authentication. In the

absence of SSL/TLS, an attacker could record communication between the client and server. Usingthis information, the attacker can then use that information to replay the transaction.

! See the Microsoft MSDN® Knowledge Base article KB222208 �Setting Up Digest Authenticationfor Use with Internet Information Services 5.0�.

Page 50: 2806 Microsoft Security Guidance Training for Developers

44 Session: Essentials of Application Security

Authentication � Client Digital Certificates

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! When a browser or software component connects to a server by using SSL/TLS, the serverpresents its X.509 server certificate to the client. The client validates the certificate to check itsauthenticity as part of the handshake setting up the connection. By default, client certificates arenot used, meaning that the server has no way of authenticating the client, but X.509 clientcertificates can perform this role.

! A similar process used in Web applications can be used for distributed applications.! A common way of deploying client certificates is on smartcards, which are usually credit card-

sized cards with an embedded chip. These cards store certificates securely and are tamper-proof,meaning that they cannot be altered.

! Client certificates is a good technique for authenticating external clients who are connecting toyour systems over the Internet.

Page 51: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 45

Authentication � When to Use Integrated Authentication

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Both NTLM and Kerberos authenticate Windows clients.! Integrated Windows authentication, like digest authentication, does not pass the user's password

across the network. Instead, a hashed value is exchanged.! This credential exchange cannot work through firewalls. Therefore, Windows Integrated

Authentication is only effective in intranet scenarios.! Integrated Windows authentication is the best authentication scheme in an intranet environment

where users have Windows domain accounts, especially when using Kerberos.! Using Kerberos v5 authentication, IIS can delegate security credentials among computers running

Windows 2000 and later that are trusted and configured for delegation. Delegation enables remoteaccess of resources on behalf of the delegated user. NTLM does not support delegation.

! Resources: IIS documentation http://www.microsoft.com/windows2000/en/server/iis/! Knowledge Base KB264921: http://msdn.microsoft.com/library/en-us/vsent7/html/

vxconIISAuthentication.asp

Page 52: 2806 Microsoft Security Guidance Training for Developers

46 Session: Essentials of Application Security

Authentication � How to Use Kerberos Version 5

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The Kerberos version 5 protocol is a ticket-based authentication protocol. The Key DistributionCenter (KDC) in the Kerberos protocol issues ticket-granting tickets (TGT) and service tickets(ST) to clients for authentication.

! To support the Kerberos version 5 protocol, both client and server must use Windows 2000 orlater.

! Initial logon authentication: When a user first logs on to the network, the user provides credentialsto prove their identity. As shown on the slide, the following occurs during Kerberos version 5initial logon authentication:1. At logon time, the user authenticates to a KDC.

2. The KDC provides the user with an encrypted TGT. The TGT contains a time stamp andauthentication information about the user.

3. The client decrypts the TGT by using the user�s private key and then caches the decryptedTGT locally in the client�s protected storage. The TGT contains a service key forsubsequent transactions with the KDC.

! Service Request: A Kerberos version 5 service request is used when a user attempts to connect toapplication or print servers on the network. As shown on the slide, the following occurs during aservice request:1. The user supplies credentials by sending the TGT, which they obtained previously, to the

KDC and requests an ST for a target server.

2. The KDC verifies the user�s credentials by decrypting the TGT and securely transmittingthe ST to the user�s computer, where the ST is cached locally in the client�s protectedstorage.

3. The user presents the ST to the target server, which grants the user access based on theuser�s assigned permissions and requested access permissions.

4. A session is established between the client computer and the target server.

Page 53: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 47

Demonstration 3: IIS Authentication Techniques

*****************************ILLEGAL FOR NON-TRAINER USE******************************

This demo shows how to set up Anonymous, Basic, and Windows Integrated authentication in IIS.It also shows how a Microsoft ASP.NET application can be made to impersonate the logged-onuser.

Using Anonymous Authentication1. SWITCH TO THE LONDON VPC.

2. If not already logged on, log onto London by using the OrdinaryUser account with a passwordof Passw0rd.

3. Open Internet Information Services Manager. Do this by clicking Start � Run� andentering:runas /env /user:London\Administrator "mmc %windir%\system32\inetsrv\iis.msc"

4. Enter a password of P@ssw0rd when prompted.

5. Under the Default Website website, locate the SecDev virtual directory. Expand SecDev.

6. Right-click the iisauth site, and then click Properties.

7. Click the Directory Security tab.

8. Click the Edit� button in the Authentication and Access Control section.

9. Ensure that Enable Anonymous Access is selected.

10. Click OK.

11. Open Microsoft Internet Explorer.

12. If you are prompted about enhanced security configuration, select the In the future, do notshow this message checkbox, and then click OK.

13. Type http://london/SecDev/iisauth in the Address bar, and press ENTER.

Page 54: 2806 Microsoft Security Guidance Training for Developers

48 Session: Essentials of Application Security

14. The page is displayed.

15. Start Notepad.

16. Click File � Open and openc:\courses\DeveloperSecurity\Democode\Websites\iisauth\web.config. (Note: If fileextensions are not displayed, the file will simply be called Web).

17. Find the line <Identity impersonate="false"/>. Change "false" to "true" and save the file.

18. Leave Notepad open.

19. In Internet Explorer, refresh http://london/SecDev/iisauth.

20. The page displays, this time with the account shown as LONDON\IUSR_WIN2K3-BASE.

Using Basic Authentication1. In IIS Manager, edit the Authentication and Access Control properties again.

2. Clear Anonymous Access.

3. Clear Integrated Windows Authentication.

4. Select Basic Authentication.

5. A warning appears. Click Yes.

6. Click OK. On main Properties page, click Apply.

7. In Internet Explorer, refresh the http://london/SecDev/iisauth page.

8. When the logon credentials window appears, enter an invalid username and password, and thenclick OK. Repeat this two more times.

9. You are notified that you are not authorized to view this page.

10. Refresh the page.

11. Enter a username of OrdinaryUser, and a password of Passw0rd

12. The page displays, this time with the user identity and the account shown asLONDON\ORDINARYUSER

13. In Notepad, find the line <Identity impersonate="true"/>. Change "true" to "false" and savethe file.

14. Close Internet Explorer, and then open it again.

15. In Internet Explorer, browse to http://london/SecDev/iisauth.

16. Enter a username of OrdinaryUser, with a password of Passw0rd

17. The page displays, this time with the user identity shown as LONDON\ORDINARYUSER andthe account shown as NT AUTHORITY\NETWORK SERVICE.

Page 55: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 49

Using Integrated Windows Authentication1. In IIS Manager, edit the Authentication and Access Control properties again.

2. Clear Basic Authentication.

3. Select Integrated Windows Authentication.

4. Click OK. On main Properties page, click Apply.

5. In Internet Explorer, go to http://london/SecDev/iisauth. When the logon credentials windowappears, enter an invalid username and password, and then click OK. Repeat this two moretimes.

6. You are notified that you are not authorized to view this page.

7. Refresh the page.

8. Enter username: OrdinaryUser, password: Passw0rd

9. The page displays, this time with the user identity shown as LONDON\ORDINARYUSER andthe account shown as NT AUTHORITY\NETWORK SERVICE.

10. In Notepad, find the line <Identity impersonate="false"/>. Change "false" to "true" and savethe file.

11. Close Internet Explorer, and then open it again.

12. In Internet Explorer, browse to http://london/SecDev/iisauth.

13. Enter username: OrdinaryUser, password: Passw0rd

14. The page displays, this time with the user identity and the account shown asLONDON\ORDINARYUSER.

15. Close all applications

Page 56: 2806 Microsoft Security Guidance Training for Developers

50 Session: Essentials of Application Security

Authorization � What is Authorization?

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Authorization is the process of confirming that an authenticated principal is allowed access to oneor more resources. After an identity is authenticated, the authorization process determines whetherthat identity has access to a specified resource. The authorization process limits access rights bygranting or denying specific permissions to an already authenticated identity.

! Authorization and authentication go together because any meaningful authorization policy requiresauthenticated users.

! The administrator assigns rights to files, folders, registry settings, applications, databases, andfiles.

! Authorization can be user-based, which includes group-based and role-based security.! Authorization can also be code-based, which secures what resources the code is allowed to access.! We will cover common authorization techniques, and the Impersonation/Delegation and trusted

subsystem models in the next three slides.

Page 57: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 51

Authorization� Common Authorization Techniques

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! IIS Web permissions and IP or DNS restrictions are a feature of IIS. You can limit part of awebsite, or an entire website so that it can be accessed only from specific IP addresses, subnets,and DNS names.

! .NET roles are a programmatic way of defining roles. In your .NET application, you map useridentities (or principals in .NET parlance) to one or more roles that you define. In code, youperform permission checks when a protected resource is accessed, so that only principals thatbelong to specific roles gain access.

! .NET code access security is a layer of security that supplements Windows user-based securitymechanisms. It is a way of restricting software not only based on the identity of the user, but alsoon the source of the software component. Therefore, a component that is downloaded from theInternet, that is signed with a digital certificate that identifies the �publisher�, is granted a specificset of privileges. That set of privileges differs from those given to unsigned applications, or tosoftware that is installed directly onto the system. Security policy on the computer dictateswhether software with a particular set of privileges is allowed to run, and if it is, what resources itis allowed to access.

! NTFS access control lists (ACL) are used to grant access rights to Windows user and groupaccounts. They are often used to secure files, directories and registry entries.

! Microsoft SQL Server� logins provide the authorization for the SQL Server, but the databasepermissions provides the authorization for the database objects such as tables, views, and storedprocedures. The recommended model is to map a SQL Server login to a database User, put thedatabase user into a database role, and to then grant permissions to the role.

Page 58: 2806 Microsoft Security Guidance Training for Developers

52 Session: Essentials of Application Security

Authorization � Impersonation/Delegation Model

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The two most commonly used resource-access security models that are used by Web applications(and distributed multi-tier applications in general) are:1. The impersonation/delegation model

2. The trusted subsystem model

! In the impersonation/delegation model, a service or component (usually somewhere in the middletiers of a multi-tier application) impersonates the client�s identity (using operating system-levelimpersonation) before it accesses the next downstream service. If the next service in line is on thesame computer, impersonation is sufficient. Delegation is required if the downstream service islocated on a remote computer.

! As a result of the delegation, the security context used for the downstream resource access is thatof the client.

! The impersonation/delegation model is typically used for a couple of reasons:1. It allows the downstream service to perform per-caller authorization by using the original

caller�s identity.

2. It allows the downstream service to use operating system-level auditing features.

! The primary advantage of the impersonation/delegation model is auditing (close to the data).Auditing allows administrators to track which users have attempted to access specific resources.

! The primary disadvantages are:1. The technological difficulties of delegating identity, unless Kerberos is used.

2. Scalability is limited, since each database connection is in the context of the caller identity,preventing effective connection pooling.

3. Increased administration, since ACL's on downstream resources and SQL Server loginsmust be maintained for each individual user.

Page 59: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 53

Authorization � Trusted Subsystem Model

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In the �Trusted Subsystem� model, the user is checked at the IIS gate (and authenticated) and isthen mapped to a role.

! The database trusts the middle tier to authorize callers and allows only authorized callers to accessthe database by using the trusted identity.

! Downstream resource access uses a fixed service account used to service requests from all users inthat role (in the world of ASP.NET, typically the service account used is the ASPNET account,which requires a mirrored (duplicate) account on the remote box, or alternatively a least privilegeddomain account � if the downstream box is in the same or trusting domain and an interveningfirewall does not prevent Windows authentication)

! The Trusted Subsystem model offers the following advantages:1. Improved scalability. Since only a known number of service accounts is used to access

database resources, connection pooling is used effectively.

2. Reduced administration. ACL management of resources is reduced, since there are fewerservice accounts than clients.

3. Indirect data access. Users cannot access data directly, but must instead go through theapplication authorization controls.

! The Trusted Subsystem model has the following disadvantages:1. Auditing difficulties. If auditing is required on a per-user basis, this is not easily achieved

because service accounts are used to access the data. It is necessary instead to flow useridentity at the application level, and implement per-user auditing manually in theapplication.

2. Increased risk of server compromise. Since the database tier trusts the front-end tiers toauthenticate users correctly, any weakness in that authentication leaves the server moreexposed than if authentication was on a direct, per-user basis.

! Resources: http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetch03.asp

Page 60: 2806 Microsoft Security Guidance Training for Developers

54 Session: Essentials of Application Security

Demonstration 4: Trusted Subsystem Model AuthorizationTechniques

*****************************ILLEGAL FOR NON-TRAINER USE******************************

This demo will show how to configure authorization between an application server and a databaseserver by using the Trusted Subsystem model.

Reviewing the Application1. SWITCH TO THE LONDON VPC.

2. If you are not already logged on, log onto London by using the OrdinaryUser account, with apassword of Passw0rd.

3. Start Notepad.

4. Click File � Open and openc:\courses\DeveloperSecurity\Democode\Websites\TrustedSubsystem\default.aspx.cs

5. Show the Page_Load method

6. Open Internet Explorer.

7. Browse to http://london/SecDev/TrustedSubsystem.

8. The error page displays: Login failed for user '(null)'. Reason: Not associated with a trustedSQL Server connection.

Page 61: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 55

Setting Authentication on the Web Server1. Open Internet Information Services Manager. Do this by clicking Start � Run� and entering:

runas /env /user:London\Administrator "mmc %windir%\system32\inetsrv\iis.msc"

2. Enter a password of P@ssw0rd when prompted.

3. Under the Default Website website, locate the SecDev virtual directory. Expand that.

4. Right-click the TrustedSubsystem site, and then click Properties.

5. Click the Directory Security tab.

6. Click the Edit� button in Authentication and Access Control.

7. Clear Enable Anonymous Access.

8. Ensure that Integrated Windows Authentication is selected.

9. Click OK. On main Properties page, click Apply.

10. In Internet Explorer, refresh http://london/SecDev/TrustedSubsystem.

11. Enter username: OrdinaryUser, password: Passw0rd

12. The error page still displays: Login failed for user '(null)'. Reason: Not associated with atrusted SQL Server connection.

Creating Service Accounts on the Web Server1. On LONDON, open the Computer Management console. Do this by clicking Start � Run�

and entering:runas /env /user:London\Administrator "mmc %windir%\system32\compmgmt.msc"

2. Enter a password of P@ssw0rd when prompted.

3. Expand Local Users and Groups, then Users.

4. Click Action � New User.

5. Create a new user:

a. Username: OrderReadersb. Password: Passw0rdc. Confirm password: Passw0rdd. User must change password at next logon: Uncheckede. Check User cannot change password and Password never expires

6. Click Create, and then click Close.

7. Switch to Notepad.

8. Click File � Open and openc:\courses\DeveloperSecurity\Democode\Websites\TrustedSubsystem\web.config

9. Find the line <Identity impersonate="false"/>.

10. Change to:<identity impersonate="true"

userName="OrderReaders"password="Passw0rd"/>

Page 62: 2806 Microsoft Security Guidance Training for Developers

56 Session: Essentials of Application Security

11. Save the file.

12. Close Notepad.

13. In Internet Explorer, refresh http://london/SecDev/TrustedSubsystem.

14. The error page displays: Access to the path"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NETFiles\secdev_trustedsubsystem\7ef0ea93\dd5d4bc2\hash.web" is denied.

15. Log off as OrdinaryUser

16. Log on as Administrator, password: P@ssw0rd

17. Click Start � My Computer

18. Expand to the C:\Windows\Microsoft.NET\Framework\v1.1.4322 directory.

19. Right-click on the Temporary ASP.NET Files folder, and click Properties.

20. Click the Security tab, and then click Add.

21. Enter OrderReaders, and then click Check Names.

22. Click OK.

23. Check Write and Modify in addition to the privileges already checked.

24. Click OK, and then click Yes.

25. Log off as Administrator.

26. Log on as OrdinaryUser again, password Passw0rd.

27. Open Internet Explorer.

28. Open http://london/SecDev/TrustedSubsystem.

29. Enter username: OrdinaryUser, password: Passw0rd

30. The error page displays: Login failed for user '(null)'. Reason: Not associated with a trustedSQL Server connection.

Setting Authorization on the Database Server1. Log onto Denver by using the Administrator account, with a password of P@ssw0rd.

2. Click Start � Administrative Tools � Computer Management.

3. Expand Local Users and Groups, and then Users.

4. Click Action � New User.

5. Create a new user:

a. Username: OrderReadersb. Password: Passw0rdc. Confirm password: Passw0rdd. User must change password at next logon: Uncheckede. Check User cannot change password and Password never expires

6. Click Create, and then click Close.

Page 63: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 57

7. Open SQL Server Enterprise Manager.

8. Expand the tree to find the Logins category for the Security folder.

9. Click Action � New Login.

10. Click the ellipsis button next to Name. Select OrderReaders in the list and click Add.

11. Click OK.

12. Leave Windows Authentication selected.

13. Select Northwind in the database field.

14. On the Database Access tab, click the check box next to the Northwind database.

15. In the Permit in database role list, select db_datareader.

16. Click OK.

17. SWITCH TO THE LONDON VPC

18. Open Internet Explorer.

19. Refresh the http://london/SecDev/TrustedSubsystem page.

20. The data displays.

Page 64: 2806 Microsoft Security Guidance Training for Developers

58 Session: Essentials of Application Security

Firewalls

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! A firewall is a collection of hardware or software devices that enforces an access control policybetween two networks. Although the firewall can perform many functions, the primary twofunctions are to block network traffic and to permit approved traffic. A firewall can secure variouslayers of communication; including packet filtering, circuit-level filtering, and applicationfiltering.

! At the packet level, a firewall prevents malformed and oversized packets resulting in denial ofservice attacks from entering the internal network.

! At the circuit-level, a firewall inspects packets from various sessions, using specific ports andcommunicating over a variety of protocols such as HTTP and Simple Mail Transfer Protocol(SMTP).

! The most sophisticated level of firewall traffic inspection is application-level security. Goodapplication filters allow you to analyze a data stream for a particular application and provideapplication-specific processing, including inspecting, screening or blocking, redirecting, ormodifying the data, as it passes through the firewall.

! In addition, some firewalls provide auditing and intrusion detection features.! However, firewalls cannot meet all your security requirements. Application filters will not be

sufficient to ensure that your Web application is secure.

Page 65: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 59

Auditing

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! You can use security auditing techniques to monitor a broad range of user and server securityactivity. It is recommended that you routinely audit your server configuration to detect areas whereresources may be susceptible to unauthorized access and tampering.

! Auditing is an important ingredient of a secure application. Audit records can notify operationsstaff that unauthorized access is being attempted. They can help you to diagnose security breachesafter they have occurred and give important information that will allow you to rectify the securityvulnerability.

Page 66: 2806 Microsoft Security Guidance Training for Developers

60 Session: Essentials of Application Security

Service Packs and Updates

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Service packs are the means by which product updates, including hotfixes, are distributed. Servicepacks may contain updates for system reliability, program compatibility, security, and more. All ofthese updates are conveniently bundled for easy downloading.

! Application of service packs is usually the responsibility of operations staff.! It is the responsibility of secure developers to liaise with operations staff, so that applications can

be tested in a test bed against new service packs before the service pack is deployed across theenterprise.

! On occasions, applications may knowingly or unknowingly make use of a �feature�, or unintendedbehavior of some infrastructure software. Should a service pack alter the way the feature works,your application may not operate in the way you intended.

Page 67: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 61

Secure Development Guidelines

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will consider what developers should do to improve secure programming practices.Specifically, we will discuss:

! Steps to improve security practices.! How to adopt the SD3 security framework.! The Microsoft Java end of support alert.

Page 68: 2806 Microsoft Security Guidance Training for Developers

62 Session: Essentials of Application Security

Proactive Security Development

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Effective secure application development requires that security is considered at every stage of thedevelopment process. Adopt a holistic approach to security.

! There is no quick-fix for security. A sprinkling of security features spread throughout anapplication does not make it secure. Ensure that security is a prime concern during design,development, and deployment.

! You must update the software development process itself. Add process improvements at everystep of the software development life cycle to better focus on security.

! Security threats continually evolve, so it is important that your commitment to security iscontinuous and vigilant.

! Education is the key ingredient of this, both to learn from security vulnerabilities that arediscovered in your system, but also to be informed about new security vulnerabilities that arediscovered elsewhere in the computer industry. There are two aspects to security training. The firstis to teach people about security issues so they can apply that knowledge to their current projectand find and fix security bugs. However, the most important goal is to teach people not tointroduce security flaws in the first place.

Page 69: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 63

Adopt the SD3 Security Framework

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The SD3 security framework has proven an effective tool for encouraging the adoption of securedevelopment practices.

! Ensure your systems are secure by design, meaning that you have carried out threat modelling toidentify security vulnerabilities, you conduct code reviews focusing on security issues and that youensure that security testing is an integral part of the testing process. Write software that runs withjust enough privilege to carry out its purpose, but no more.

! Implement systems that are secure by default. Reduce the potential for attack by ensuring thatoptional features are turned off by default.

! Secure in Deployment. Ensure that your systems are easy to administer and update, so thatsecurity vulnerabilities may be addressed. Educate users on how to use the application securely.Provide a continuing program of security assessments and testing.

Page 70: 2806 Microsoft Security Guidance Training for Developers

64 Session: Essentials of Application Security

Microsoft Java Virtual Machine � End of Support Alert

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Microsoft have announced that the Microsoft Java Virtual Machine (MSJVM) is no longershipped with Windows XP SP1a or Windows Server 2003.

! Support for MSJVM will be discontinued from the end of September 2004, and no bug fixes willbe made after that date.1. No bug fixes, including security fixes, will be made after that date. No exception possible.

2. Security holes found after that date may force emergency removal of MSJVM.

! Enterprises should begin planning to remove all applications that are dependent upon MSJVM.! Developers should update their applications to use alternative Java runtime environments or

different technologies, and offer the updated applications as upgrades to their customers.! For more information, visit http://www.microsoft.com/java

Page 71: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 65

Session Summary

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 72: 2806 Microsoft Security Guidance Training for Developers

66 Session: Essentials of Application Security

Next Steps

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Next steps include going to the Microsoft Web site to:

! Get the latest security information.! Get additional security training.

Page 73: 2806 Microsoft Security Guidance Training for Developers

Session: Essentials of Application Security 67

For More Information

*****************************ILLEGAL FOR NON-TRAINER USE******************************

More technical information for IT professional and developers is available on the following Websites:

! Microsoft Security Site (all audiences)

• http://www.microsoft.com/security! MSDN Security Site (developers)

• http://msdn.microsoft.com/security! TechNet Security Site (IT professionals)

• http://www.microsoft.com/technet/security

Page 74: 2806 Microsoft Security Guidance Training for Developers

68 Session: Essentials of Application Security

Questions and Answers

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 75: 2806 Microsoft Security Guidance Training for Developers

Contents

What We Will Cover 1

Session Prerequisites 2

Secure Development Process 3

Threat Modeling 8

Risk Mitigation 22

Security Best Practices 27

Demonstration 1: ASP.NET ApplicationsSecurity 29

Session Summary 51

Clinic Evaluation 55

Session: Writing Secure Code � BestPractices

Page 76: 2806 Microsoft Security Guidance Training for Developers

Information in this document, including URL and other Internet Web site references, is subject tochange 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 applicablecopyright laws is the responsibility of the user. Without limiting the rights under copyright, nopart of this document may be reproduced, stored in or introduced into a retrieval system, ortransmitted in any form or by any means (electronic, mechanical, photocopying, recording, orotherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectualproperty rights covering subject matter in this document. Except as expressly provided in anywritten license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

2004 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Windows Server, Active Directory, and ASP.NETare either registered trademarks or trademarks of Microsoft Corporation in the United States and/orother countries.

The names of actual companies and products mentioned herein may be the trademarks of theirrespective owners.

Page 77: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 1

What We Will Cover

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this session, we will focus on how to perform threat modeling during the design and codingstages of a software development project and the best practices for writing secure code.Specifically, we will discuss:

! The secure development process.! Threat modeling.! Risk mitigation.! Security best practices.

Page 78: 2806 Microsoft Security Guidance Training for Developers

2 Session: Writing Secure Code � Best Practices

Session Prerequisites

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 79: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 3

Secure Development Process

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will review the essential components of a successful secure development process.Specifically, we will discuss:

! Improving the application development process.! The SD3 security framework.! The secure product development timeline.! Secure by design.

Page 80: 2806 Microsoft Security Guidance Training for Developers

4 Session: Writing Secure Code � Best Practices

Improving the Application Development Process

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Experiences at Microsoft and throughout the software industry have shown that successfuldelivery of trustworthy software products requires process improvements throughout theapplication development process.

! Often, security is considered as an afterthought, with security review of the product left until latein the development process. Although implementing security measures at this late stage does yieldsome benefits, it cannot substitute for considering security as an integral part of the process rightfrom the beginning of the design phase, through development, to deployment.

! In short, you must build security into your application development lifecycle. For step-by-stepguidance on how to achieve this, see Fast Track � How to Implement the Guidance athttp://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMFastTrack.asp

Page 81: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 5

The SD3 Security Framework

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The first and most important step towards good security practice is to ensure that security is anintegral part of the entire development process.

! The Secure Windows Initiative team at Microsoft has adopted a simple set of strategies calledSD3. The SD3 framework has three core concepts: secure by design, secure by default, and securein deployment. These concepts have shaped the development process to help deliver securesystems.

• Secure by design means that you have taken appropriate steps to ensure that the overall designof the product is secure from the outset. Include threat modeling at the design phase andthroughout the project to identify potential vulnerabilities. Use secure design, coding andtesting guidelines.

• Secure by default means that the product is shipped and that it is secure out of the box. Iffeatures are optional, turn them off by default. If a feature is not activated, then an attackercannot use it to compromise your product. Ensure that only the least amount of privilege isrequired by user accounts to run your application. That way, a compromise has less seriousconsequences than if an attacker is able to run malicious code under an account withadministrator privileges. Ensure that effective access controls are in place for resources.

• Secure in deployment means that the system is maintainable after installation. If a product ishard to administer, it makes it more difficult to maintain protection against security threats.Ensure that users are educated to use the system in a secure manner. If a security vulnerabilityis discovered and a patch is necessary, ensure that the fix is fully tested internally and issued ina timely fashion.

Page 82: 2806 Microsoft Security Guidance Training for Developers

6 Session: Writing Secure Code � Best Practices

Secure Product Development Timeline

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Activities that are shown as ongoing start at the points as illustrated on the product developmenttimeline. However, these activities continue on throughout the project lifecycle. For example,hiring of team members may not occur only at the start of the project, but happens at later stages aswell.

! At the commencement of a project, during interviews with potential team members, ask securityquestions to assess the level of security knowledge. This will help you to select security consciousdevelopers, and help you to assess the need for further security training.

! During the design phase and later in the project, threat modeling is a valuable tool for identifyingsecurity defects. Threat modeling is examined further in the next section of this presentation.

! During development, developers should be trained to recognize common security defects and howto code to avoid them. There should be special focus on security during code reviews.

! Test plans must include a significant element of security testing. Testers should devise ways ofattacking the software, looking for security defects.

! After the product is shipped, there must be an appropriate plan of response for any security defectsthat are uncovered. At the least, this should involve education of developers so that the same orsimilar security issues can be uncovered. It may also involve the timely issuing of patches toexisting installations.

Page 83: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 7

Secure By Design

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Education is the key ingredient of an effective secure development process. You must ensure thatall designers and programmers are informed about common security flaws in software so they canavoid repeating past mistakes. Perform regular training to raise security awareness and ensure thatsecurity remains a primary concern of all team members.

! Problems discovered late in the development cycle are much more expensive to fix than thosediscovered early on. This is particularly true for security issues. Be sure to consider the security ofyour application right at the beginning of the design phase.

! The security goals of the product should be considered with equal (or greater) importance to theother functional goals.

! If security is designed as a product feature, rather than considered as a �value-add� feature to beadded on �if there is time,� the resulting product will be much more secure than if it is added as anafterthought.

! Threat modeling during the design phase as well as the development phase has proven to beextremely effective in determining the highest level security risks that are posed to the product andhow attacks can occur.

Page 84: 2806 Microsoft Security Guidance Training for Developers

8 Session: Writing Secure Code � Best Practices

Threat Modeling

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will discuss threat modeling. Specifically, we will discuss:

! What threat modeling is.! The benefits of threat modeling.! The threat modeling process.! Categorizing threats by using STRIDE.! Identifying threats by using attack trees.! Coding to a threat model.

Page 85: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 9

What Is Threat Modeling?

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Threat modeling is an analysis approach that helps designers to define the security aspect of thedesign specifications.

! The overriding driver of threat modeling is that you cannot build secure systems unless youunderstand your threats. The process aims to evaluate the threats to the application with the goal ofreducing the consequences of an attack.

! Threat modeling is simple although it does require significant time investment and some practiceto get it right. However, time spent during this phase is time well invested. Bugs found during thisphase of development are much cheaper to fix than bugs discovered right before shipping!

! Threat modeling has a structured approach that is far more cost efficient and effective thanapplying security features in a haphazard manner. Without threat modeling, you may not knowprecisely what threats each feature is supposed to address. It leads naturally to a solid securitydesign which is a part of the formal design specification of your application.

! Threat modeling allows you to systematically identify and rate the threats that are most likely toaffect your system.

! An asset is also referred to in threat parlance as an attack target. It is anything that is worthprotecting.

! A vulnerability is a weakness in a system, such as a coding bug or a design flaw.! A threat to a system is a potential event that will have an unwelcome consequence if it becomes an

attack.

Page 86: 2806 Microsoft Security Guidance Training for Developers

10 Session: Writing Secure Code � Best Practices

Benefits of Threat Modeling

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Threat modeling helps you:

• Understand your application better: Team members who spend time analyzing the applicationin a structured manner inevitably end up with a deeper understanding of how the applicationworks.

• Find bugs: The additional scrutiny of the threat modeling process leads to the discovery ofother, non-security related bugs.

• Identify complex design bugs: The analytical nature of the process can reveal complex multi-step security bugs where several small failures combine to cause a major failure. This kind ofvulnerability may be missed by unit testing performed by the developer and the majority of testplans.

• Integrate new members: Threat modeling is a useful tool for new team members to becomefamiliar with the architecture of the product.

! Threat modeling should drive your security test plan design. Testers should test against the threatmodel, which will help them develop new test tools and procedures.

Page 87: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 11

The Threat Modeling Process

*****************************ILLEGAL FOR NON-TRAINER USE******************************

A threat modeling process requires several steps:

1. Identify assets. Identify the valuable assets that your systems must protect.

2. Create an architecture overview. Use simple diagrams and tables to document the architectureof your application, including subsystems, trust boundaries, and data flow.

3. Decompose the application. Decompose the architecture of your application, including theunderlying network and host infrastructure design, to create a security profile for theapplication. This security profile helps to uncover vulnerabilities in the design, implementation,or configuration of your application.

4. Identify the threats. Keeping the goals of an attacker in mind, and with knowledge of thearchitecture and potential vulnerabilities of your application, identify the threats that couldaffect the application.

5. Document the threats. Document each threat using a common threat template that defines a coreset of attributes to capture for each threat.

6. Rate the threats. Rate the threats to prioritize and address the most significant threats first.These threats present the biggest risk. The rating process weighs the probability of the threatagainst damage that could result should an attack occur. It might turn out that certain threats donot warrant any action when you compare the risk posed by the threat with the resultingmitigation costs.

Page 88: 2806 Microsoft Security Guidance Training for Developers

12 Session: Writing Secure Code � Best Practices

Threat Modeling Process � Step 1: Identify Assets

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The first stage of the threat modeling process is to identify the assets you need to protect.! An asset is a system resource of value, such as the data in a database or on the file system.! You must build a list of assets that require protection including:

• Confidential data, such as customer databases.

• Web pages.

• System availability.

• Anything else that, if compromised, would prevent correct operation of your application.

Page 89: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 13

Threat Modeling Process � Step 2: Create An Architecture Overview

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The purpose of the architecture overview is to document the function of your application, itsarchitecture and physical deployment configuration, and the technologies that form part of yoursolution.

! There are three main parts to the application overview:

• Identify what the application does. Document use cases to help you and others understand howyour application is supposed to be used. This also helps you determine how it can be misused.Use cases put application functionality in context.

• Create an architecture diagram. This describes the composition and structure of yourapplication and its subsystems as well as its physical deployment characteristics. Depending onthe complexity of the application, this may need to split into several diagrams that focus onspecific areas

• Identify the technologies. This helps you focus on technology-specific threats later in theprocess. It also helps you determine the correct and most appropriate mitigation techniques.

Page 90: 2806 Microsoft Security Guidance Training for Developers

14 Session: Writing Secure Code � Best Practices

Threat Modeling Process � Step 3: Decompose the Application

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Identify the trust boundaries that surround each of the assets in your application. For eachsubsystem, consider whether the upstream data flows, user input or calling code is trusted, and ifnot, consider how the data flows and input can be authenticated and authorized. Also considerserver trust relationships.

! Analyze the data flow between different subsystems, paying particular attention to data flowscrossing trust boundaries.

! Carefully consider all entry points to your application � such as Web pages or socket servers � asthese are potential routes for attack. Also consider entry points on internal subsystems orcomponents. Although these entry points may only exist to allow internal communication betweencomponents in your application, they could also serve as points of attack, if the attacker managesto bypass the normal �front door� security controls.

! Consider code that accesses secure resources such as DNS servers, directory services, environmentvariables, event logs, file systems, message queues, performance counters, printers, the registry,sockets, and Web services. Any code that demands special privileges or which works with thesecurity system (for example .NET code access security) demands special vigilance.

! Create a security profile for the application by documenting the design and implementationapproaches for input validation, authentication, authorization, configuration management, and theremaining areas where applications are most susceptible to vulnerabilities.

! Data flow diagrams (DFDs) are a useful tool for decomposing an application into its keycomponents. They provide the basis of a good technique for illustrating the flow of data betweenprocesses. An alternative is UML activity diagrams, which are similar in purpose, although focusmore on the transfer of control between processes. The guiding principle for DFDs is that anapplication or a system can be decomposed into subsystems, and subsystems can be decomposedinto still lower-level subsystems. Ignore the inner workings of the application, but focus on thescope of the application, not functional details. Decompose the application down only two, threeor four levels deep � just deep enough to understand the threats to the application. Do not fail inthe threat modeling process by analyzing too deeply and losing sight of the original objective.

Page 91: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 15

Threat Modeling Process � Step 4: Identify the Threats

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In this stage of the threat modeling process, you identify threats to your system assets. The bestway to do this is to assemble a team consisting of members of the development and test teams toconduct an informed brainstorming session in front of a whiteboard.

! There are three types of threats that you need to identify. You need to:

• Identify network threats: Analyze the network topologies and look for vulnerabilities. Ensureyour network is not vulnerable to incorrect device and server configuration.

• Identify host threats: Look for vulnerabilities through poor configuration of hosts security.Consider patch levels and updates, services, protocols, accounts, files and directories, shares,ports, and auditing and logging.

• Identify application threats: Scrutinize the security profile you created in the previous stage ofthe threat modeling process. Focus on application threats, technology-specific threats, and codethreats. Look for things such as poor input validation, passing authentication credentials overunencrypted network connections, or using weak password or account policies.

Page 92: 2806 Microsoft Security Guidance Training for Developers

16 Session: Writing Secure Code � Best Practices

Threat Modeling Process � Identify the Threats by Using STRIDE

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Categorizing the threats that hackers pose has many benefits. For example, by categorizing thethreats, you can identify and develop security policies that apply to a range of threats in a categoryand not just to individual threats.

! The STRIDE categories are:

• Spoofing: Illegally accessing and then using another user�s authentication information, such asuser name and password. For example, a hacker can bypass authorization by using SQLinjection and assuming the �sa� role.

• Tampering with Data: Maliciously modifying data. An example would be makingunauthorized changes to persistent data such as data in a database or alternating data as it flowsbetween two computers over an open network, such as the Internet.

• Repudiation: Threats associated with users denying (repudiating) an action when other partiesdo not have any way of proving otherwise.

• Information disclosure: Exposing information to unauthorized individuals. An example wouldbe reading data in transit between two companies. Another example is using cross-sitescripting to steal somebody�s cookies.

• Denial of service: Denying service to valid users. An example would be making a Web servertemporary unavailable or unusable. Another example is exploiting a buffer overrun that causesa server to restart.

• Elevation of privilege: An unprivileged user gaining privileged access and thereby havingsufficient access to compromise or destroy the entire system. An example would be exploitinga buffer overrun to gain a command shell and adding the hacker to the Administrators group.

Page 93: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 17

Threat Modeling Process � Identify the Threats by Using AttackTrees

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Building threat trees is an effective method for determining computer system security issues. Theidea behind threat trees is that an application is composed of threat targets and that each targetcould have vulnerabilities that when successfully attacked could compromise the system.

! The threat tree describes the decision-making process an attacker would go through tocompromise the software component.

! The decomposition process has helped you to identify all the system components. You thenidentify potential threats to each component. Threat trees then help you decide how that threatcould manifest itself.

! The way to write a threat tree is to identify goals and sub-goals of an attack, as well as what mustbe done so that the attack succeeds.

! The threat tree on this slide shows the ways in which an attacker could view another user�sconfidential payroll data.

! Although threat trees communicate data well, they can become cumbersome when building largethreat models. An alternative way of representing the threat tree is using an outline, as illustratedon the slide.

Page 94: 2806 Microsoft Security Guidance Training for Developers

18 Session: Writing Secure Code � Best Practices

Threat Modeling Process � Step 5: Document the Threats

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Document all the threats you identify.! You must include the threat target and threat description. The Risk is left blank for now, and is

completed in the final stage of the process.! You may want to include the attack techniques, which can also highlight the vulnerabilities

exploited, and the countermeasures that are required to address the threat.

Page 95: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 19

Threat Modeling Process � Step 6: Rate the Threats

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! At this step, you can fill in the risk data that you left blank in step 5.! After you document your threats, you need a way to determine which threats are the most

dangerous. To do this, you need a way to rank them.! You can calculate risk using a 1-10 scale for probability (where 1 is not probable, 10 is very

probable), and 1-10 for damage potential (1 � minimal damage, 10 � catastrophe). This results in arisk in the range of 1 � 100. You can divide the scale into three bands to generate a High, Mediumand Low risk rating.

! This way of assessing risk is too simplistic for some, so at Microsoft, the DREAD model is usedto refine this calculation to add a dimension that assesses what the impact of a security threatreally means.

• Damage potential: How much damage can the threat inflict on the system?

• Reproducibility: How difficult is it to reproduce the threat?

• Exploitability: How easy is it for hackers to succeed in exploiting a vulnerability?

• Affected users: How many users will be affected?

• Discoverability: How difficult is it to discover the threat?! Applications and companies use different criteria for different elements of the DREAD model.

The formula used to calculate the rank is not as important because the values derived are relativeto one another. You just need to be consistent.

Page 96: 2806 Microsoft Security Guidance Training for Developers

20 Session: Writing Secure Code � Best Practices

Threat Modeling Process � Example: Rate the Threats

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! DREAD provides a further refinement of the simple Risk = Damage * Chance formula.

• D (Damage Potential) and A (Affected users) are analogous to Damage.

• R (Reproducibility), E (Exploitability) and D (Discoverability) are analogous to Chance.! You can use this strategy to prioritize risks. After you calculate the priority for each identified

security risk, you can prioritize the risks and determine a management strategy based on thepriority value.

! Within each DREAD category, use a score of 3 for high risk, 2 for medium risk, and 1 for lowrisk.

! Assess each threat in your threat tree and assign the risk rating for each of the DREAD categoriesand add up the result.

! For example, the SQL Injection threat identified earlier could have a score of D � 3, R � 3, E � 3 ,A � 3, D � 2. This gives a total score of 14.

! Across the total possible range of 5 � 15, 12 � 15 may be considered high risk, 8 � 11 as mediumrisk, and 5 � 7 as low risk.

Page 97: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 21

Coding to a Threat Model

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In summary, threat modeling is a valuable analysis tool which improves the design process. Itallows you to identify the most vulnerable parts of your application so you can focus your effortson those places. It also helps you to identify appropriate techniques for mitigating threats.

! The benefit of threat modeling does not end there. Use threat modeling through the coding processto revisit and retest security decisions made in the design phase and to direct focus in security codereviews.

! The results of the threat modeling process provide the information necessary to select appropriatesecurity technologies and techniques to mitigate the threats that have been identified.

! Data flow diagrams are an effective tool for identifying data flows and are particularly useful foridentifying all inputs to your application. Any inputs are a particular source of securityvulnerabilities.

Page 98: 2806 Microsoft Security Guidance Training for Developers

22 Session: Writing Secure Code � Best Practices

Risk Mitigation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will examine how to mitigate the risks that the threat modeling process hasuncovered. Specifically, we will discuss:

! Risk mitigation options.! The risk mitigation process.! Some sample mitigation techniques.

Page 99: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 23

Risk Mitigation Options

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Mitigation techniques protect assets by securing vulnerabilities in a system and preventing threatsfrom being realized.

! When considering risks and how to mitigate them, you have four choices:

• Option 1: Do nothing. You may decide to leave a low security risk without fixing it. This israrely a good choice as the fault will lie latent in the application and it is likely that it will bediscovered and you will be forced to fix it. This is bad for your users and bad for your businessreputation.

• Option 2: Warn the user. Inform the user of the problem and allow them to decide whether touse the feature. However, you cannot expect users to have sufficient detailed knowledge of thesystem or the nature of the limitation to make a decision.

• Option 3: Remove the problem. If there is no time to fix the problem, you should considerpulling the feature from the product before shipping. It is better to fix it for the next releasethan allow it to go out and compromise your user�s computers.

• Option 4: Fix it. Select the technologies required to fix the problem.

Page 100: 2806 Microsoft Security Guidance Training for Developers

24 Session: Writing Secure Code � Best Practices

Risk Mitigation Process

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Determining how to allay the risks identified by the threat modeling process is a three-stepprocess.1. First, identify the category of threat, using STRIDE.

2. Next, determine which techniques can help.

3. Then, decide on appropriate technologies.

! For example, if the threat modeling process has identified a threat of spoofing identity, thetechnologies that can mitigate this include authentication or protecting secret data such as securitycredentials. If authentication is selected as the appropriate mitigating technique, the technologiesyou can use for authentication include NTLM, X.509 certificates, PGP (Pretty Good Privacy)Keys, Digest authentication, Kerberos, and SSL/TLS.

Page 101: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 25

Sample Mitigation Techniques

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Some of the mitigating techniques for each of the STRIDE threat categories are shown on theslide. In general, the mitigation techniques for each of these threats include:

• Spoofing:

• Use appropriate authentication.

• Protect secret data.

• Do not store secrets.

• Tampering with data:

• Use appropriate authorization.

• Use hashes or message authentication codes (MAC).

• Use digital signatures.

• Use tamper-resistant protocols such as SSL/TLS.

• Repudiation:

• Use digital signatures.

• Use timestamps.

• Use audit trails.

Page 102: 2806 Microsoft Security Guidance Training for Developers

26 Session: Writing Secure Code � Best Practices

• Information disclosure:

• Use authorization.

• Use privacy-enhanced protocols.

• Use encryption.

• Protect secrets.

• Do not store secrets.

• Denial of service:

• Use appropriate authentication.

• Use appropriate authorization.

• Use filtering.

• Use throttling.

Page 103: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 27

Security Best Practices

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Fortunately, there are effective techniques developers can use to prevent attacks. Some of these canmitigate a wide range of attacks and should be used when developing any application on anyplatform. Some attacks can be mitigated by specific methods. In this topic, we will discuss acommon set of techniques that developers can apply to mitigate security threats. Specifically, wewill discuss:

! Running with least privilege.! Reducing the attack surface.! Validating user input.! The defense in depth model.! Not relying on obscurity.! Not storing secret information.! Using DPAPI.! Failing intelligently.! Testing security.! Learning from mistakes.

Page 104: 2806 Microsoft Security Guidance Training for Developers

28 Session: Writing Secure Code � Best Practices

Run with Least Privilege

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! You must always run with just enough privilege to get the job done, and no more. For example, ifyou have a buffer overrun that runs under the security context of an administrator, a hacker canoverwrite the return address and have malicious code execute with those same privileges.

! Many well-known viruses rely on infecting computers by using accounts that have elevatedprivileges.

! It is easier for developers to create applications that require users with administrator-level access,because there are no permission errors, but this should not be done.

! Many developers develop applications using Administrator privileges �just for now� because itmakes development easier. Although the developer may intend to lower the required privilegeslater on, time pressures frequently mean that this does not happen. This results in applicationsgoing live with elevated privileges, because system admin staff discover that �If we do not run asadministrator, the application does not work!�

Page 105: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 29

Demonstration 1: ASP.NET Applications Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will show that the Microsoft® ASP.NET worker process runs under anonprivileged account by default. You will show how the secure developer grants access to anASP.NET application to access the file system, write to a custom event log, and access the registry.

Investigating ASP.NET Application PrivilegesPerform the steps on the LONDON VPC.

1. Log on to the Administrator account with a password of P@ssw0rd.

2. Open Internet Explorer.

3. Browse to http://london/SecDev/lowPrivASPNET.

4. Select the Write File option. Click the Do It button.

5. If you are prompted by Internet Explorer, click Yes.

6. Select the Write to Event Log option. Click the Do It button to show the security error.

7. Close Internet Explorer.

8. On the Start menu, click Run.

9. Type regedt32 and then click OK.

10. Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog.

11. Right-click Eventlog, and then click Permissions.

12. Click Add.

13. In the Object names box, type NETWORK SERVICE

14. Click Check Names, and then, click OK.

Page 106: 2806 Microsoft Security Guidance Training for Developers

30 Session: Writing Secure Code � Best Practices

15. Select the Allow checkbox for Full Control, and then click OK.

16. Close the Registry Editor.

17. Open Internet Explorer.

18. Browse to http://london/SecDev/lowPrivASPNET.

19. Select the Write to Event Log option. Click the Do It button to show that it now works.

20. Close Internet Explorer.

Restricting ASP.NET Application Trust Levels1. Using Notepad, open

C:\Courses\DeveloperSecurity\Democode\Websites\LowPrivASPNET\Web.config.

2. Below the <system.web> tag, enter the following:<trust level="Medium" originUrl="" />

3. Save the file.

4. Open Internet Explorer.

5. Browse to http://london/SecDev/lowPrivASPNET.

6. Select the Write File option. Click the Do It button to show the security error.

7. Click Back, and then select the Write to Event Log option. Click the Do It button to show thesecurity error.

8. Close Internet Explorer.

Sandboxing Privileged Code1. Start Visual Studio .NET.

2. Open the following solution C:\Courses\DeveloperSecurity\Democode\Session03\lowPrivASPNET\lowPrivASPNET.sln.

3. Add a new C# class library project to the solution. Call the new project EventLogger.

4. Open a Visual Studio .NET 2003 Command Prompt.

5. cd C:\Courses\DeveloperSecurity\Democode\Session03\lowPrivASPNET\EventLogger

6. Type sn.exe -k eventloggerkeypair.snk.

7. In Visual Studio .NET, edit AssemblyInfo.cs for the EventLogger project.

8. Modify the AssemblyKeyFile line to:[assembly: AssemblyKeyFile(@"..\..\eventloggerkeypair.snk")]

9. Configure the Assembly Version:[assembly: AssemblyVersion("1.0.0.0")]

10. Below the AssemblyVersion line, add the AllowPartiallyTrustedCallersAttribute as follows:[assembly:AllowPartiallyTrustedCallersAttribute()]

11. Add using System.Security; to the top of the AssemblyInfo.cs module for the EventLoggerproject.

Page 107: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 31

12. Right-click default.aspx and select View Code.

13. Locate the Button1_Click method.

14. Within the Button1_Click method, locate the if block that begin:

if (RadioButtonList1.SelectedValue == "Event")

15. Select all the code inside the braces for this if block except for the line that reads:

TextBox1.Text = "Event log entry written successfully";

16. From the Edit menu, click Cut.

17. Double-click Class1.cs.

18. Type public static string writeEvent() directly above the public Class1() constructor functionand press ENTER.

19. Type { and press ENTER twice.

20. Type } and press ENTER.

21. Place the cursor on the line inside the curly braces {} you have just entered, and click Edit -Paste.

Page 108: 2806 Microsoft Security Guidance Training for Developers

32 Session: Writing Secure Code � Best Practices

22. Modify the code you have just pasted to that it reads:

public static string writeEvent(){

try{

string source = "Event Source";string log = "Application";string eventText = "Writing to the event log";EventLogEntryType eventType = EventLogEntryType.Information;

//Assert permissionEventLogPermission eventPerm;eventPerm = new

EventLogPermission(EventLogPermissionAccess.Instrument,"LONDON");eventPerm.Assert();

//Check to see if the source exists.if(!EventLog.SourceExists(source)){

//The keys do not exist, so register your application// as a source

EventLog.CreateEventSource(source, log);}

//Write to the log.EventLog.WriteEntry(source, eventText, eventType);return "Event log entry written successfully";

}finally{CodeAccessPermission.RevertAssert();

}}

23. Add using System.Diagnostics; and using System.Security; to the top of Class1.cs.

24. Select the EventLogger project in the Solution Explorer window, and click Build � BuildEventLogger.

25. Install the assembly in the GAC by switching to the command window, and then typing cdbin\debug

26. Type gacutil -i eventlogger.dll and press ENTER.

Page 109: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 33

Using Sandboxed Assemblies1. In the command window, get the public key token of the signed assembly by typing sn �Tp

eventlogger.dll

2. In Visual Studio .NET, edit Web.config in the lowPrivASPNET Web application. Change the<compilation> section to:.

<compilationdefaultLanguage="c#"debug="true"><assemblies>

<add assembly="eventlogger, Version=1.0.0.0,Culture=neutral, PublicKeyToken=ea...d6"/>

</assemblies></compilation>

3. Replace ea�d6 with the public key token you found in the previous step.

4. Add a Reference to the Web project. In the Add Reference window, click the Browse buttonand navigate to C:\Courses\DeveloperSecurity\Democode\Session03\lowPrivASPNET\EventLogger\bin\debug\ folder. Select EventLogger.dll and click Open.

5. Click OK.

6. Edit default.aspx.cs. In the Button1_Click method, modify the code to call the static method inEventLogger, as follows:

if (RadioButtonList1.SelectedValue == "Event"){

TextBox1.Text = EventLogger.Class1.writeEvent();}

7. Build the solution.

8. If Internet Explorer is running, close Internet Explorer.

9. In the command window, type iisreset to restart IIS.

10. Open Internet Explorer.

11. Browse to http://london/SecDev/lowPrivASPNET

12. Select the Write to Event Log option. Click the Do It button to show that it works again.

13. Close all applications.

Page 110: 2806 Microsoft Security Guidance Training for Developers

34 Session: Writing Secure Code � Best Practices

Reduce the Attack Surface

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Hackers commonly exploit weaknesses in platform services, such as the Index Service in IIS, tocompromise applications.

! Hackers can also attack all the interfaces that your applications expose.! By turning all unused platform services off and limiting the number of interfaces exposed by your

application, you can limit the attack vectors that hackers can exploit.! Microsoft Windows Server� 2003, for example, installs with the majority of services turned off.

Administrators must explicitly enable services. This extends to features such as IIS and ASP.NET,which are disabled out of the box.

Page 111: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 35

Do Not Trust User Input

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Consider all user input as harmful until proven otherwise.! Look for valid input and deny everything else. Do not do the opposite and look for invalid data,

reject it, and then let everything else in.

• Hackers can circumvent client-side validation. Consider performing validation often and closeto the threats. For example, validate data on the server before committing it to a database.

• Invalidate input that is too large.

• Invalidate input that contains dangerous characters or keywords, such as scripting elements(<script>, <object>), reserved SQL characters and keywords (- -, INSERT, xp_cmdshell), orfile traversal characters (..\).

! Use the mantra: Constrain, Reject, and Sanitize.

• One of the most powerful ways to constrain data input is through validation controls andregular expressions.

• The example regular expression ( \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* ) checks thatthe input string is of the correct form for an Internet e-mail address.

Page 112: 2806 Microsoft Security Guidance Training for Developers

36 Session: Writing Secure Code � Best Practices

Demonstration 2: Windows Forms Validation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will show how to add input validation code to a Windows Formapplication. ASP.NET developers have the benefit of having a large number of controls to help withinput validation. In Windows Forms, the developer must write more code to achieve the sameresult. However, it is still easy to implement.

Viewing a Non-Validating ApplicationPerform the steps on the LONDON VPC.

1. If you are not already logged on, log on to London by using the OrdinaryUser account with apassword of Passw0rd.

2. Using Windows Explorer, navigate to the C:\Courses\DeveloperSecurity\DemoCode\Session03\WindowsFormsValidation\bin folder and double-click WindowsFormsValidation.exe.

If file extensions are not shown, this will simply be WindowsFormsValidation

3. Do not enter any name input and select a date on a Sunday (weekends should not be allowed) toshow that no validation is being performed.

4. No errors occur. Close the application

Page 113: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 37

Adding Input Validation1. In Visual Studio .NET, open C:\Courses\DeveloperSecurity\DemoCode\Session03\

WindowsFormsValidation\ WindowsFormsValidation.sln.

2. Open Form1.vb in design view.

3. From the Toolbox, drag an ErrorProvider control onto the form. Visual Studio .NET places itin the Component Box under the form.

4. Right-click the form, and then click View Code.

5. Select nameTextBox from the left-hand dropdown box and Validating from the right-handdropdown box.

6. Inside the nameTextBox_Validating method, type the following:

If (nameTextBox.Text = "") ThenErrorProvider1.SetError(nameTextBox, _

"Please enter your Name")Else

ErrorProvider1.SetError(nameTextBox, "")End If

7. Select eventDateTimePicker from the left-hand dropdown box and Validating from the right-hand dropdown box.

8. Inside the eventDateTimePicker_Validating method, type the following:

If ((eventDateTimePicker.Value.DayOfWeek = _DayOfWeek.Sunday) _

Or (eventDateTimePicker.Value.DayOfWeek = _DayOfWeek.Saturday)) Then

ErrorProvider1.SetError(eventDateTimePicker, _"Please select a weekday")

ElseErrorProvider1.SetError(eventDateTimePicker, "")

End If

9. Build and run the application. Show that the user must enter a name and that the date must be aweekday.

Validating the Complete Form1. Go to Design view of the form, and then double-click the button.

2. Inside the Button1_Click method, type the following:

If ErrorProvider1.GetError(nameTextBox) <> "" _OR ErrorProvider1.GetError(eventDateTimePicker) <> "" Then

MessageBox.Show("Please enter valid data")End If

3. Build and run the application. Show that the warning message displays until the user enters aname and a date during the week.

4. Close all applications.

Page 114: 2806 Microsoft Security Guidance Training for Developers

38 Session: Writing Secure Code � Best Practices

Defense in Depth (1 of 3) � Use Multiple Gatekeepers

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! People make mistakes, which means that one layer of defense is not good enough. By buildingmultiple layers of defense, you can increase the security of a system.

! Software architects should design systems with multiple defense barriers. For example, if you areexposing sensitive data in a server running SQL Server on a Web page, you can place a firewall infront of the Web server to prevent unauthorized access to it. In addition, you can require clients toconnect by using Secure Sockets Layer (SSL). You can strengthen the security perimeter byplacing an additional firewall in front of the server running SQL Server and requiring all thecomputers on the internal network to use Internet Protocol security (IPSec).

! Threat modeling defines the location and importance of defensive strategies.

Page 115: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 39

Defense in Depth (2 of 3) � Apply Appropriate Measures for EachLayer

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In addition to implementing multiple layers of security in systems, you can also add layers ofsecurity in applications. For example, you can have an application .exe file authenticate andauthorize users. Then, each supporting application .dll file can also authenticate and authorizeusers.

! If only the application .exe file authenticates and authorizes users, then a hacker might circumventit and call the application .dll file independently.

! As a last line of defense, be sure to use access control lists (ACLs) to secure files and folders.! Increased security often comes with a cost in performance. Determine the depth of defense for

software components based on threat modeling and prioritization that is performed during theenvisioning phase.

Page 116: 2806 Microsoft Security Guidance Training for Developers

40 Session: Writing Secure Code � Best Practices

Defense in Depth (3 of 3) � Use Strong ACLs on Resources

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! During the design phase of a software project, document all of the ACL requirements of theapplication and develop them into the application.

! You can use ACLs to restrict access to a variety of items including files, folders, Web pages,registry settings, database files, printers, and objects in Active Directory® directory service.

! To protect sensitive files and folders for your application, programmatically create ACLs duringinstallation.

! Be explicit, and use the DENY ACE often.! A NULL discretionary access control list (DACL) is a way of granting all access for an object to

all users, including hackers. For example, a hacker can change a NULL DACL to Everyone DenyAccess. Other dangerous access control entries (ACEs) include WRITE, WRITE_DAC,WRITE_OWNER, and DELETE.

Page 117: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 41

Do Not Rely on Security by Obscurity

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! One issue with encryption is the need to store encryption keys securely.! You may be tempted to hide keys inside text files, html files, or data files and use to extract the

required data when required. However, it is very easy for an attacker to find hidden information.Concealing secrets can contribute to overall security, but it must never be your primary securitymechanism.

! You should always assume that an attacker knows everything you do, and has access to all sourcecode and diagrams.

Page 118: 2806 Microsoft Security Guidance Training for Developers

42 Session: Writing Secure Code � Best Practices

Use Data Protection API (DPAPI) to Protect Secrets

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! DPAPI is an encryption application programming interface (API) that ships with MicrosoftWindows Server 2003 and Microsoft Windows XP. DPAPI is a powerful encryption class builtinto the operating system that uses a user�s password to derive user-specific or computer-specificencryptions.

! The Data Protection API can be used to protect security-sensitive data, such as databaseconnection strings and service account credentials. It is password-based, and can store data ineither a user or machine store.

! There are two ways to use it: the user store approach, where you protect data such that only thedata owner can access it, or the machine store approach, where any user on the machine can accessit. You select the latter case by setting the CRYPTPROTECT_LOCAL_MACINE flag in thedwFlags field when calling the API.

! The user store approach affords an additional layer of security because it limits who can access thesecret. Only the user who encrypts the data can decrypt the data. However, use of the user profilerequires additional development effort when DPAPI is used from an ASP.NET Web application.You need to take explicit steps to load and unload a user profile. ASP.NET does not automaticallyload a user profile.

! The machine store approach is easier to develop because it does not require user profilemanagement. However, unless an additional entropy parameter is used, it is less secure becauseany user on the computer can decrypt data. (Entropy is a random value designed to makedeciphering the secret more difficult.) The problem with using an additional entropy parameter isthat this must be securely stored by the application, which presents another key management issue.With this approach, you should also protect the encrypted data produced by DPAPI with an ACLwhen you store it in persistent storage.

Page 119: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 43

Demonstration 3: DPAPI

*****************************ILLEGAL FOR NON-TRAINER USE******************************

This demonstration shows how to use DPAPI to encrypt data in Web.config, such as a connectionstring. It also shows how to use the Aspnet_setreg utility to encrypt user credentials in Web.config.

IMPORTANT: This demo uses user accounts that are set up in Demo 4: Authorization Techniquesusing the Trusted Subsystem Model in the session Essentials of Application Security. If you havenot run that demonstration, you must perform the following tasks to prepare for this demonstration:

! Create a local account on London called OrderReaders with password Passw0rd. Ensure that theUser must change password at next logon checkbox is not selected. Ensure that the Passwordnever expires checkbox is selected.

! Grant the new account write and modify access to the C:\Windows\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files folder. If you are prompted with a message about systemfolder security, click Yes.

! Create a local account on Denver called OrderReaders with password Passw0rd. Ensure that theUser must change password at next logon checkbox is not selected. Ensure that the Passwordnever expires checkbox is selected.

! In SQL Server Enterprise Manager on Denver:

• Create a login for OrderReaders.

• Set the default database for OrderReaders to Northwind.

• Permit the OrderReaders access to the Northwind database.

• Add OrderReaders to the db_datareader role for the Northwind database.

Page 120: 2806 Microsoft Security Guidance Training for Developers

44 Session: Writing Secure Code � Best Practices

Storing Connection Strings in Web.configPerform the steps on the LONDON VPC.

1. If you are not already logged on, log on to London by using the OrdinaryUser account with apassword of Passw0rd.

2. Open Visual Studio .NET 2003.

3. Open the solution C:\Courses\DeveloperSecurity\Democode\Session03\dpapi.sln

4. Right-click default.aspx and click Set at Start Page.

5. Run the solution without debugging by pressing CTRL + F5.

6. If prompted about Enhanced Security, select the In the future, do not show this messagecheckbox and click OK.

7. Close Internet Explorer.

8. Show the code in default.aspx.cs.

9. Expand the Webform Designer Generated Code region, and show where the connectionstring is hard-coded into the application.

10. Show default.aspx in design view.

11. Right-click sqlConnection1 and then click Properties.

12. Expand Dynamic Properties. Click Connection String, and then click the ellipsis button.Select the Map property to a key in configuration file checkbox, and then click OK.

13. Show Web.config and Default.aspx.cs to show that Visual Studio .NET has moved theconnection string definition to the configuration file.

Encrypting Connection Strings with DPAPI1. In Visual Studio .NET, view the code for class1.cs in the EncryptString project.

2. Point out the call to the dp.Encrypt method.

3. Optionally, briefly show the code to DataProtection.cs in the dpapiLibrary project showing thecalls to the data protection API.

4. In Solution Explorer, right-click the EncryptString project, point to Debug, and click Startnew instance.

5. When the Input: prompt appears, switch to viewing Web.Config.

6. Copy the text of the connection string from where it is defined at the bottom of Web.config.

7. Switch to the Command window, and then right-click the title bar, point to Edit, and clickPaste.

8. Press ENTER. The encrypted text is written to a file.

9. Press ENTER.

10. In Visual Studio .NET, on the File menu, point to Open and click File.

Page 121: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 45

11. Open the file C:\Courses\DeveloperSecurity\Democode\Session03\dpapi\EncryptString\Encrypted.txt.

12. Copy the contents of the file.

13. Switch to Web.config. Remove the existing connection string text and paste in the encryptedversion.

14. Save Web.config.

15. In default.aspx.cs, expand the WebDesigner Generated Code region if it isn�t already.

16. Locate the line beginning this.sqlConnection1.ConnectionString = (�

17. Change to:

//// sqlConnection1//DataProtection dp = new

DataProtection(DataProtection.Store.USE_MACHINE_STORE);string appSettingValue =

((string)(configurationAppSettings.GetValue("sqlConnection1.ConnectionString", typeof(string))));

byte[] dataToDecrypt =Convert.FromBase64String(appSettingValue);

string connStr =Encoding.ASCII.GetString(dp.Decrypt(dataToDecrypt,null));

this.sqlConnection1.ConnectionString = connStr;

18. Press CTRL + F5 to run the application.

19. Close Internet Explorer.

Installing the Aspnet_setreg Utility1. View Web.Config again. Find the <Identity �> element.

2. Notice that this application uses impersonation, and the username and password are in the file inclear text.

3. Open Windows Explorer.

4. Navigate to C:\Courses\DeveloperSecurity\Democode\Session03\Aspnet_setreg.

5. Double-click aspnet_setreg.exe.

6. Enter C:\Tools as the unzip folder.

7. Open a Command window.

8. Type cd C:\Tools and press ENTER.

9. Enter aspnet_setreg /? to show all the options available with this utility.

Page 122: 2806 Microsoft Security Guidance Training for Developers

46 Session: Writing Secure Code � Best Practices

Using Encrypted Attributes in a Configuration File1. From the Start menu, point to All Programs | Accessories. Right-click Command Prompt

and click Run as.

2. Select The following user and provide a User name of Administrator and a password ofP@ssw0rd.

3. Type cd C:\Tools and press ENTER.

4. At the command prompt, type aspnet_setreg.exe -k:SOFTWARE\MY_SECURE_APP\identity -u:"OrderReaders" -p:"Passw0rd"

5. This command also generates output that specifies how to change your Web.config orMachine.config file so that ASP.NET will use these keys to read that information from theregistry.

6. Edit Web.Config in Visual Studio .NET.

7. Change the <identity> section to:

<identity impersonate="true"userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,userName"password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password" />

Granting Permissions on Registry Keys1. Switch back to the command window.

2. Type regedt32 then press ENTER. Registry Editor starts.

3. Right-click the HKEY_LOCAL_MACHINE\SOFTWARE\MY_SECURE_APP\ subkey,and click Permissions.

4. Click Add. In the dialog box that opens, type NETWORK SERVICE and then click CheckNames.

5. Click OK.

6. Select Allow checkbox for the Read permissions, and then click Advanced.

7. Select the permission entry for the Network Service account and then select the Replacepermission entries on all child objects with entries shown here that apply to child objectscheckbox.

8. Click OK.

9. In the Security message box, click Yes.

10. Click OK to close the Permissions dialog box.

11. Close Registry Editor.

12. In Visual Studio .NET, press CTRL + F5 to demonstrate that the application works.

13. Close all applications.

Page 123: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 47

Fail Intelligently (1 of 2)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! When programmatically authorizing users based on their credentials or validating input, alwaysfollow a specific pattern. First, attempt to authorize or validate the data. Accept only valid input,and reject everything else. Do not attempt to invalidate the user or data and then accept everythingelse.

Page 124: 2806 Microsoft Security Guidance Training for Developers

48 Session: Writing Secure Code � Best Practices

Fail Intelligently (2 of 2)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Do not reveal error information to end users. Ensure production code does not contain errormessages that developers use during production. If it is necessary to capture error information,write it to an event log.

! Do not consume resources for lengthy periods of time after a failure. It may result in a DoS attack.! Your error handling should be structured in such a way that details of the error are not propagated

back to the user.! If your program has vulnerabilities in specific areas, write code to update an error log with any

activities that appear suspicious.

Page 125: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 49

Test Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Involve test teams at the very beginning of the design phase for each project. They can providevaluable feedback.

! Most testing is designed to prove product features work correctly. Security testing should bedesigned to make features fail. Examples of testing security include attempting to spoof useridentities, submitting bad input, or creating DoS attacks.

! To defend against hackers, you must ensure that your test team has the same level of knowledgeand access to the same technologies as hackers.

! Decomposing an application involves logically separating components, interfaces, and data toidentify important assets and likely vulnerabilities. Use threat modeling to define security testingstrategies.

! Attack every conceivable and inconceivable vulnerability. Explicitly test security, not justfeatures.

! Use all of the means at your disposal to attack the application on all fronts.! Use low-level programming languages such as C++ to find hidden vulnerabilities in the

application. You can also use common scripts to automate attacks and create bad data.! Submit data that is too long or too short, contains empty or NULL values, and contains completely

random or only partially incorrect data.! Try to delete critical files or place DENY DACLs on critical resources.! Test with an account that is not an administrator account to accurately capture error information.! If you have access to source code, review it.

Page 126: 2806 Microsoft Security Guidance Training for Developers

50 Session: Writing Secure Code � Best Practices

Learn from Mistakes

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! �There is only one thing more painful than learning from experience and that is not learning fromexperience.� � Archibald McLeish (1892 � 1982), American poet.

! Approach every bug as a learning opportunity. If you fail to learn from a mistake, it is highlyprobable that you will make the same mistake in the future.

Page 127: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 51

Session Summary

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 128: 2806 Microsoft Security Guidance Training for Developers

52 Session: Writing Secure Code � Best Practices

Next Steps

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Next steps include going to the Microsoft Web site to:

• Get the latest security information.

• Get additional security training.

Page 129: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 53

For More Information

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! More technical information for IT professional and developers is available on the following Websites:

• Microsoft Security Site (all audiences)

• http://www.microsoft.com/security

• MSDN Security Site (developers)

• http://msdn.microsoft.com/security

• TechNet Security Site (IT professionals)

• http://www.microsoft.com/technet/security

Page 130: 2806 Microsoft Security Guidance Training for Developers

54 Session: Writing Secure Code � Best Practices

Questions and Answers

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 131: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Best Practices 55

Clinic Evaluation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Your evaluation of this clinic will help Microsoft understand the quality of yourlearning experience.

At a convenient time before the end of the clinic, please complete a clinicevaluation, which is available at http://www.CourseSurvey.com.

Microsoft will keep your evaluation strictly confidential and will use yourresponses to improve your future learning experience.

Page 132: 2806 Microsoft Security Guidance Training for Developers
Page 133: 2806 Microsoft Security Guidance Training for Developers

Contents

What We Will Cover 1

Session Prerequisites 2

The Need For Secure Code 3

Defending Against Memory Issues 8

Defending Against Arithmetic Errors 15

Defending Against Cross-Site Scripting 21

Defending Against SQL Injection 29

Defending Against Canonicalization Issues 35

Defending Against CryptographyWeaknesses 41

Defending Against Unicode Issues 44

Defending Against Denial of Service 48

Session Summary 51

Session: Writing Secure Code � ThreatDefense

Page 134: 2806 Microsoft Security Guidance Training for Developers

Information in this document, including URL and other Internet Web site references, is subject tochange 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 applicablecopyright laws is the responsibility of the user. Without limiting the rights under copyright, no partof this document may be reproduced, stored in or introduced into a retrieval system, or transmittedin any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), orfor any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectualproperty rights covering subject matter in this document. Except as expressly provided in anywritten license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

2004 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Windows Server, Explorer, JScript, SQL Server,and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of theirrespective owners.

Page 135: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 1

What We Will Cover

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this session, we will focus on writing secure code. Specifically, we will discuss:

! The need for secure code.! Defending against memory issues.! Defending against arithmetic errors.! Defending against cross-site scripting.! Defending against SQL injection.! Defending against canonicalization issues.! Defending against cryptography weaknesses.! Defending against Unicode issues.! Defending against denial of service.

Page 136: 2806 Microsoft Security Guidance Training for Developers

2 Session: Writing Secure Code � Threat Defense

Session Prerequisites

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 137: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 3

The Need For Secure Code

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on the need for secure code. Specifically, we will discuss:

! The need for secure code.! Threat scenarios.! Potential attackers.! Common types of attack.

Page 138: 2806 Microsoft Security Guidance Training for Developers

4 Session: Writing Secure Code � Threat Defense

The Need For Secure Code

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! There has always been a need for secure code. However, with the birth of the Internet and theever-increasing complexity of software and systems, the need for secure code has never been sourgent. The comments on the slide illustrate just a few of the results of recent attacks.

! One simple lapse in code design or implementation could lead to another security-based newsheadline.

Page 139: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 5

Threat Scenarios

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In the current age, it is safe to say that data is no longer accessed simply through a local areanetwork (LAN). Instead, many new data retrieval scenarios exist and will exist in the future.Unfortunately, as investment in new data retrieval devices increases, data thieves have a greaterrange of potential target points.

! When designing, developing, and testing software, a developer should consider the differentmechanisms that are and will be used to access data. Each access point should be considered,tested, and proven to be secure.

Page 140: 2806 Microsoft Security Guidance Training for Developers

6 Session: Writing Secure Code � Threat Defense

Potential Attackers

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! When designing and coding secure systems, never underestimate the enemy. The Internet playshost to a wide range of potential attackers, ranging from hobby hackers to professional datathieves.

! When your software system goes live, you should not be surprised if it falls under attack.

Page 141: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 7

Common Types of Attack

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Organizational attacks involve one organization breaking into your network to try to accessconfidential information in order to gain a business advantage.

! Hackers enjoy exercising their skills by attempting to bypass security safeguards and gain illegalaccess to your network.

! Automated attacks use software to scan for network vulnerabilities or to implement an electronicbrute force attack. Brute force attacks involve trying many different user names, passwords, orother credentials to gain access to your resources.

! Denial of service (DoS) attacks flood a server with requests for action, thus rendering it incapableof providing its normal service.

! Viruses, Trojan horses, and worms are harmful programs that act by exploiting some knownvulnerability to install themselves on a computer (perhaps by entering as an attachment to an e-mail). Once they are present on a computer, they distribute copies of themselves to otherconnected computers, and these copies also replicate themselves, resulting in a rapid infection ofthe computer network.

! Accidental breaches in security often result from poor practices or procedures. For example, ifsecurity information, such as user names and passwords, is exposed, an attacker can exploit thatinformation to gain access to your network.

Page 142: 2806 Microsoft Security Guidance Training for Developers

8 Session: Writing Secure Code � Threat Defense

Defending Against Memory Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against memory issues. Specifically, we will discuss:

! What a buffer overrun is.! Possible results of buffer overruns.! An example of a stack-based buffer overrun.! Heap overruns.! Defending against buffer overruns.

Page 143: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 9

What Is a Buffer Overrun?

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! A buffer overrun occurs when the size of a variable is not large enough to hold a given value andthe memory buffer is overwritten with the extra data. Buffer overruns are one of the most commonand, potentially, one of the most damaging security risks.

! Buffer overruns primarily exist in C/C++ code because of the low level of memory managementthat is available with these languages.

! There are different kinds of buffer overruns such as stack-based buffer overruns, heap overruns,V-table and function pointer overwriting, and exception handler overwriting.

! Buffer overruns can be exploited by worms:

• The worm created by Robert T. Morris in 1988 was one of the first major buffer overrunexploits to receive public attention. It nearly brought the Internet to a standstill.

• The CodeRed Worm was the result of an exploited buffer overrun in Microsoft InternetInformation Services (IIS).

! Buffer overruns are sometime called buffer overflows. These terms are synonymous.

Page 144: 2806 Microsoft Security Guidance Training for Developers

10 Session: Writing Secure Code � Threat Defense

Possible Results of Buffer Overruns

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! During normal execution, when a procedure is called, a return address that marks the location ofthe calling code is placed on the stack. As a result, when the procedure finishes executing, controlreturns to the original location. Following the return address, parameters and local variables arepushed on the stack. At the end of the procedure, the stack unwinds and memory space isreclaimed. When the stack unwinds to the return address, control returns to the original location.

! With buffer overruns, there is not a strict limit on the amount of data that can be placed on thebuffer. Hackers can overwrite nearly anything on the stack. The hacker can also control the valuesthat are placed on the stack, for example, the return address. If the hacker overwrites the returnaddress with the address of a malicious procedure, that procedure executes with the sameprivileges as the original program.

! At best, an access violation error occurs, and the process shuts down. If you are unlucky,instability may result, and variables may be overwritten, resulting in unexpected behavior of theprogram. At worst, the hacker overwrites the return address, and malicious code may be executedwith the same privileges as your process. This can result in severe damage if your process runswith administrator or elevated privileges. Therefore, you must always apply the general riskmitigation strategy of running processes with the least possible privileges.

Page 145: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 11

Stack-Based Buffer Overrun Example

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The above code is a typical example of an unsafe function. Like many C/C++ applications, itdefines a buffer that is �just� big enough (4 bytes) to hold the data it is designed to store.

! However, what happens if a string bigger than 4 bytes is passed into the function? As the stackworks from top to bottom (high memory address to low memory address), the strcpy functioncould overwrite the return address in the stack. This is very dangerous, because if the returnaddress is overwritten with the address of a malicious procedure, that procedure executes with thesame privileges as the original program.

Page 146: 2806 Microsoft Security Guidance Training for Developers

12 Session: Writing Secure Code � Threat Defense

Heap Overruns

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Heap overruns are different from stack-based buffer overruns.! When you perform an operation such as malloc in the C language, memory is allocated on the

heap. A heap overrun corrupts data stored on the heap.! The data that is stored on the heap is much more variable than that on the stack. The heap data

depends on how many dynamic buffers the programmer allocates in the code, and what is stored inthose buffers.

! If the heap is used to store pointers to functions or classes, then a hacker can exploit the uncheckedinput buffer in a way similar to a stack-based overrun. However, the hacker must do much moreinvestigative work to make the exploit than with a buffer overrun. For example, they mustdetermine whether a function pointer is adjacent to the input buffer.

Page 147: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 13

Defending Against Buffer Overruns (1 of 2)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Be very cautious when using certain functions:

• You should not use strcpy. This function provides no buffer length checks, so your code thatuses strcpy can easily be exploited by hackers wanting to perform buffer overruns.

• Be alert to the risks posed by strncpy. Although strncpy avoids the buffer checking problem ofstrcpy because it only copies the string up to the zero terminator or up to the size specified, itcan also result in access violations. For example, you want to make sure that the string in thebuffer is zero-terminated; however, the zero can be added past the end of the buffer. While thiscannot lead to code injection attacks, hackers can use potential programming flaws like this toachieve access violations and, as a result, software disruption.

• Be alert to the risks posed by CopyMemory and MultiByteToWideChar. Both these functionsrely on you passing in buffer sizes and destination addresses and getting them right! If you getthem wrong, your program crashes, at best. At worst, a clever hacker can corrupt yourfunction�s return address to get his own function to execute with your code's privileges.

! The /GS compile option is new in Microsoft Visual C++ .NET and helps prevent buffer overrunsby placing a random value into the stack between the local data and the return address. When thefunction returns, the random value is verified. This does not prevent all buffer overruns and doesnot replace careful programming. This compile option is for unmanaged code and does not affectmanaged code.

! Strsafe.h provides a set of safer string-handling functions for the C programming language. Youcan download it as part of the Microsoft Windows® Core SDK.

Page 148: 2806 Microsoft Security Guidance Training for Developers

14 Session: Writing Secure Code � Threat Defense

Defending Against Buffer Overruns (2 of 2)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Check array bounds and do not exceed the array capacity.! Use proven wrapper classes that already provide bounds checking, but make sure that the bounds

checking remains in all configurations, such as release builds.! Check file-path lengths. Ensure that path lengths do not exceed 260 characters by using

_MAX_PATH.! Do not create your own file path�processing methods. Use recognized methods such as splitpath.! Ultimately, use managed code, but identify and check all calls to unmanaged APIs and COM

Interop. In managed code, it is much easier to avoid buffer overruns, because the code you writedoes not have direct access to pointers, computer registers, or memory. However, any unmanagedcode that you call, either through PInvoke or COM components, may still suffer from bufferoverruns.

Page 149: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 15

Defending Against Arithmetic Errors

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against arithmetic errors. Specifically, we will discuss:

! Arithmetic errors.! Defending against arithmetic errors.

Page 150: 2806 Microsoft Security Guidance Training for Developers

16 Session: Writing Secure Code � Threat Defense

Arithmetic Errors

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Arithmetic errors occur when the limitations of a variable are exceeded.! Arithmetic errors can lead to more serious bugs such as buffer overruns or denial of service

attacks.! Arithmetic errors are commonly overlooked and underestimated, because they are difficult to

trace.! Arithmetic errors include:

• Overflows. For example a 16-bit unsigned integer is capable of storing values between 0 and65535, so the following code results in an overflow:unsigned int i=65530;i+=10;In this case, no runtime exception would occur, and thus the error would continue untraced.

• Underflows. For example, the smallest value a double can hold is 1.7*10-308. As a result, iftwo numbers are multiplied and produce a value less than that, and the result is stored in adouble variable, an underflow occurs.

Page 151: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 17

Defending Against Arithmetic Errors

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Know the limitations of the data type that you are using.! Wherever possible, check the results of calculations to verify that arithmetic errors have not

occurred.! Write your own defensive safe arithmetic functions. You can reuse them throughout your code.! If coding in C++, consider using a template class for arithmetic calculations.

Page 152: 2806 Microsoft Security Guidance Training for Developers

18 Session: Writing Secure Code � Threat Defense

Demonstration 1: Memory Issues and Data Type Errors

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Investigating Buffer Overruns1. SWITCH TO THE LONDON VPC

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Open Microsoft Notepad. On the Format menu, click Font, and then switch to 16-point fontsize.

4. On the File menu, click Open, and then open the fileC:\Courses\DeveloperSecurity\Democode\Session02\BufferOverrun\BODEMO.CPP.

5. Open a Command Prompt window. In properties, set the font to 10x18.

6. Type cd C:\Courses\DeveloperSecurity\Democode\Session02\BufferOverrun and pressENTER.

7. Type bodemo AAAAAAAAAAAAAAAAAA and then press ENTER.

8. Explain the output displayed in the command window.

9. When the Application Error message box appears, explain that this is caused by the stackoverrun. Click OK.

10. Close the command window and Notepad.

Page 153: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 19

Using the /GS Compiler Switch1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Open Notepad. On the Format menu, click Font, and then switch to 16-point font size.

4. On the File menu, click Open, and then open the fileC:\Courses\DeveloperSecurity\Democode\Session02\BufferOverrun\BODEMO.CPP.

5. Open a Command Prompt window. In properties, set the font to 10x18

6. Type cd C:\Courses\DeveloperSecurity\Democode\Session02\GSCompileOption and thenpress ENTER.

7. Type bodemo 123456789112 and then press ENTER.

8. Explain the output displayed in the command window.

9. When the Buffer overrun detected message box appears, explain that this is caused by the stackoverrun but that the application will not be allowed to continue. Click OK.

10. Close the command window and Notepad.

Using STRSAFE.H1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Open Notepad. On the Format menu, click Font, and then switch to 16-point font size.

4. On the File menu, click Open, and then open the fileC:\Courses\DeveloperSecurity\Democode\Session02\SafeStrings\SafeStrings.cpp.

5. Open a Command Prompt window. In properties, set the font to 10x18.

6. Type cd C:\Courses\DeveloperSecurity\Democode\Session02\SafeStrings and then pressENTER.

7. Type SafeStrings and then press ENTER.

8. Explain the output in the command window.

9. Press ENTER.

Page 154: 2806 Microsoft Security Guidance Training for Developers

20 Session: Writing Secure Code � Threat Defense

Performing Safe Arithmetic Calculations1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Open Notepad. On the Format menu, click Font, and then switch to 16-point font size.

4. On the File menu, click Open, and then open the file C:\Courses\DeveloperSecurity\Democode\Session02\DemoSafeIntegerAddition\DemoSafeIntegerAddition.cpp.

5. Place the cursor next to the ConcatString method.

6. Open a Command Prompt window. In properties, set the font to 10x18.

7. Type cd C:\Courses\DeveloperSecurity\Democode\Session02\DemoSafeIntegerAdditionand then press ENTER.

8. Type DemoSafeIntegerAddition and then press ENTER.

9. Explain the output in the command window.

10. Press ENTER.

11. Close all applications.

Page 155: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 21

Defending Against Cross-Site Scripting

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against cross-site scripting. Specifically, we willdiscuss:

! What cross-site scripting is.! Two common exploits of cross-site scripting.! Form-based attacks.! Defending against cross-site scripting attacks.

Page 156: 2806 Microsoft Security Guidance Training for Developers

22 Session: Writing Secure Code � Threat Defense

What Is Cross-Site Scripting?

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Cross-site scripting involves Web applications that dynamically generate HTML pages. If theseapplications embed user input in the pages they generate, hackers can include content in thosepages that executes malicious script in client browsers.

! Scripting tags that hacker can embed in this way include <script>, <object>, <applet>, <form>,and <embed>.

! The browser executes the malicious script in the security context of the site from which it believesthe script came.

! The malicious script can perform a variety of actions, such as monitoring the user�s Web sessionand forwarding data to the hacker. The script can also modify what is displayed on the user�sscreen, giving them incorrect information. The script can make itself persistent so that themalicious script runs again when the user returns to the Web site.

! Cross-site scripting is not a vendor-specific issue. It affects every Web server and browser that iscurrently on the market. There is no single patch to fix it.

Page 157: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 23

Two Common Exploits of Cross-Site Scripting

*****************************ILLEGAL FOR NON-TRAINER USE******************************

With cross-site scripting, a hacker can:

! Insert HTML tags, such as <script>, into messages and postings on discussion boards. When aclient reads the message or posting with a browser, the malicious HTML tags are interpreted andexecuted on the client browser.

! Use HTML <form> tags to redirect private information. The hacker embeds HTML <form> tagsinto hyperlinks that are typically e-mailed to unsuspecting users. When the user clicks the link, a<form> tag is embedded in the HTML response from a legitimate Web site. The action attribute ofthe <form> tag is modified so that session information can be posted to the hacker�s Web site.

Page 158: 2806 Microsoft Security Guidance Training for Developers

24 Session: Writing Secure Code � Threat Defense

Form-Based Attacks (1 of 2)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In this example, the hacker embeds a <script> block in an e-mail that an unsuspecting user willread by using a Web browser. When the user opens the e-mail or reads the discussion board withher browser, the script is interpreted and executed on the client browser.

! Fortunately, most Web-based e-mail providers and discussion board administrators are aware ofthis type of attack and validate user input before rendering it arbitrarily to clients.

Page 159: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 25

Form-Based Attacks (2 of 2)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In this example, www.contoso.msft has a vulnerable page that echoes the �Name� value of thequerystring parameter. A hacker, who owns www.nwtraders.msft, sends an e-mail to anunsuspecting user with a link in it.

! When the user clicks the link, the name is echoed to the user�s browser by the welcome.asp pageat www.contoso.msft. The problem is that in this case the �name� is actually a collection ofHTML and Microsoft JScript®.

! In this example, the HTML is a form that posts a hidden field named �cookie� towww.nwtraders.msft, which is owned by the hacker. The script fills the hidden field with Mary�scookie for the current domain, www.contoso.msft, and then submits it to www.nwtraders.msft.The cookie is passed, therefore, from www.contoso.msft to www.nwtraders.msft.

Page 160: 2806 Microsoft Security Guidance Training for Developers

26 Session: Writing Secure Code � Threat Defense

Demonstration 2: Cross-Site Scripting

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Investigating Cross-Site Scripting1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Click Start, and then click Microsoft Visual Studio .NET 2003.

4. In Visual Studio .NET 2003, on the File menu, point to Open, and then click Project.

5. Navigate to the directory C:\Courses\DeveloperSecurity\Democode\Websites\DemoCSS.

6. Open the DemoCSS.sln solution.

7. In the Solution Explorer window, right-click CSSDemo.aspx, and then click View Code.

8. Locate the cmdSubmit_Click event.

9. Locate the Page_Load event.

10. Locate the Page_PreRender event.

11. On the Build menu, click Build Solution.

12. Close Visual Studio .NET 2003.

13. Using Microsoft Windows® Explorer, navigate to theC:\Courses\DeveloperSecurity\Democode\Websites\DemoCSS folder.

14. Double-click csslinks.html to open it with Microsoft Internet Explorer.

Page 161: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 27

15. If prompted about enhanced security configuration, select the In the future, do not show thismessage check box, and then click OK.

16. Click the first link on the page.

17. Click the Back button in your browser.

18. Click the second link on the page.

19. Click OK.

20. Click OK.

21. Close all applications.

Page 162: 2806 Microsoft Security Guidance Training for Developers

28 Session: Writing Secure Code � Threat Defense

Defending Against Cross-Site Scripting Attacks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Do not trust user input. Validate all user input to ensure that it does not contain any malicious tags,such as <script> and <object>.

! Do not blindly echo user input unless you are certain that it is not malicious.! Do not store secret information or sensitive data in cookies. Hackers can easily obtain cookie data.! Use the following security-related features of Microsoft Internet Explorer 6.0 Service Pack 1:

• HttpOnly cookies, which cannot be accessed from client-side script

• The <frame> tag security attribute, which can be used to apply Internet Explorer security zonesettings to the contents of the frame

! Use Microsoft ASP.NET 1.1 security features:

• The page validateRequest attribute, which tests for malicious tags within user input, andthrows an exception if any are found.

• The HTMLEncode and URLEncode methods, which can prevent scripts from running andhyperlinks from being active.

Page 163: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 29

Defending Against SQL Injection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against SQL injection. Specifically, we will discuss:

! What SQL injection is.! Examples of SQL injection.! Defending against SQL injection.

Page 164: 2806 Microsoft Security Guidance Training for Developers

30 Session: Writing Secure Code � Threat Defense

What is SQL Injection?

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! SQL injection occurs when developers dynamically build SQL statements by using user input. Thehacker can add their own commands to the SQL statement via the user input, thereby performingoperations that were not intended by the developer.

! Hackers can exploit this vulnerability in the following ways:

• Probing databases. Hackers can use the default Open Database Connectivity (ODBC)/OLEDB error messages returned in Active Server Pages (ASP) to investigate the design of adatabase.

• Bypassing authorization. Hackers can modify authorization-based SQL statements to gainentry to a database.

• Executing multiple SQL statements. Hackers can append additional SQL statements to the oneswritten by the developer.

• Calling system stored procedures on Microsoft SQL Server�. Hackers can execute some of thebuilt-in stored procedures that ship with SQL Server to access server functionality.

Page 165: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 31

Examples of SQL Injection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In the code example shown, the developer builds a string named sqlString by concatenating SQLstatements with input supplied by a user. Imagine that the user input is read directly from a textboxon a Web form or a Windows form, and then stored in the ID variable used in the code. A hackercan easily exploit this design by adding their own SQL statements as well as the expected querycriterion.

! The developer expects a discrete value to be typed in the textbox, and then inserts that valuebetween two single quotes in the SQL query�s WHERE clause. If the user simply enters a discretevalue such as ALFKI1001, the query behaves as the developer intended.

! However, a hacker may enter the following text:ALFKI1001' OR 1=1 --In this case, the hacker has provided the closing single quote for the first part of the criteria, andthen included an OR clause that always resolves to true. They have included the SQL commentmarker (--) so that the database server ignores the trailing quote in the developer's code. Theresulting SQL statement that would be executed is:SELECT HasShipped FROM OrderDetailWHERE OrderID = 'ALFKI1001' OR 1=1 --'This statement returns all rows from the OrderDetail table, rather than the single row intended bythe developer.

! A more damaging version of this type of SQL injection is:ALFKI1001' DROP TABLE OrderDetail --

In this case, the hacker has used a similar approach by providing the closing quote with the querycriterion, but has then included a data definition language (DDL) statement that permanentlydeletes another table in the database. Even though there are now two distinct statements, thedatabase server will process them both in a single batch. Again, the hacker has included the SQLcomment so that the database server ignores the trailing quote in the developer's code.

! An even more damaging version is:ALFKI1001' exec xp_cmdshell('fdisk.exe') --Exactly the same approach is used for the two previous examples. However, in this case, thehacker calls an extended stored procedure on the server, xp_cmdshell, which is capable of runningany operating system command. For this example, the hacker runs the FDisk.exe command, whichis capable of deleting and creating disk partitions.

Page 166: 2806 Microsoft Security Guidance Training for Developers

32 Session: Writing Secure Code � Threat Defense

Demonstration 3: SQL Injection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Investigating SQL Injection Issues1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Click Start, point to All Programs, and then click Microsoft SQL Server.

4. Right-click Query Analyzer, and then click Run as.

5. Select The following user and provide a user name of Administrator and a password ofP@ssw0rd

6. Click OK.

7. Ensure that the Start SQL Server if it is stopped check box is selected.

8. Ensure that Windows Authentication is selected.

9. Click OK.NOTE: You must be logged on as an administrator for all of the SQL statements to executecorrectly.

10. Select the Northwind database from the combo box on the toolbar.

11. On the Query menu, click Results in Text.

12. In the query window, type SELECT * FROM Customers WHERE City = 'Seattle'

13. Click Execute Query.

14. In the query window, modify the query so that it reads:SELECT * FROM Customers WHERE City = 'Seattle' OR 1=1

15. Click Execute Query.

Page 167: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 33

16. In the query window, modify the query so that it reads:SELECT * from Customers WHERE City ='Seattle'; UPDATE Customers SET Phone ='555-0100' WHERE CustomerID = 'anatr'

17. Click Execute Query.

18. In the query window, modify the query so that it reads:SELECT * FROM Customers WHERE City ='Seattle'; drop table "Order Details"

19. Click Execute Query.

20. In the query window, modify the query so that it reads:SELECT * FROM Customers WHERE City ='Seattle'; exec master..xp_cmdshell'ipconfig /release'

21. DO NOT EXECUTE this query. It is for demonstration purposes.

22. Close Query Analyzer and do not save the query when prompted.

Using Parameterized Queries to Defend Against SQL Injection1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Click Start, point to All Programs, and then click Microsoft Visual Studio .NET 2003.

4. In Visual Studio .NET 2003, on the File menu, point to Open, and then click Project.

5. Navigate to the directory C:\Courses\DeveloperSecurity\DemoCode\Session02\PQ.

6. Open the PQ.sln solution.

7. In Solution Explorer, double-click App.cs.

8. In the design window, double-click the Execute Sql.

9. On the File menu, click Close.

10. In Solution Explorer, double-click App.cs.

11. In the design window, double-click Execute Sql Using PQ.

12. On the Build menu, click Build Solution.

13. Using Windows Explorer, navigate to C:\Courses\DeveloperSecurity\DemoCode\Session02\PQ\Bin\Debug.

14. Right-click PQ.exe, and then click Run as.

15. Select The following user and provide a user name of Administrator and a password ofP@ssw0rd

16. Click OK.

17. Click Execute Sql.

18. Click Execute Sql Using PQ.

19. Close all applications.

Page 168: 2806 Microsoft Security Guidance Training for Developers

34 Session: Writing Secure Code � Threat Defense

Defending Against SQL Injection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Sanitize all input.

• Assume all input is harmful.

• Validate user input that contains dangerous keywords or SQL characters, such as�xp_cmdshell�, �- -�, and �;�.

• Consider using regular expressions to remove unwanted characters. This approach is safer thanwriting your own search and replace routines.

! Run with least privilege.

• Do not execute an SQL SELECT statement as �sa�. Create low-privilege accounts to accessdata.

• Use SQL permissions to lock down databases, stored procedures, and tables.

• Remove unused stored procedures.! Do not allow clients to view ODBC/OLE DB error messages. Handle these errors with your own

code. By default, ASP pages returns error messages to clients.! Enable logging of all user access, and set alerts to log all failed attempts to access objects.! Do not use string concatenations to build SQL queries. Instead, use parameterized queries or

parameterized stored procedures, because they explicitly define input and output values and do notprocess multiple statements as a batch.

Page 169: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 35

Defending Against Canonicalization Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against canonicalization issues. Specifically, we willdiscuss:

! What the canonicalization issues are.! Examples of canonicalization issues.! Defending against canonicalization issues.

Page 170: 2806 Microsoft Security Guidance Training for Developers

36 Session: Writing Secure Code � Threat Defense

Canonicalization Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Canonicalization is the process by which different forms of a name are resolved into a single,standard name called the canonical name. A canonicalization error is a parsing error that allowsan attacker to submit a malformed name (typically a malformed URL submitted to a Web server)that causes incorrect permissions to be applied by the resource being accessed.

! Sometimes, applications make decisions based on file names. For example, an application mightuse the .jpg or .gif file extension to determine how to access the file.

! If it can be avoided, you should not allow decisions to be based on a file name, because there arealternate representations that might elude your security implementation.

! There are alternate representations for file names, URLs, and devices that you may be unaware ofand for which you do not have a security strategy.

! Additionally, hackers can also traverse file and Internet directories by using canonicalization toexecute files in critical folder paths.

Page 171: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 37

Canonicalization Issues � Example 1: File Names

*****************************ILLEGAL FOR NON-TRAINER USE******************************

File names are subject to canonicalization issues. For example, the following names all provideaccess to the same file:

! MyLongFile.txtThis is the standard and obvious representation of a file name.

! MyLongFile.txt.The Microsoft Win32® file system determines that the trailing dot (.) should not be there andremoves it in this file name.

! MyLong~1.txtLegacy file allocation table (FAT) systems require file names to have a maximum of eightcharacters, followed by three characters that represent the file type. Later file systems, such asFAT32 and NTFS, allow longer file names. For backward compatibility, later systemsautomatically generate an 8.3-format file name that includes the first six legal characters, followedby an incrementing digit and a tilde (~).

! MyLongFile.txt::$DATAIn the NTFS file system, $DATA returns the default data stream for a file. This was exploited inIIS with ASP pages. The hacker can request the default stream of an ASP file, such ashttp://www.nwtraders.com/Default.asp::$DATA, and have the source code for this file returned.

Page 172: 2806 Microsoft Security Guidance Training for Developers

38 Session: Writing Secure Code � Threat Defense

Canonicalization Issues � Example 2: Character Representation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! On the Internet, there are many ways to represent and misrepresent characters that are used inURLs and Web pages. This includes US-ASCII, hexadecimal escapes, legal and illegal UnicodeTransformation Format (UTF) 8, double hexadecimal escapes, and dotless Internet Protocol (IP)addresses. The following list illustrates the canonicalization issues of character representation.

• http://www%2emicrosoft%2ecom%2ftechnet%2fsecurityThis is an example of a hexadecimal escape. %2e is the hexadecimal escape sequence for aperiod (.), and %2f is the hexadecimal escape sequence for a backslash (/).

• http://www.microsoft.com%c0%aftechnet%c0%afsecurityUTF-8 can be misrepresented by using varying byte sizes to represent the same character. Thisis an example of an alternate form of UTF-8. %c0%af is the double-byte UTF-8 representationof a backslash (/).

• http://www%25%32%65microsoft.com/technet/securityThis is an example of double escaping the period (.), which is first escaped to %2e and thenescaped again as follows:

• %25 is the hexadecimal escape sequence for the percent sign (%).

• %32 is the hexadecimal escape sequence for 2.

• %65 is the hexadecimal escape sequence for �e.�

• http://172.43.122.12 = http://2888530444This is the alternate IP address for a Web site. This is an example of a dotless IP address. Youcan calculate a dotless IP address by using the following formula: (1st octet X 224) + (2ndoctet X 216) + (3rd octet X 28) + (4th octet).

! If your validation code does not consider all the possible formats that a URL can take, you will notbe able to check for potentially dangerous strings.

Page 173: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 39

Demonstration 4: Canonicalization Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will see how dangerous it is to make security-based decisions by filename alone.

Investigating File Name Security Decisions1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Click Start, point to All Programs, and then click Microsoft Visual Studio .NET 2003.

4. In Visual Studio .NET 2003, on the File menu, point to Open, and then click Project.

5. Navigate to the directoryC:\Courses\DeveloperSecurity\Democode\Session02\Canonicalization.

6. Open the Canonicalization.sln solution.

7. In Solution Explorer, double-click Canonicalization.cpp.

8. Locate the function _tmain and the first call to strcmp.

9. Scroll down to the second call to strcmp.

10. Scroll down to the third call to strcmp.

11. Press CTRL + F5 to run the application.

12. Click Yes if prompted to build the project configuration.

13. Once the console application appears, press ENTER. Then, press ENTER again.

14. Close all applications.

Page 174: 2806 Microsoft Security Guidance Training for Developers

40 Session: Writing Secure Code � Threat Defense

Defending Against Canonicalization Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Countermeasures to address canonicalization issues include:

• Avoiding input file names where possible and instead using absolute file paths that cannot bechanged by the end user.

• Making sure that file names are well formed (if you must accept file names as input) andvalidating them within the context of your application. For example, you would check that theyare within your application's directory hierarchy.

• Ensuring that the character encoding is set correctly to limit how input can be represented.! Rather than make code-based decisions, secure those files that need to be protected by using the

file system.! No matter how careful you are, if you code in such a way that decisions are made based on URLs

or file names, it is very likely that you will overlook something.! If possible, you should set up IIS to prevent the application from accessing parent directories.

Page 175: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 41

Defending Against Cryptography Weaknesses

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against cryptography weakness issues. Specifically,we will discuss:

! Cryptography weaknesses.! Defending against cryptography weaknesses.

Page 176: 2806 Microsoft Security Guidance Training for Developers

42 Session: Writing Secure Code � Threat Defense

Cryptography Weaknesses

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Most encryption processes follow a specific path:1. First, you generate a key with a user password or preferably with a random value.

2. Then, you use a standardized algorithm, such as RC2, RC4, Data Encryption Standard(DES), or Triple DES, with the key you generated to encrypt the plaintext. The CryptoAPIprovides methods that allow you to generate random keys and also encrypt the plaintext.The resulting encrypted text is called the ciphertext.

3. Then, you must store the key in a safe place. This is the most important part. No matter howstrong the encryption algorithm is, if the hacker gets the key, the hacker can access yourdata.

! A hacker only needs three of the four cryptography components to decrypt data. For example, ifthe hacker knows the plaintext, ciphertext, and algorithm, the hacker can deduce the key.

! Although cryptography is widely used to secure data and communications, there are a number ofweaknesses associated with it:

• Inappropriate use of algorithms. This includes attempting to create your own algorithms, usingweak algorithms, and applying algorithms incorrectly.

• Failure to keep keys secure. The longer a key is used, the more likely it is that the key could becompromised. No algorithm remains secret for long. Most modern algorithms are standardizedand the formulas are public knowledge.

• Human factor. It is possible for human error to result in the accidental release of a private key.Therefore, you should implement rigorous security procedures.

Page 177: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 43

Defending Against Cryptography Weaknesses

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Use the following security measures to defend against cryptography weaknesses:

! Recycle keys periodically.! Use ACLs to restrict access to keys.! Store keys on an external device, such as a smart card or Pocket PC.! Use system access control lists (SACLs) to monitor activities.! Use larger keys to provide increased security.! Use DPAPI to simplify key management. DPAPI is an encryption application programming

interface (API) that is included with Microsoft Windows Server� 2003 and MicrosoftWindows XP. DPAPI is a powerful encryption class built into the operating system that uses auser�s password to derive user-specific or computer-specific encryption.

! Do not implement your own cryptographic routines.

Page 178: 2806 Microsoft Security Guidance Training for Developers

44 Session: Writing Secure Code � Threat Defense

Defending Against Unicode Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against Unicode issues. Specifically, we will discuss:

! Unicode issues.! Defending against Unicode issues.

Page 179: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 45

Unicode Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Common mistakes in using Unicode include:

• Treating a Unicode character as a single byte.

• Miscalculating target buffer sizes when converting between Unicode and ASCII (and viceversa).

• Misusing MultiByteToWideChar, potentially causing a buffer overrun.

• Validating data before and not after conversion. When validating a Unicode string, the stringmay pass your validation tests. However, when the string is converted to ASCII, somecharacters that are perfectly acceptable in Unicode may not be available under ASCII.

! All of the above can lead to buffer overruns or dangerous character sequences.

Page 180: 2806 Microsoft Security Guidance Training for Developers

46 Session: Writing Secure Code � Threat Defense

Defending Against Unicode Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

When coding in Unicode, consider the following:

! Always use sizeof (WCHAR) when allocating buffer space. Do not assume a Unicode character isa byte.

! Be aware that Chinese language standard GB18030, which states that 4 bytes are used percharacter.

! Convert Unicode strings to ASCII before validating. This will prevent dangerous characters fromremaining undetected.

! Use IsNLSDefinedString. This method checks whether each character in a string has a definedresult for a specified NLS (National Language Support) capability.

! Always ensure that your target buffers are large enough when calling MultiByteToWideChar.

Page 181: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 47

Demonstration 5: Unicode Issues

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will show some of the issues associated with the use of UNICODEstrings.

Investigating Unicode Issues1. SWITCH TO THE LONDON VPC.

2. Log on to the OrdinaryUser account with a password of Passw0rd

3. Click Start, point to All Programs, and then click Microsoft Visual Studio .NET 2003.

4. In Visual Studio .NET 2003, on the File menu, point to Open, and then click Project.

5. Navigate to the directoryC:\Courses\DeveloperSecurity\Democode\Session02\DemoUnicode.

6. Open the DemoUnicode.sln solution.

7. In Solution Explorer, double-click DemoUnicode.cpp.

8. Locate the function _tmain and the first call to malloc.

9. Scroll down to the second call to malloc.

10. Scroll down to the initialization of the four variables, pwszString, wszDest,pwszSensitiveData, and wszUpperCase.

11. Scroll down to the call to WideCharToMultiByte.

12. Press CTRL+F5 to run the application.

13. Click Yes if prompted to build the project configuration.

14. Press ENTER to terminate the application.

15. Close Visual Studio .NET 2003.

Page 182: 2806 Microsoft Security Guidance Training for Developers

48 Session: Writing Secure Code � Threat Defense

Defending Against Denial of Service

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on how to defend against denial of service issues. Specifically, we willdiscuss:

! Denial of service attacks.! Defending against denial of service attacks.

Page 183: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 49

Denial of Service Attacks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

A denial of service (DoS) attack exploits the need to have access to a specific service. The attacksdeny clients access to the required service through:

! CPU starvation. Applications may be forced to repeat intensive calculations or processes.! Memory starvation. Applications may be forced to consume excessive amounts of memory.! Resource starvation. Applications may be forced to consume excessive numbers of resources such

as threads or database connections.! Network starvation. Malicious applications may flood a network with superfluous data.

Page 184: 2806 Microsoft Security Guidance Training for Developers

50 Session: Writing Secure Code � Threat Defense

Defending Against Denial of Service Attacks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Consider security as a design feature. DoS attacks are easy for hackers to implement. Make sureto design mitigation techniques into your applications to prevent DoS attacks. You should alsocreate contingency plans in case your company is targeted by DoS attacks.

! Do not trust user input. Validate all data that can initiate a DoS attack before it is processed byexpensive resources, such as database connections.

! Fail intelligently. Do not consume expensive resources for lengthy periods of time in the event ofa failure.

! Test security. Create scripts or test applications to automate attacks. Look for memory leaks overtime.

Page 185: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 51

Session Summary

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 186: 2806 Microsoft Security Guidance Training for Developers

52 Session: Writing Secure Code � Threat Defense

Next Steps

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Next steps include going to the Microsoft Web site to:

! Get the latest security information.! Get additional security training.

Page 187: 2806 Microsoft Security Guidance Training for Developers

Session: Writing Secure Code � Threat Defense 53

For More Information

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 188: 2806 Microsoft Security Guidance Training for Developers

54 Session: Writing Secure Code � Threat Defense

Questions and Answers

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 189: 2806 Microsoft Security Guidance Training for Developers

Contents

What We Will Cover 1

Session Prerequisites 2

ET Framework Security Features 3

Code Access Security 12

Role-Based Security 24

Cryptography 33

Securing ASP.NET Web Applications 40

Securing ASP.NET Web Services 48

Session Summary 52

Clinic Evaluation 56

Session: Implementing Application SecurityUsing the Microsoft .NET Framework

Page 190: 2806 Microsoft Security Guidance Training for Developers

Information in this document, including URL and other Internet Web site references, is subject tochange 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 applicablecopyright laws is the responsibility of the user. Without limiting the rights under copyright, nopart of this document may be reproduced, stored in or introduced into a retrieval system, ortransmitted in any form or by any means (electronic, mechanical, photocopying, recording, orotherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectualproperty rights covering subject matter in this document. Except as expressly provided in anywritten license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

2004 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Windows Server, SQL Server, and Win32 areeither registered trademarks or trademarks of Microsoft Corporation in the United States and/orother countries.

The names of actual companies and products mentioned herein may be the trademarks of theirrespective owners.

Page 191: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 1

What We Will Cover

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will introduce application security by using the Microsoft® .NET Framework.Specifically, we will discuss:

! .NET Framework security features.! Code access security.! Role-based security.! Cryptography.! Securing Microsoft ASP.NET Web applications.! Securing ASP.NET Web services.

Page 192: 2806 Microsoft Security Guidance Training for Developers

2 Session: Implementing Application Security Using the Microsoft .NET Framework

Session Prerequisites

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 193: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 3

.NET Framework Security Features

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will introduce the .NET Framework security features. Specifically, we will discuss:

! .NET managed execution.! A type-safe system.! Buffer overrun protection.! Arithmetic error trapping.! Strong-named assemblies.! Isolated storage.

Page 194: 2806 Microsoft Security Guidance Training for Developers

4 Session: Implementing Application Security Using the Microsoft .NET Framework

.NET Managed Execution Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! The .NET common language runtime controls the execution of .NET code. The .NET Frameworksecurity system is part of the common language runtime.

! The .NET Framework includes many features that you will learn about in this presentation, suchas type checking for safe type-conversions, secure exception management, and code accesssecurity control.

! .NET Framework security is designed to complement the security provided by MicrosoftWindows®. It does not override Windows-based security. For example, if a Windows accesscontrol list (ACL) restricts access to a file, the .NET Framework does not override this security.

Page 195: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 5

A Type-Safe System

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Type-safety verification is the cornerstone of .NET Framework security because it prevents accessto unauthorized memory locations. This allows you to consistently enforce security policy. Forexample, code cannot overrun a buffer and cause execution to jump to an arbitrary memorylocation.

! Type-safety verification allows the common language runtime to run more than one type-safeassembly in the same process. These sub-processes are called application domains. Applicationdomains are especially useful in server scenarios in which the overhead of using many processesmay slow system performance.

! In the past, the use of dynamic-link library (DLL)-based components was preferred for efficiencyreasons, because EXE-based components were seen to be more secure and robust (due to theMicrosoft Win32® virtual address space architecture). However, .NET supports the concept of anApp Domain. An App Domain can be thought of as a process within a process, which providesgood performance (like a DLL-based component), excellent security, and robustness.

Page 196: 2806 Microsoft Security Guidance Training for Developers

6 Session: Implementing Application Security Using the Microsoft .NET Framework

Buffer Overrun Protection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Managed code typically does not deal with raw pointers (such as a char *). Instead, the .NETruntime uses classes such as System.String and System.Text.StringBuilder, which are managedby .NET type-verification checks.

! A String is an immutable object, which vastly alleviates the buffer overrun issue. Consider thefollowing code:void CopyString (string src){stringDest = src;}

! When the code executes, a new resultant string object will be created, and the reference stringDestwill be altered to refer to that string. Therefore, a buffer overrun is not possible.

! Another string class found in the .NET Framework is StringBuilder. StringBuilder is also arobust class and will throw an exception if an attempt is made to overwrite its internal buffer.

Page 197: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 7

Arithmetic Error Trapping

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Trapping arithmetic errors in unmanaged code (for example, Visual C++) is very difficult.However, with managed code, spotting arithmetic runtime errors is easier. For example, the VisualC# compiler enables automatic checking for arithmetic overflows and underflows.

! By default, the arithmetic error trapping feature is turned off (for optimization reasons). However,you can easily turn on this feature either from the project properties or by using the checkedkeyword in your code.

! If you have turned arithmetic checking on at the project level, you can override the settings byusing the unchecked keyword in your code. This is useful if you are certain that arithmetic errorscannot occur in specific blocks of code and you want to optimize those blocks when your code iscompiled.

Page 198: 2806 Microsoft Security Guidance Training for Developers

8 Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 1: Type Safety

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Investigating .NET Data-Type Safety1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, with a password of Passw0rd.

3. From the Start menu, select Microsoft Visual Studio .NET 2003.

4. After Visual Studio .NET 2003 has loaded, select File->Open->Project.

5. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\TypeSafety.

6. Open the TypeSafety.sln solution.

7. In Solution Explorer, right click on the String project.

8. Select Set as StartUp Project.

9. In Solution Explorer, expand the String project.

10. Double-click string.cs

11. Locate the comment //String immutability example.

12. Press CTRL + F5 to run the application.

13. Press ENTER to terminate the application.

14. In Solution Explorer, right click on the StringBuilder project.

15. Select Set as StartUp Project.

16. In Solution Explorer, expand the StringBuilder project.

17. Double-click StringBuilder.cs

Page 199: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 9

18. Press CTRL + F5 to run the application.

19. Press ENTER to terminate the application..

20. In Solution Explorer, right click on the Cast project.

21. Select Set as StartUp Project.

22. In Solution Explorer, expand the Cast project.

23. Double-click cast.cs.

24. Locate the comment //Type safe casting - example of downcasting

25. Press CTRL + F5 to run the application.

26. Press ENTER to continue.

27. Press ENTER to continue.

28. Press ENTER to terminate the application.

29. Close Visual Studio .NET.

Using the checked Keyword1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, with a password of Passw0rd.

3. From the Start menu, select Microsoft Visual Studio .NET 2003.

4. After Microsoft Visual Studio .NET 2003 has loaded, select File->Open->Project.

5. Browse to the directoryC:\Courses\DeveloperSecurity\Democode\Session04\ArithOverflow.

6. Open the ArithOverflow.sln solution.

7. Double-click ArithOverflow.cs.

8. Press F7 to switch to code view.

9. Scroll to the bottom of the file.

10. Locate the timer1_Tick method.

11. Press CTRL + F5 to run the application.

12. Allow count to exceed 255.

13. Click on the check box (labeled checked).

14. Wait for the exception.

15. Press the Quit button in the exception box.

16. Close Visual Studio .NET 2003.

Page 200: 2806 Microsoft Security Guidance Training for Developers

10 Session: Implementing Application Security Using the Microsoft .NET Framework

Strong-Named Assemblies

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Strong names are unique identifiers for your assemblies. You can generate strong names and thenuse them to digitally sign your assemblies. Strong-naming solves problems (such as versioncontrol and backward compatibility issues) that are caused when components are shared bymultiple applications. In effect, strong names associate a distinct build of a component assemblywith the client application. A distinct build is indicated by a combination of a version number anda special value that is called the publicKeyToken.

! You can generate a public/private key pair for signing your assembly by using the Strong Nametool (Sn.exe).

! When you have a private key, you can specify the key file and the version number to be assignedwhen you compile the assembly, using attributes as shown:[assembly: System.Reflection.AssemblyVersion("1.0.0.0")][assembly: System.Reflection.AssemblyKeyFile("orgKey.snk")]

! A strong-named assembly prevents attackers from tampering with the assembly�s code, and allowsconfirmation of the assembly publisher�s identity. Strong-named assemblies also allow side-by-side components to co-exist, which aids version control and backward compatibility.

Page 201: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 11

Isolated Storage

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! For some applications, such as downloaded Web applications and code that may come fromsources that are not trusted, the basic file system does not provide the necessary isolation andsafety. Isolated storage is a data storage mechanism that provides isolation and safety by definingstandardized ways of associating code with saved data.

! Administrators can use tools that are designed to manipulate isolated storage to configure filestorage space, set security policies, and to delete unused data.

! With isolated storage, developers no longer have to invent unique paths to specify safe locations inthe file system. Developers can now access safe locations by using either the application�s identityor the user�s identity. The code sample on the slide show an example of how to access the isolatedstorage based on a user�s identity.

Page 202: 2806 Microsoft Security Guidance Training for Developers

12 Session: Implementing Application Security Using the Microsoft .NET Framework

Code Access Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will introduce code access security. Specifically, we will discuss:

! Evidence-based security.! Security policies.! Security checks.! Using security checks.! Permission requests.! Partial trust applications.! Sandboxing privileged Code.

Page 203: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 13

Evidence-Based Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Win32 security works on the principal of user authentication and authorization. For example, if auser places a floppy disk into the computer, lists the directory, and chooses to execute the file�trustme.exe�, the operating system will oblige, and run the application in the security context ofthe logged on user. Therefore, the application (which may be malicious) will have all of the systemprivileges granted to the user in question.

! .NET provides you with the concept of evidence-based security. This security works on top ofWin32 security; it does not replace it.

! Irrespective of the logged on user, the .NET Framework collects evidence about an assembly andpresents it to the security system. After the evidence has been gathered, the runtime will decide onwhether or not the code will be allowed to complete all of the tasks that it requests.

! Some evidence is considered stronger by the runtime than other evidence. For example, strongnames and Authenticode signatures are considered stronger than URL or zone evidence, because itis more difficult for an attacker to fake values for these elements.

! Developers can create their own unique evidence. For example, they can create evidence thatindicates an assembly was developed internally and reviewed by the IT department for securityflaws.

Page 204: 2806 Microsoft Security Guidance Training for Developers

14 Session: Implementing Application Security Using the Microsoft .NET Framework

Security Policies

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! In contrast to many security systems, the .NET Framework security policy is based on assemblyidentity, rather than user identity.

! Security policies map assembly evidence to permissions that are granted for that assembly.Security policies use code groups and policy levels to achieve this mapping.

! The .NET Framework includes multiple levels of policy configuration, including enterprise,machine, and user settings. Developers use an intersection of different policy settings whendetermining permissions.

! Code groups and policy levels give administrators fine-grained control over security policy.Administrators can configure policies to grant a set of permissions for the assembly based on avariety of evidence.

! Administrators can use Active Directory to ease the deployment of security policies.

Page 205: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 15

Security Check Stack Walks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! When the code accessing a protected resource demands a permission, a stack walk is performed.! The security system checks the permission granted to each caller. If each caller is granted the

permission, the demand succeeds, otherwise a security exception is thrown. This approachprevents an assembly without permissions, using your assemblies to perform unauthorized actions.

Page 206: 2806 Microsoft Security Guidance Training for Developers

16 Session: Implementing Application Security Using the Microsoft .NET Framework

Types of Security Checks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Imperative security checks involve creating instances of Permission objects at run time andinvoking methods on them, such as the Demand method. For example, the developer may createan instance of the FileIOPermission object, and demand the Read permission for a specific file. Ifthe call to the Demand method succeeds, execution continues, otherwise, a security exception isthrown.

! With declarative security checks, permissions are specified by using attributes instead of creatingPermission objects at run time. At design time, developers specify permissions (such as theFileIOPermission Read access permission for a specific file) by including the attributes in classdefinitions or individual methods. Although the same types of permission can be managed as withthe imperative approach, the declarative process makes it easier to review the required permissionsfor a class or method. However, because the permissions apply only to classes or methods, thisapproach is slightly less flexible than imperative checking.

! While obtaining evidence for both imperative and declarative security checks, the runtime willwalk the stack, assuring that less privileged code further up the stack is not trying to execute codefor which it does not normally have permission. However, you can use the Assert method tochange the behavior of the stack walk. When the method in which you call Assert is reached, thestack walk stops. This means that permissions for the callers of your code are not checked. TheAssert method is most useful when your code needs access to a protected resource, but your codedoes not give access to that resource to its callers.

Page 207: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 17

Permission Requests

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Developers use permission requests to state the permission requirements of their assemblies.Permission requests are implemented as assembly attributes.

! Using permission requests makes it easier to run code with least privilege. If an assembly does notreceive its minimum permission request at load time, it does not load, rather than waiting until anunauthorized operation is attempted and then failing.

! In the slide example, an assembly requests the Unmanaged code permission. If that permission isdenied at load time, the assembly will not continue.

Page 208: 2806 Microsoft Security Guidance Training for Developers

18 Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 2: Code Access Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Using the .NET Framework Configuration Tool1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, with a password of Passw0rd.

3. From the Start menu, click Run.

4. Type runas /env /user:London\Administrator "MMC %windir%\Microsoft.NET\Framework\v1.1.4322\mscorcfg.msc"

5. Click OK.

6. Enter a password of P@ssw0rd when prompted.

7. In the left-hand pane, expand Runtime Security Policy.

8. In the left-hand pane, expand Machine.

9. Expand Code Groups.

10. Expand All_Code.

11. Select LimitedBehaviourCodeGroup.

12. Right-click on LimitedBehaviourCodeGroup.

13. Select Properties.

14. Click on the Membership Condition tab.

15. Click the Permission Set tab.

16. Click Cancel.

17. In the left-hand pane, expand Permission Sets.

Page 209: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 19

18. Right-click on LimitedBehaviourPermissions and click Change Permissions.

19. In the right-hand pane, double-click Security.

20. Click OK.

21. Click Cancel.

22. Do not close the .NET Framework 1.1 Configuration tool.

Performing Security Checks1. SWITCH TO THE LONDON VPC

2. From the Start menu, select Microsoft Visual Studio .NET 2003.

3. After Visual Studio .NET 2003 has loaded, select File->Open->Project.

4. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\ImperativeSecurity.

5. Open the ImperativeSecurity.sln solution.

6. In Solution Explorer, double-click ImperativeSecurity.cs.

7. In design view, double-click the Test ImperativeSecurity button.

8. Run the application (CTRL + F5).

9. Click the Test ImperativeSecurity button.

10. Dismiss the security error by clicking OK.

11. Close the Imperative Code Access Security application.

12. Switch to the Microsoft .NET Framework 1.1 Configuration tool.

13. Right-click on LimitedBehaviourPermissions.

14. Select Change Permissions.

15. In the left-hand pane, double-click File IO.

16. Select the Grant assemblies unrestricted access to the file system option.

17. Click OK.

18. Click Finish.

19. Do not close the Microsoft .NET Framework 1.1 Configuration tool.

20. Switch to Visual Studio.NET 2003

21. Run the application (Ctrl+F5).

22. Click on the Test ImperativeSecurity button.

23. Dismiss the resulting message box by pressing OK.

24. Close the Imperative Code Access Security application.

25. Return to Visual Studio .NET 2003 and select File->Open->Project.

Page 210: 2806 Microsoft Security Guidance Training for Developers

20 Session: Implementing Application Security Using the Microsoft .NET Framework

26. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\DeclaritiveSecurity.

27. Open the DeclarativeSecurity.sln solution.

28. In Solution Explorer, double-click DeclarativeSecurity.cs.

29. Press F7 to switch to code view.

30. Locate the line -[FileIOPermission(SecurityAction.Demand, Write= "C:\\temp.txt")] (Located at the top of thefile).

31. Run the application (Ctrl+F5).

32. Close the application.

33. Switch to the Microsoft .NET Framework 1.1 Configuration tool.

34. Right-click on LimitedBehaviourPermissions.

35. Select Change Permissions.

36. In the right-hand pane, double-click File IO.

37. Select the Grant assemblies access to the following files and directories option.

38. Click OK.

39. Click Finish.

40. Do not close the Microsoft .NET Framework 1.1 Configuration tool.

41. Return to Visual Studio .NET 2003.

42. Run the application (Ctrl+F5).

43. Dismiss the exception message box by pressing No.

Requesting Permissions1. SWITCH TO THE LONDON VPC

2. Switch to Visual Studio .NET and click File->Open->Project.

3. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\RequestUnmanagedCode

4. Open the RequestUnmanagedCode.sln solution.

5. In Solution Explorer, double-click RequestUnmanagedCode.cs.

6. Press F7 to enter code view.

7. Locate the line [assembly:SecurityPermission(SecurityAction.RequestMinimum,UnmanagedCode=true)] (Located at the top of the file).

8. Switch to the Microsoft .NET Framework 1.1 Configuration tool.

9. Right-click on LimitedBehaviourPermissions.

10. Select Change Permissions.

Page 211: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 21

11. In the right-hand pane, double click Security.

12. Clear the Allow calls to unmanaged assemblies check box.

13. Click OK.

14. Click Finish.

15. Run the application in Visual Studio .NET 2003 (CTRL + F5).

16. Dismiss the security error by clicking No.

17. Switch to the Microsoft .NET Framework 1.1 Configuration tool.

18. Right-click on LimitedBehaviourPermissions.

19. Select Change Permissions.

20. In the right-hand pane, double-click Security.

21. Select the Allow calls to unmanaged assemblies check box.

22. Click OK.

23. Click Finish.

24. Close the Microsoft .NET Framework 1.1 Configuration tool.

25. Return to Visual Studio .NET 2003.

26. Run the application (CTRL + F5).

27. Click on the Use Win32 API EnumWindows button.

28. Close all applications.

Page 212: 2806 Microsoft Security Guidance Training for Developers

22 Session: Implementing Application Security Using the Microsoft .NET Framework

Partial Trust Applications

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Prior to the .NET Framework 1.1, all ASP.NET Web applications ran with full trust, which meantthat code access security could not be applied to them.

! The .NET Framework 1.1 allows an administrator to define the trust levels for all Webapplications within the machine.config file, thereby gaining control on what code access isavailable. Five trust levels are available, as follows:

• Full. Unrestricted permissions enable applications to access any resource that is subject tooperating system security, and all privileged operations are supported.

• High. Cannot call unmanaged code, message queues, serviced components, or OLE DB datasources.

• Medium. Can only access its own directory structure, and cannot access the registry.

• Low. Cannot access Microsoft SQL Server�, and no assertion permission.

• Minimal. Execute permission only.! Each of these trust levels can be customized with its own .config file.

Page 213: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 23

Sandboxing Privileged Code

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Rather than allowing a whole application maximum privileges, it is possible to sandbox privilegedcode while retaining partial trust for the Web application as a whole.

! The .NET sandboxing approach is as follows:

• Encapsulate the resource access in a wrapper assembly.

• Demand and then assert the relevant permission prior to accessing the resource.

• Add the AllowPartiallyTrustedCallersAttribute to the assembly. This is necessary to allow itto be called from a partial-trust Web application.

• Install the wrapper assembly in the global assembly cache (GAC). This automatically assignsthe assembly full trust.

• Configure the Web application to use an appropriate trust level.

Page 214: 2806 Microsoft Security Guidance Training for Developers

24 Session: Implementing Application Security Using the Microsoft .NET Framework

Role-Based Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will introduce role-based security. Specifically, we will discuss:

! Authentication and authorization.! Identities and principals.! Creating Windows identities and principals.! Creating generic identities and principals.! Performing security checks.! Imperative and declarative security checks.

Page 215: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 25

Authentication and Authorization

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Authentication is the process of obtaining identification credentials, such as a name and apassword, from a user and then validating those credentials against some authority, such as adatabase. If the credentials are valid, the entity that submitted the credentials is considered anauthenticated identity. For example, all users must provide a user name and password every timethey log on to a network. These credentials are then validated against an authority, such as adatabase or a Windows-based domain server.

! After an identity has been authenticated, the authorization process determines whether that identityhas access to a specified resource. The authorization process limits access rights by granting ordenying specific permissions to an authenticated identity. For example, you can authorize one userto access the color printer, but deny access to another user. Similarly, you can authorize only theusers of a group to access the color printer and deny access to the rest of the users.

! Role-based security in the .NET Framework mostly involves authorization.

Page 216: 2806 Microsoft Security Guidance Training for Developers

26 Session: Implementing Application Security Using the Microsoft .NET Framework

Identities and Principals

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! An identity contains information about the user�s identity, such as their logon name and whetherthe user is authenticated.

! A principal contains information about the role membership for a user or computer.! The .NET Framework implements two major types of identities and principals.

• WindowsIdentity and WindowsPrincipal objects provide information about the Windowscredentials for a user.

• GenericIdentity and GenericPrincipal objects enable the developer to implement their ownauthentication technique.

! The following slides show how to create Windows and Generic principals and identities, and thendemonstrates how to use them to make role-based security checks.

Page 217: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 27

Creating Windows Identities and Principals

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! You can create Windows identities and principals for users based on their Windows credentials.You can use either of the approaches that are shown on the slide to achieve this, but the first codesample is more efficient, if the principal and identity are retrieved for a single check, whereas thesecond sample is more efficient if multiple checks will be made.

! After you have created Windows identities and principals, you can use them to perform securitychecks.

Page 218: 2806 Microsoft Security Guidance Training for Developers

28 Session: Implementing Application Security Using the Microsoft .NET Framework

Creating Generic Identities and Principals

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Creating GenericIdentity and GenericPrincipal objects is useful when you want to implementcustom authentication techniques, such as finding credentials in a database, rather than performauthentication based on a user�s Windows credentials.

! The slide shows sample code for creating Generic identities and principals.! After you have created generic identities and principals, you can use them to perform security

checks, as we will discuss next.

Page 219: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 29

Performing Security Checks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Now that you have seen how to create identities and principals, you can use them to performsecurity checks in your code. The slide demonstrates two examples.

! The first code example performs a case-insensitive string comparison of the current identity�sName property and a hard-coded string.

! The second code example uses the IsInRole method to check role membership. In this example,the code checks whether the principal is a member of the built in Administrators group.

Page 220: 2806 Microsoft Security Guidance Training for Developers

30 Session: Implementing Application Security Using the Microsoft .NET Framework

Imperative and Declarative Security Checks

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! You can also use imperative and declarative approaches for role-based security checks.! The first code sample on the slide uses an imperative security check to determine whether the

active principal object�s permissions match the permissions of the newly created prinPerm object.The call to the Demand method will throw a security exception if the permissions do not match.This approach is useful if you want to secure specific actions within your code.

! The second sample on the slide uses declarative security. The attribute shown can be applied to aclass or an individual method, so that a security check is performed when the class or method isused. Although the same types of check can be performed as with the imperative approach, thedeclarative process makes it easier to review the required permissions for a class or method.However, because the checks apply only to classes or methods, this approach is slightly lessflexible than imperative checking.

Page 221: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 31

Demonstration 3: Role-Based Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Using Windows Role Based Security1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, password Passw0rd.

3. From the Start menu, select Microsoft Visual Studio .NET 2003.

4. After Visual Studio .NET 2003 has loaded, select File->Open->Project.

5. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\WindowsRoleBasedSecurity

6. Open the WINDOWSROLEBASED.SLN solution.

7. Double-click MainForm.cs.

8. Press F7 to switch to code view.

9. Locate the GoButton_Click function.

10. Locate the comment // Get WindowsIdentity and WindowsPrincipal objects.

11. Locate the comment // Get WindowsIdentity information.

12. Locate the // Use WindowsPrincipal object comment.

13. Press CTRL + F5 to run the application.

14. Click Get Windows Role-Based Security Information

15. Click the Exit button but leave Visual Studio .NET 2003 open.

Page 222: 2806 Microsoft Security Guidance Training for Developers

32 Session: Implementing Application Security Using the Microsoft .NET Framework

Using Generic Role Based Security1. SWITCH TO THE LONDON VPC

2. Switch to Visual Studio .NET 2003 and click File->Open->Project.

3. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\GenericRoleBasedSecurity.

4. Open the RBSLAB.SLN solution.

5. Using Solution Explorer, double-click MainForm.cs and then press F7.

6. Show the breakpoints in the following methods:configureSecurityDecPermButton_ClickImpPermButton_ClickPrincipalButton_Click

7. Debug the application (F5).

8. Enter the user name Spencer and with a Password of password.

9. Click OK.

10. Press the F5 button to continue.

11. Click Perform Manager Check with Principal.

12. Press F5.

13. Click Perform Manager Check with Imperative Permission.

14. Press F5.

15. Click Perform Manager Check with Declarative Permission.

16. Press F5.

17. Click Exit

18. Close Visual Studio.NET 2003.

Page 223: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 33

Cryptography

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will introduce cryptography. Specifically, we will discuss:

! Cryptography review.! Symmetric encryption.! Asymmetric encryption.! Signing data.

Page 224: 2806 Microsoft Security Guidance Training for Developers

34 Session: Implementing Application Security Using the Microsoft .NET Framework

Cryptography Review

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Symmetric encryption enables you to encrypt and decrypt data by using a single secret key. If thesecret key is compromised, all of the data that you used the key to encrypt can be decrypted.

! Asymmetric encryption enables you to encrypt and decrypt data with a public/private key pair.You can distribute the public key freely, but the private key must be kept secret. Data encryptedwith the public key can be decrypted only with the private key and vice versa.

! Hashing is the process of mapping a longer string of data, such as a file, to a small string of datathat is a fixed size, such as a 160-bit hash value.

! Digital signing is the process of encrypting a hash value with a private key and distributing thissignature with the data. When a recipient receives the data, the recipient can decrypt the data withthe sender�s public key and compare it with the hash value of the data. If the values match, theintegrity of the data is guaranteed.

Page 225: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 35

Using Symmetric Algorithms

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The basic steps for using symmetric encryption algorithms are:

1. Choose the algorithm you want to use. The .NET Framework provides wrapper classes forworking with symmetric encryption, such as the TripleDESCryptoServiceProvider theRijndaelManaged classes.

2. Generate a secret key by using the .NET wrapper class that you have chosen. Symmetricalgorithms require this key to encrypt and decrypt data. The class constructor can create thesevalues or you can provide your own.

3. Use the same key to encrypt and decrypt data. You can encrypt data by using any class thatderives from the Stream class, including FileStream, MemoryStream, and NetworkStream.

Page 226: 2806 Microsoft Security Guidance Training for Developers

36 Session: Implementing Application Security Using the Microsoft .NET Framework

Using Asymmetric Algorithms

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The basic steps for using asymmetric encryption algorithms are:

1. Choose the algorithm that you want to use. The .NET Framework provides wrapper classes forworking with asymmetric encryption, such as the RSACryptoServiceProvider and theDSACryptoServiceProvider classes. These classes use the well-known algorithms after whichthey are named

2. Generate public and private keys by using the .NET wrapper class that you have chosen.Asymmetric algorithms use a public key and a private key to perform cryptographic operations.Some operations, such as signature creation and decryption, require a private key. Otheroperations, such as signature verification and encryption, require a public key.

3. Use the appropriate key when encrypting or decrypting data. For example, if you are encryptingdata, you would use the public key, whereas if you are decrypting data you would use theprivate key. You can encrypt and decrypt data by using any class that derives from the Streamclass, including FileStream, MemoryStream, and NetworkStream.

Page 227: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 37

Signing Data and Verifying Signatures

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Signing data prevents tampering and asserts the identity of the signer. In some situations, you willwant to sign data so that other's can be assured of your identity, whereas at other times, you willwant to verify a signature so that you are sure that the data originated from a specific source.

! Signing data and verifying signatures involves:

• Signing Data. Hash the data, and then use an asymmetric algorithm to create a signature.

• Verifying the signature. Decrypt the signature, hash the data, and then use an asymmetricalgorithm to verify the signature.

Page 228: 2806 Microsoft Security Guidance Training for Developers

38 Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 4: .NET Framework Encryption

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Performing Symmetric Encryption1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, password Passw0rd.

3. From the Start menu, select Microsoft Visual Studio .NET 2003.

4. After Visual Studio .NET 2003 has loaded, select File->Open->Project.

5. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Session04\SymmetricPasswordEncryption

6. Open the CRYPTOLAB.SLN solution.

7. Using Solution Explorer, open up the file MainForm.cs.

8. Press F7 to enter code view.

9. Locate the function encryptData.

10. Show the breakpoint at the entry to the method.

11. Press F5 to compile and run the application.

12. When the application appears, type Apples and Bananas in the Text Viewer form.

13. On the File menu, click Save and Encrypt.

14. Enter the file name Safe.bin and click Save.

15. Enter the password Alrx123:::: (and repeat for verification).

16. Click OK.

Page 229: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 39

17. Press F5 to continue.

18. Using Notepad, open the file C:\Courses\DeveloperSecurity\Democode\Session04\SymmetricPasswordEncryption\Bin\Debug\Safe.bin

19. Return to the application.

20. Click on File->Open and Decrypt.

21. Double-click Safe.bin.

22. Enter the password Alrx123:::: and click OK.

23. Close the application and notepad, but leave Visual Studio .NET 2003 running.

Signing Data1. If you are not already logged on, log onto London by using the OrdinaryUser account with a

password of Passw0rd.

2. Switch to Visual Studio .NET 2003 and click File->Open->Project.

3. Browse to the directory C C:\Courses\DeveloperSecurity\Democode\Session04\SigningData

4. Open the DATASIGNING.SLN solution.

5. Using Solution Explorer, open up the file MainForm.cs.

6. Press F7 to enter code view.

7. Locate the CreateSigButton_Click method.

8. Locate the VerifyOrigButton_Click method.

9. Press F5 to compile and run the application.

10. Click Create Signature.

11. Click Verify Signature Against Original Data.

12. Click Verify Signature Against Altered Data.

13. Click Exit.

14. Close Visual Studio .NET 2003.

Page 230: 2806 Microsoft Security Guidance Training for Developers

40 Session: Implementing Application Security Using the Microsoft .NET Framework

Securing ASP.NET Web Applications

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on securing ASP.NET Web applications. Specifically, we will discuss:

! ASP.NET authentication types.! Configuring forms-based authentication.! Forms-based authentication enhancements.! Validation controls.! Types of validation controls.

Page 231: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 41

ASP.NET Authentication Types

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! ASP.NET supports three types of authentication method:

• Windows-based authentication

• Forms-based authentication

• Microsoft Passport authentication! With Windows-based authentication, the ASP.NET Web application relies on the Windows

operating system to authenticate the user. ASP.NET uses Windows-based authentication inconjunction with Internet Information Services (IIS) authentication. With Windows-basedauthentication, the user requests a secure Web page from the Web application, and the request thenpasses through IIS. If the user�s credentials do not match those of an authorized user, IIS rejectsthe request. The user then has to enter his or her name and password in the logon form. Thecredentials are again verified by IIS. If these credentials are accepted, IIS directs the originalrequest back to the Web application. The secure Web page is then returned to the user.

! Forms-based authentication involves non-authenticated requests being redirected to a HypertextMarkup Language (HTML) form. The user provides their credentials and submits the form. If theapplication validates the credentials on the form, the system issues an authentication cookie to theuser. Subsequent requests from the user are issued with the authentication cookie in the requestheaders, and then the user is authenticated on that basis. You will see how to set up forms-basedauthentication in the next slide. You will then see the .NET enhancements that are associated withforms-based authentication.

! Passport authentication is a centralized authentication service, provided by Microsoft, which offersa single logon option and core profile services for member sites. Users who sign up to use Passportare authenticated by Web sites with a single Passport account. Microsoft Passport is an XML Webservice, and is an integral part of the .NET Framework.

Page 232: 2806 Microsoft Security Guidance Training for Developers

42 Session: Implementing Application Security Using the Microsoft .NET Framework

Configuring Forms-Based Authentication

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Configuring forms authentication for your .NET Web application involves the following fourtasks:

• Configure IIS to use Anonymous authentication so that the user is authenticated by ASP.NETand not by IIS.

• Set the authentication method to 'Forms' for the application in an <authentication> subsectionof the <system.web> section in Web.config, If you set the authentication mode to 'Forms', youmust add a <forms> element to the <authentication> section, as shown in the slide example. Inthe <forms> section, configure the settings of the cookie. Set the name attribute to the suffix tobe used for the cookies and the loginUrl attribute to the Uniform Resource Locator (URL) ofthe page to which unauthenticated requests are redirected.

• Set up the <authorization> section in Web.config to deny or allow users access to your Webapplication. You can also mark the entire Web application as needing authorization or specifyauthorization on a page-by-page basis.

• Build a logon Web Form. This can be a simple page with two fields for a user name and apassword. The page requires the users to enter their user name and password to access to yourWeb application.

! Although you can perform these tasks in any order, ensure they are all completed before deployingyour solution, otherwise forms-based authentication will not work.

Page 233: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 43

Forms-Based Authentication Enhancements

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! By default, there is no requirement for the authentication cookie submitted by the client with eachrequest to be encrypted. Encryption is normally performed by implementing SSL across the site;however, this is controlled by the site administrators, rather than developers. Developers canensure that the cookie is encrypted by adding the attribute requireSSL=�true� to the <forms>element in the web.config file. This will set the HttpCookie.Secure property, such that compliantbrowsers will only return the cookie over SSL.

! One consideration with secure cookies is the use of validation and decryption keys. These can beautomatically generated for the application. However, it is possible for the same key to begenerated for several Web applications on the same computer. To avoid this, developers can usethe IsolateApps parameter within the machineKey element in the web.config file.

Page 234: 2806 Microsoft Security Guidance Training for Developers

44 Session: Implementing Application Security Using the Microsoft .NET Framework

Validation Controls

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Input validation can take place on both the server and the client. Client-side validation is an optionwith some browsers.

! The validation controls in ASP.NET have both client-side and server-side support. Client-sidevalidation uses JavaScript and dynamic HTML (DHTML) scripts. Server-side validation can bewritten in any .NET-based language.

! Client-side validation enhances the usability of the Web Form by checking user input as the userenters data. By checking for errors when data is being entered, client-side validation allows errorsto be detected on the client before the Web Form is submitted.

! Writing multiple versions of validation code to support both the server and several differentbrowsers can be extremely time-consuming for developers. ASP.NET validation controls eliminatethis problem because the validation logic is encapsulated within the controls. The controls createbrowser-specific code so that users with client-side script support will have client-side inputvalidation. Browsers that do not support scripts will not receive client-side validation scripts.

! In browser versions that support input validation, such as Microsoft Internet Explorer 4 or later,client-side validation occurs when the user clicks the Submit button. The page will not be postedback to the server until all client-side validation is true. In Internet Explorer 5 or later, using theTAB key to move from one input control to the next runs the client-side validation for thecompleted input control.

! All input validation controls also run on the server side. Client-side validations are repeated on theserver side when the page is posted back to the server. This repetition avoids attackers bypassingthe client-side script and trying to use provide input.

Page 235: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 45

Types of Validation Controls

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The ASP.NET page framework includes a number of validation controls:

! The CompareValidator control compares an input control to another input control, a fixed value,a data type, or a file.

! The CustomValidator control allows you to write your own code to create the validationexpression. For example, this control can be used to verify that the input value is a prime number.

! The RangeValidator control is similar to the CompareValidator control, but this control canverify that the user input is between two values or the values of other input controls.

! The RegularExpression control verifies that the entry matches a pattern that has been defined bya regular expression. For example, social security numbers, e-mail addresses, telephone numbers,and postal codes.

! The RequiredFieldValidator control checks whether a value has been entered into a control.This is the only validation control that requires a value.

! The ValidationSummary control displays a summary of all of the validation errors for all of thevalidation controls on the page. This control is typically placed near the Submit button to provideimmediate feedback on the page input status.

Page 236: 2806 Microsoft Security Guidance Training for Developers

46 Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 5: ASP.NET Web Application Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Configuring Forms Authentication1. SWITCH TO THE LONDON VPC

2. Log onto the OrdinaryUser account, password Passw0rd.

3. From the Start menu, select Microsoft Visual Studio .NET 2003.

4. After Visual Studio .NET 2003 has loaded, select File->Open->Project.

5. Browse to the directory C:\Courses\DeveloperSecurity\Democode\Websites\FBE

6. Open the FBE.sln solution.

7. Using Solution Explorer, open up the file Web.config

8. Locate <authentication mode="Forms" />

9. Locate the authorization section in Web.config.

10. Double-click the login.aspx file and press F7.

11. Locate the LoginButton_Click method.

17.Right-click Main.aspx and click Set as Start Page.

18.Press CTRL + F5.

19.Microsoft Internet Explorer will be launched. If you are prompted about enhanced securityconfiguration, select the In the future, do not show this message checkbox and click OK.

20.Type Ben Smith in the Name text box, and password in the Password text box.

21.Click Login.

22.Close Internet Explorer.

Page 237: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 47

Using Validation Controls1. SWITCH TO THE LONDON VPC

2. Switch to Visual Studio .NET 2003, and click File->New->Project.

3. Select Visual C# Projects.

4. Select ASP.NET Web Application.

5. In the location textbox, type http://localhost/Validation

6. Click OK.

7. From the Toolbox (on the left-hand side of the screen), add a TextBox control.

8. Add a RegularExpressionValidator control and place it next to the TextBox.

9. Add a Button to the form.

10. In the properties window, set the ControlToValidate property for theRegularExpressionValidator to TextBox1.

11. In the properties window, set the ErrorMessage property for the RegularExpressionValidatorto Invalid input.

12. In the properties window, set the RegularExpressionValidator�s ValidationExpression toInternet E-mail Address.

13. Press CTRL + F5 to run the application.

14. When the application appears, enter microsoft.com into the textbox.

15. Click the button.

16. Enter [email protected] into the textbox.

17. Press the button.

18. Close Internet Explorer and Visual Studio .NET 2003.

Page 238: 2806 Microsoft Security Guidance Training for Developers

48 Session: Implementing Application Security Using the Microsoft .NET Framework

Securing ASP.NET Web Services

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this topic, we will focus on securing ASP.NET Web services. Specifically, we will discuss:

! Message-level security.! Web Service Enhancements.

Page 239: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 49

Message-Level Security

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Message-level security applies to the contents of a Simple Object Access Protocol (SOAP)message. This is extremely useful for XML Web Services, because developers and administratorscannot usually secure both end-points in this type of communication, so the actual message itselfneeds securing.

! The World Wide Web Consortium (W3C) have defined a set of specifications called WS-Security,which describe enhancements to SOAP messaging. These specifications define message integrity,message confidentiality, and single message authentication for SOAP messaging.

! With message-level security, authentication is provided by security tokens, which flow in SOAPheaders. The security tokens may include Kerberos tickets, X.509 certificates, or a custom binarytoken.

! Secure communication is provided by digital signatures to ensure message integrity and by XMLencryption for message confidentiality.

! WS-Security can be used to construct a framework for exchanging secure messages in aheterogeneous Web services environment. It is ideally suited to heterogeneous environments andscenarios where you are not in direct control of the configuration of both endpoints andintermediate application nodes.

! Message-level security:

• Can be independent from the underlying transport.

• Enables a heterogeneous security architecture.

• Provides end-to-end security and accommodates message routing through intermediateapplication nodes.

• Supports multiple encryption technologies.

• Supports non-repudiation.

Page 240: 2806 Microsoft Security Guidance Training for Developers

50 Session: Implementing Application Security Using the Microsoft .NET Framework

Web Service Enhancements (WSE)

*****************************ILLEGAL FOR NON-TRAINER USE******************************

! Web Services Enhancements for Microsoft .NET (WSE) is a set of tools that can be used toimplement security within a SOAP message, rather than relying on security features of otherprotocols (such as SSL). Microsoft developed WSE to conform with the WS-Security standards.

! The main security-oriented features of WSE are:

• Authentication through SOAP headers. This is based either on Username tokens, which aredefined in the WS-Security standard, or binary tokens, such as an X.509 Certificate token. Onthe server-side, you can implement your own mechanism for storing user names andpasswords.

• Message encryption. This is implemented through input and output filters, which allowsdevelopers to use both the SOAPWebRequest and SOAPWebResponse, thereby applyingwhichever encryption mechanism they require to the messages.

• Message signing. This is a signature element generated from an X509 security token. Thesignature is added to the security header within the SOAP header.

• It is possible to control which parts of the header, body, and message the signature applies to.This is useful if the message is routed, because the routing process may modify parts of theheader which would otherwise invalidate the signature.

• Attachments can also be secured with WSE.

• As a developer, you can access the WSE functionality by using classes exposed inMicrosoft.Web.Services.dll.

Page 241: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 51

Demonstration 6: Web Services Enhancements

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Implementing Security for a Web Service1. SWITCH TO THE LONDON VPC

2. Using Internet Explorer, open the file UsernameToken.xml, which you can find in the folderC:\Courses\DeveloperSecurity\Democode\Session04\WSE.

3. Highlight the wsse:UsernameToken element.

4. Open the file X509Sign.xml, which you can find in the folderC:\Courses\DeveloperSecurity\Democode\Session04\WSE.

5. Within wsse:Security element, highlight the wsse:BinarySecurityToken.

6. Close all applications.

Page 242: 2806 Microsoft Security Guidance Training for Developers

52 Session: Implementing Application Security Using the Microsoft .NET Framework

Session Summary

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 243: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 53

Next Steps

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Next steps include going to the Microsoft Web site to:

! Get the latest security information.! Get additional security training.

Page 244: 2806 Microsoft Security Guidance Training for Developers

54 Session: Implementing Application Security Using the Microsoft .NET Framework

For More Information

*****************************ILLEGAL FOR NON-TRAINER USE******************************

More technical information for IT professional and developers is available on the following Websites:

! Microsoft Security Site (all audiences)

• http://www.microsoft.com/security! MSDN Security Site (developers)

• http://msdn.microsoft.com/security! TechNet Security Site (IT professionals)

• http://www.microsoft.com/technet/security

Page 245: 2806 Microsoft Security Guidance Training for Developers

Session: Implementing Application Security Using the Microsoft .NET Framework 55

Questions and Answers

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Page 246: 2806 Microsoft Security Guidance Training for Developers

56 Session: Implementing Application Security Using the Microsoft .NET Framework

Clinic Evaluation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Your evaluation of this clinic will help Microsoft understand the quality of yourlearning experience.

To complete a clinic evaluation, go to http://www.CourseSurvey.com.

Microsoft will keep your evaluation strictly confidential and will use yourresponses to improve your future learning experience.