You are on page 1of 246

Microsoft Security Guidance Training for Developers

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 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 either registered 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 their respective owners.

Clinic: 2806A Part Number: X10-42504 Released: 02/2004

Contents

Introduction
Prerequisites ............................................................................................................2 Clinic Outline ..........................................................................................................3 Microsoft Learning ..................................................................................................4 Microsoft Learning Product Types..........................................................................5 Microsoft Certified Professional Program...............................................................6 Additional Reading from Microsoft Press...............................................................9 Facilities ................................................................................................................10

Session: Essentials of Application Security


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: Writing Secure Code Best Practices


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 Applications Security...............................................29 Session Summary ..................................................................................................51 Clinic Evaluation ...................................................................................................55

Session: Writing Secure Code Threat Defense


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 Cryptography Weaknesses .....................................................41 Defending Against Unicode Issues........................................................................44 Defending Against Denial of Service ....................................................................48 Session Summary ..................................................................................................51

Session: Implementing Application Security Using the Microsoft .NET Framework


What We Will Cover ...............................................................................................1 Session Prerequisites ...............................................................................................2 .NET 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: Essentials of Application Security

Contents
What We Will Cover Session Prerequisites The Importance of Application Security Secure Application Development Practices Security Technologies Secure Development Guidelines Session Summary 1 2 3 13 23 61 65

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2004 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Windows Server, Active Directory, MSDN, and SQL Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Session: Essentials of Application Security

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.

Session: Essentials of Application Security

Session Prerequisites

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

Session: Essentials of Application Security

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.

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 new standard 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 2003 during this time. Trustworthy Computing is a serious initiative within Microsoft to improve the security and reliability 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, and malicious actions originate from within an organization, either by disgruntled or misguided employees.

Session: Essentials of Application Security

Connection Scenarios and Security Concerns

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


!

Workforce mobility is increasing, and consequently, the way in which employees connect to your companys network is evolving. Employees connect in a number of different ways, including traditional wired connections, new and evolving wireless network standards, and dial-up and broadband virtual private network (VPN) connections. The variety of ways your mobile users connect to your companys network introduces a number of security concerns, including: Wireless susceptibility. Although wireless networks can be as secure as wired networks if administered properly, by default, many wireless networks provide the opportunity for any compatible device to connect in an ad-hoc manner. Employee home security. Many employees have wireless networks at home, and may not be aware of the issues that are involved with securing this type of network. Furthermore, alwayson broadband connections make home networks (whether wireless or not) more susceptible to viruses and attackers. The potential susceptibility of home networks may result in viruses or attackers gaining access to your corporate network, either when the user connects over a VPN or when they physically plug their computers into the network on your companys premises. Although virus checkers and firewalls can help secure home networks and broadband connections, it is often difficult for your network administrators to enforce the use of these defences.

Employees increasingly use their laptop computers and other mobile devices to connect to wireless networks run by third parties. For example, they might connect to WiFi hotspots in coffee houses, airports, hotels, and other places to check their e-mail or to browse the Internet. Because your company has no control over the security of these public networks, they provide a potential route for attackers or viruses. As with home networks, this may result in viruses or attackers gaining access to your corporate network, either when the user connects over a VPN or when they physically plug their computers into the network on your companys premises.

6
!

Session: Essentials of Application Security

Applications are becoming increasingly dependant on connections to the Internet, for updated data, Web services, and so on. The Internet is a potential route to your systems for attackers and viruses. 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 potential route to your systems for attackers and viruses. Security attacks will also still happen from within your enterprise. This could be as simple as an employee who writes down a password which then falls into the wrong hands, or it could be deliberate actions from a disgruntled employee. It is important to remember that security is not just required for public facing connections.

Session: Essentials of Application Security

Common Types of Attacks

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


!

Organizational attacks involve one organization breaking into your network to try to access confidential information, thereby gaining a business advantage. Attackers like to exercise their skill in attempting to bypass security safeguards to gain illegal access to your network. Automated attacks use software to scan for network vulnerabilities, or to implement a brute force attack. Brute force attacks involve trying many different usernames and passwords or other credentials to gain access to your resources. Denial of Service attacks overwhelm a server with requests for action, thereby rendering it incapable of providing its normal service. Viruses, Trojan horse, and worms are harmful programs that act by exploiting some known vulnerability to install themselves on a computer (perhaps by entering as an attachment to an email). Once present on a computer, they distributes copies of themselves to other connected computers, and these copies also replicate themselves, resulting in a viral-like infection of the computer network. Accidental breaches in security often result from poor practices or procedures. For example, the exposure of security information, such as usernames and passwords, can be exploited by an attacker to gain access to your network.

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, it creates 100 threads first. Out of those initial 100 threads, it uses 99 threads to spread the worm while the 100th thread checks to see if it is running on a English (U.S.) Microsoft Windows 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 systems website. Exploits an unchecked buffer overrun in Microsoft Index Server 2.0, a component of Internet Information 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 Visual Basic 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.

Session: Essentials of Application Security


!

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 their body as a resource. These files then spread the infection when users exchange programs such as games. Scans the Internet for vulnerable servers and defaces Web pages on those servers, leading to further propagation of the worm through users browsing the infected sites. Infects network shares, causing any user who opens a Word document on those shares to become infected. Reads e-mail addresses from your e-mail client and also searches local HTML files looking for additional addresses. It then sends one e-mail to each address containing the README.EXE attachment.

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 put them to advantage in their own products. An attack may result in your systems being taken offline while the damage is assessed and rectified. All effort expended combating security attacks and repairing the damage is lost productivity. This time 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 is that if your systems security is bad, then many of your other practices will also be bad. It is easy to come 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 defaced website, will visit your competitors websites instead. The financial losses from security intrusions can be substantial. It is difficult to determine the exact cost of issuing a security fix, but the Microsoft Security Response Center believes a security bug that requires a security bulletin costs approximately $100,000.

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 the attacker has over the defenders, and how the degree of security affect users, as well as conveying the 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. Secure developers should strive to make the system as secure as possible, but not to make it impossible to use. Complex and strong passwords are those that must contain a mixture of uppercase and lowercase letters, and possibly punctuation characters. They must also be long perhaps 9 or more characters in length. However, there is often user resistance to strong passwords, because they are more difficult to remember. 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. There is also a perception that the cost of implementing security is high and the business benefits are unclear. 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 last issue addressed, fixing of any security vulnerabilities that are discovered may break other product functionality, and in common with any other late changes in the product development cycle, it is much more expensive than if security is designed in the first place.

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 and take collective responsibility for security. Developers must adopt good practices that ensure the production of secure software. They must be knowledgeable about security vulnerabilities and how to avoid them, and must have both a broad and deep knowledge about security technologies and how to use them in order to create secure solutions.

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, we will 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.

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 for network, host, and application layers. Even if you have the most secure network infrastructure possible, with completely hardened servers, a simple vulnerability in your application (for example, failing to validate input) renders all 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 in the Writing Secure Code Best Practices presentation. In short, you need to "bake security into your application development lifecycle". For step-by-step guidance on how to achieve this, refer to the Patterns and Practices documentation at http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMFastTrack.asp

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-off activities they continue throughout the development lifecycle.

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 called SD3. The SD3 framework has three core concepts: Secure by Design, Secure by Default, and Secure in Deployment. These concepts have shaped the development process to help deliver secure systems. Secure by Design means that you have taken the appropriate steps to ensure that the overall design of the product is secure from the outset. Include threat modeling at the design phase and throughout the project to identify potential vulnerabilities. Use secure design, coding, and testing guidelines. Secure by Default means that the product is released so that it is secure out of the box. If features are optional, and you can turn them off by default. If a feature is not activated, then an attacker cannot use it to compromise your product. Ensure that only the least amount of privilege is required by user accounts to run your application. Then a compromise can have less serious consequences than if an attacker is able to run malicious code under an account with administrator 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 is difficult to administer, it makes it more difficult to maintain protection against security threats as new ones evolve. Ensure that users are educated to use the system in a secure manner. If a security vulnerability is discovered and a patch is necessary, ensure that the fix is fully tested internally and then issued in a timely manner.

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 know what 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) or similar. 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.

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 secure programming 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 that knowledge, you cannot be an effective team member when taking part in threat modelling, or in doing security code reviews. However, understanding security technologies on their own does not mean that your application is secure. It is important not only to know how the technologies work, but how to use them to solve security problems. It is essential that programmers know what flawed code looks like so that they can pick up vulnerabilities in code reviews. Developers need to be fully aware of common security mistakes and know how to avoid or rectify them. 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.

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, developers implicitly trust users to type in the right thing and do not add software checks to ensure that they have done so. Buffer Overruns are one of the most common type of input vulnerability. It occurs when a buffer has been reserved to store an input value, but the input value supplied exceeds the length of the buffer. When the input value is copied into the buffer, it overwrites the memory around it. This can be exploited by attackers to change the execution path of the running program, which can be used to 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 a database. For example, a program may ask for input of a name to look up in a database, and build a 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 --, then deletion 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, which an attacker can then use to spoof the user (pretend to be them) to then access personal data that is held on websites that normally only that user could access. It can also be used to execute arbitrary code on the victims computer. Developers must validate all user-input to avoid these types of security vulnerabilities.

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 bypass application security. You will show the code for a class that is used to set and get personal details. You will point out the security features written into the code for the class. You will then exploit a buffer overrun to show how an attacker could bypass the security and retrieve details that they are not authorized to read.

Bypassing Security Checks


1. 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 the Font 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.

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.

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 have unexpected benefits, such as increased awareness of the internals of your application (not just security internals) for all members of the team. It also serves as a good way of getting new members of the team up to speed. Ongoing education is a crucial component of a secure development infrastructure. Developers must know how to recognize security defects and how to mitigate them. Developers must have a good working knowledge of security technologies and their correct application. Code reviews are also a crucial component of good security practice. Use your knowledge of common 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 that databases are accessed by using correct authentication (do not access the database server by using the 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: your experience and intellect. Continuing threat modeling, code reviews, and security reviews help to focus developers attention, and keep them focused on security issues. Secure communications solutions such as SSL/TLS or IPSec, and cryptographic libraries such as CAPICOM or the Microsoft .NET Crypto libraries are tried and tested. A solution built with these will, on the whole, be robust and reliable. Consider migrating to managed code if you have a large base of unmanaged C/C++ code. Many of the common security vulnerabilities such as buffer overruns are prevented by the common language runtime execution engine, and .NET offers additional benefits, such as additional security technologies like code access security. Use existing, proven solutions when implementing secure code. It is usually a mistake to do lowlevel cryptographic programming, since such solutions are always complex and often flawed.

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.

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. A broad understanding of these technologies is important for you as a developer, so that you have the grounding you need to take part in threat modeling, develop secure software, and to perform effective code reviews.

Session: Essentials of Application Security

25

Encryption

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


!

Encryption protects data from being viewed or modified, and provides secure channels of communication over otherwise insecure channels. For example, data can be encrypted by using a cryptographic algorithm, transmitted in an encrypted state, and later decrypted by the intended party. If a third party intercepts the encrypted data, it is difficult to decipher the data. Encryption is used for: 1. Confidentiality: Protect a users 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.

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 the data. 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 from reading the data. With this type of encryption, a key pair is used to encrypt and decrypt data. A key pair consists of two parts: a public key and a private key. These two keys are mathematically related. Although asymmetric encryption consumes more resources than symmetric encryption, it is 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).

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 at some 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 long string of bits with a fixed-length string of bits. For example, matching a 50-kilobyte file with a 160-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 data that 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 verify the validity of the data by applying the same hash algorithm to the data and then comparing the resulting hash value to the hash value that is sent with the data. If the hash values match, User B can 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).

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 that is unique to that party. This process also uses hash functions. Put simply, digital signatures combine hashing (for the validation of the signature data) with asymmetric encryption for encoding 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 As private key, thereby creating the digital signature. 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 As public key and then recovers the hash value. If the signature can be decrypted, User B knows that the data came from User A (or the 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 has not been modified.

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 private key, it does not guarantee that party's identity. For example, an attacker might have obtained a private key that belongs to Microsoft. They could then use that key along with a standard hashing algorithm to sign some data, implying that the source of the data is Microsoft. A digital certificate prevents this electronic identity theft by verifying that the signature does indeed belong to the publisher. The data and signature can now be verified as belonging to the authorized publisher because 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 network connection. 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 the CA.

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

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 protect privacy 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 of cryptographic security services that are negotiated between the client and server. IPSec is built 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-level secure communication solution and can be used to secure the data that is sent between two computers, 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 that require a trust relationship, because each request or response is validated by the authority of the certificate. When you use SSL, either the server or the client has a digital certificate that they have obtained from a third party. This certificate is passed to your application with requests.

Session: Essentials of Application Security

31

3. TLS (Transport Layer Security). TLS is the only security option available when servers need to prove their identity to anonymous clients. This is important for websites that want to participate in e-commerce, because it allows the secure transmission of sensitive information, such as credit card numbers. TLS requires that all servers prove their identity to clients. Additionally, TLS provides the option of having clients prove their identity to servers. This mutual authentication can be used to restrict who has access to certain Web pages in a large corporate intranet. TLS is the best choice for environments where you want the highest level 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 causes every packet of data sent between client and server to be encrypted. The RPC runtime stubs and 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 details related to the network.
!

IPSec and TLS are explained in the next two slides.

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 security model, which means that the sender and the recipient are the only hosts that must know about the IPSec protection. Each computer handles its own security, under the assumption that the medium over which the communication takes place is not secure. IPSec uses symmetric algorithms to encrypt data and transmits symmetric keys by using asymmetric algorithms. When a computer configured with an IPSec policy attempts to communicate with another computer, 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 key algorithms that are used to encrypt packets at the network layer.

Session: Essentials of Application Security

33

Secure Communication How SSL Works

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


!

SSL encryption relies on the servers public key and private key. The private key exists only on the Web server and it is used by the Web server to encrypt and decrypt secure messages. The public key exists on any client computer that has installed a certificate for that Web server. After the public key is installed, the user can send encrypted messages to, and decrypt messages received from, the Web server. When SSL is used, the following occurs: 1. The user browses to the secure Web servers site. 2. The browser creates a unique session key and encrypts it by using the Web servers public key, which is generated from the root certificate. Each session key that the Web servers certificate generates is unique. Therefore, even if an attacker has the same certificate installed on their browser, the attacker cannot decrypt the message. The browser where the encrypted message originated cannot decrypt the message. Only the Web server with the appropriate private key can decrypt the message. 3. The Web server receives the message and decrypts it by using its private key. This phase of SSL communication is often called the SSL handshake. An attacker may intercept a message protected with SSL. However, the attacker cannot decrypt the message, because the attacker does not have the Web servers private key. 4. After the connection is established, all communication between the browser and the Web server is secure.

When the session ends, the session key is destroyed.

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 using their Web site. Consequently, this demonstration requires that the host PC has a live Internet connection 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 this e-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 the e-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 you can do this at any time in the 14 days prior to the delivery of the demonstration. If you re-run the demo at a future date ensure that the trial certificate is still valid, otherwise step through this process again to receive a new trial certificate.

Session: Essentials of Application Security

35

Viewing a Web Site on a Non-Secure Server


1. 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 not show 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 warning checkbox and click OK. 6. Close Internet Explorer.

Generating a Certificate Request


1. 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. Type Contoso <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

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 Certificate


1. 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 Sites window, 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 a window 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.

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 as you 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 to retrieve the certificate that Verisign will send you. Copy the entire contents of the email to a text file and save it to the host machine in a text file called Verisign Trial Server ID.txt. Before commencing the demo for real, copy the text file to the root of the C:\ drive in the London virtual 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 Certificate


1. SWITCH TO THE LONDON VPC 2. In Notepad, open the file "c:\Verisign Trial server ID.txt" which contains the text of the email you received from Verisign. 3. Select the certificate text near the end of the e-mail (including the Begin and End lines). Press CTRL+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 error when 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.

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 Certificate


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

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 a password, and then validating those credentials against some authority, such as a database. If the identification credentials are valid, the user that submitted the credentials is considered to be an authenticated user. If you provide a secure communications channel, but then do not check who is using it, you could simply be creating an effective, hidden channel for an attacker to use to attack you, with the encrypted communications channel effectively concealing what the attacker is doing.

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 sent across the network, and not the password itself. 3. Digital signatures and digital certificates: Allow servers and clients to authenticate each other. 4. Integrated Authentication: Uses a cryptographic exchange to confirm the identity of the user as an authenticated Windows principal. a. Kerberos authentication: Supports mutual authentication and enables credentials to be delegated across processes. Also provides improved reconnection time; If a user is authenticated by a server and then disconnects but reconnects in the default time of eight hours, the user does not need to be re-authenticated. b. NTLM: Used for computers that are not participating in a domain, such as stand-alone servers and workgroups, or for pre-Windows 2000 computers. 5. Microsoft Passport: Passport authentication is a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. This benefits the user, because they no longer have to log on separately to access new protected resources 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, and Kerberos v5 are covered in more detail in the following slides.

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 protocol defined 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 is possible to write custom Basic Authentication handlers that validate credentials against data in a database or some other custom store. Used on its own, it is extremely insecure, since the username and password are transferred from the client to the server using base-64 encoding, which is trivial to decode. Consequently, this technique is only of value when combined with a secure communications channel, typically SSL/TLS. Resources: http://msdn.microsoft.com/library/en-us/vsent7/html/vxconIISAuthentication.asp

! ! !

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 instead of transmitting the user's credentials unencrypted from the browser to the Web server, it transmits a hash of the credentials. As a result, it is more secure, although it requires an Microsoft Internet Explorer 5.0 or later client and specific server configuration. When a client makes a request for content that is authenticated by using Digest authentication, the following 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 the password with data known to both the server and the client in order to create a string that is the correct number of characters required by the digest algorithm (also called a hash algorithm). The client then applies a digest algorithm (specified by the server) to the combined 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 the client's password it obtains from Active Directory, where the password is stored by using reversible encryption. 6. If the digest created by the server matches the digest created by the client, IIS authenticates the client.

Digest authentication requires that the IIS 5.0 server also be a Windows 2000 domain controller. It also requires that you use Internet Explorer 5.0 as your browser. Digest authentication encrypts client-supplied passwords in compatible browsers, but it does not encrypt the content and data in the same way as Secure Sockets Layer (SSL).

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. Using this information, the attacker can then use that information to replay the transaction. See the Microsoft MSDN Knowledge Base article KB222208 Setting Up Digest Authentication for Use with Internet Information Services 5.0.

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 server presents its X.509 server certificate to the client. The client validates the certificate to check its authenticity as part of the handshake setting up the connection. By default, client certificates are not used, meaning that the server has no way of authenticating the client, but X.509 client certificates 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 cardsized 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 to your systems over the Internet.

! !

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 remote access 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

! !

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 Distribution Center (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 or later. Initial logon authentication: When a user first logs on to the network, the user provides credentials to prove their identity. As shown on the slide, the following occurs during Kerberos version 5 initial 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 and authentication information about the user. 3. The client decrypts the TGT by using the users private key and then caches the decrypted TGT locally in the clients protected storage. The TGT contains a service key for subsequent transactions with the KDC.

Service Request: A Kerberos version 5 service request is used when a user attempts to connect to application or print servers on the network. As shown on the slide, the following occurs during a service 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 users credentials by decrypting the TGT and securely transmitting the ST to the users computer, where the ST is cached locally in the clients protected storage. 3. The user presents the ST to the target server, which grants the user access based on the users assigned permissions and requested access permissions. 4. A session is established between the client computer and the target server.

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-on user.

Using Anonymous Authentication


1. SWITCH TO THE LONDON VPC. 2. If not already logged on, log onto London by using the OrdinaryUser account with a password of Passw0rd. 3. Open Internet Information Services Manager. Do this by clicking Start Run and entering: 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 not show this message checkbox, and then click OK. 13. Type http://london/SecDev/iisauth in the Address bar, and press ENTER.

48

Session: Essentials of Application Security

14. The page is displayed. 15. Start Notepad. 16. Click File Open and open c:\courses\DeveloperSecurity\Democode\Websites\iisauth\web.config. (Note: If file extensions 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 Authentication


1. 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 then click 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 as LONDON\ORDINARYUSER 13. In Notepad, find the line <Identity impersonate="true"/>. Change "true" to "false" and save the 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 and the account shown as NT AUTHORITY\NETWORK SERVICE.

Session: Essentials of Application Security

49

Using Integrated Windows Authentication


1. 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 window appears, enter an invalid username and password, and then click OK. Repeat this two more times. 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 and the account shown as NT AUTHORITY\NETWORK SERVICE. 10. In Notepad, find the line <Identity impersonate="false"/>. Change "false" to "true" and save the 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 as LONDON\ORDINARYUSER. 15. Close all applications

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 one or more resources. After an identity is authenticated, the authorization process determines whether that identity has access to a specified resource. The authorization process limits access rights by granting or denying specific permissions to an already authenticated identity. Authorization and authentication go together because any meaningful authorization policy requires authenticated users. The administrator assigns rights to files, folders, registry settings, applications, databases, and files. 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.

! ! !

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 a website, 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 user identities (or principals in .NET parlance) to one or more roles that you define. In code, you perform permission checks when a protected resource is accessed, so that only principals that belong to specific roles gain access. .NET code access security is a layer of security that supplements Windows user-based security mechanisms. It is a way of restricting software not only based on the identity of the user, but also on the source of the software component. Therefore, a component that is downloaded from the Internet, that is signed with a digital certificate that identifies the publisher, is granted a specific set of privileges. That set of privileges differs from those given to unsigned applications, or to software that is installed directly onto the system. Security policy on the computer dictates whether software with a particular set of privileges is allowed to run, and if it is, what resources it is allowed to access. NTFS access control lists (ACL) are used to grant access rights to Windows user and group accounts. They are often used to secure files, directories and registry entries. Microsoft SQL Server logins provide the authorization for the SQL Server, but the database permissions provides the authorization for the database objects such as tables, views, and stored procedures. The recommended model is to map a SQL Server login to a database User, put the database user into a database role, and to then grant permissions to the role.

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 middle tiers of a multi-tier application) impersonates the clients identity (using operating system-level impersonation) before it accesses the next downstream service. If the next service in line is on the same computer, impersonation is sufficient. Delegation is required if the downstream service is located on a remote computer. As a result of the delegation, the security context used for the downstream resource access is that of 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 callers 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 logins must be maintained for each individual user.

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 is then mapped to a role. The database trusts the middle tier to authorize callers and allows only authorized callers to access the database by using the trusted identity. Downstream resource access uses a fixed service account used to service requests from all users in that 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 privileged domain account if the downstream box is in the same or trusting domain and an intervening firewall 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 fewer service accounts than clients. 3. Indirect data access. Users cannot access data directly, but must instead go through the application 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 user identity at the application level, and implement per-user auditing manually in the application. 2. Increased risk of server compromise. Since the database tier trusts the front-end tiers to authenticate users correctly, any weakness in that authentication leaves the server more exposed than if authentication was on a direct, per-user basis.

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

54

Session: Essentials of Application Security

Demonstration 4: Trusted Subsystem Model Authorization Techniques

*****************************ILLEGAL FOR NON-TRAINER USE****************************** This demo will show how to configure authorization between an application server and a database server by using the Trusted Subsystem model.

Reviewing the Application


1. SWITCH TO THE LONDON VPC. 2. If you are not already logged on, log onto London by using the OrdinaryUser account, with a password of Passw0rd. 3. Start Notepad. 4. Click File Open and open c:\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 trusted SQL Server connection.

Session: Essentials of Application Security

55

Setting Authentication on the Web Server


1. 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 a trusted SQL Server connection.

Creating Service Accounts on the Web Server


1. 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: OrderReaders b. Password: Passw0rd c. Confirm password: Passw0rd d. User must change password at next logon: Unchecked e. 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 open c:\courses\DeveloperSecurity\Democode\Websites\TrustedSubsystem\web.config 9. Find the line <Identity impersonate="false"/>. 10. Change to: <identity impersonate="true" userName="OrderReaders" password="Passw0rd"/>

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.NET Files\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 trusted SQL Server connection.

Setting Authorization on the Database Server


1. 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: OrderReaders b. Password: Passw0rd c. Confirm password: Passw0rd d. User must change password at next logon: Unchecked e. Check User cannot change password and Password never expires 6. Click Create, and then click Close.

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.

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 policy between two networks. Although the firewall can perform many functions, the primary two functions are to block network traffic and to permit approved traffic. A firewall can secure various layers of communication; including packet filtering, circuit-level filtering, and application filtering. At the packet level, a firewall prevents malformed and oversized packets resulting in denial of service attacks from entering the internal network. At the circuit-level, a firewall inspects packets from various sessions, using specific ports and communicating 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. Good application filters allow you to analyze a data stream for a particular application and provide application-specific processing, including inspecting, screening or blocking, redirecting, or modifying 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.

! !

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 security activity. It is recommended that you routinely audit your server configuration to detect areas where resources may be susceptible to unauthorized access and tampering. Auditing is an important ingredient of a secure application. Audit records can notify operations staff that unauthorized access is being attempted. They can help you to diagnose security breaches after they have occurred and give important information that will allow you to rectify the security vulnerability.

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. Service packs may contain updates for system reliability, program compatibility, security, and more. All of these 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 the enterprise. On occasions, applications may knowingly or unknowingly make use of a feature, or unintended behavior of some infrastructure software. Should a service pack alter the way the feature works, your application may not operate in the way you intended.

! !

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.

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 the development process. Adopt a holistic approach to security. There is no quick-fix for security. A sprinkling of security features spread throughout an application 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 every step of the software development life cycle to better focus on security. Security threats continually evolve, so it is important that your commitment to security is continuous and vigilant. Education is the key ingredient of this, both to learn from security vulnerabilities that are discovered in your system, but also to be informed about new security vulnerabilities that are discovered elsewhere in the computer industry. There are two aspects to security training. The first is to teach people about security issues so they can apply that knowledge to their current project and find and fix security bugs. However, the most important goal is to teach people not to introduce security flaws in the first place.

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 secure development practices. Ensure your systems are secure by design, meaning that you have carried out threat modelling to identify security vulnerabilities, you conduct code reviews focusing on security issues and that you ensure that security testing is an integral part of the testing process. Write software that runs with just enough privilege to carry out its purpose, but no more. Implement systems that are secure by default. Reduce the potential for attack by ensuring that optional features are turned off by default. Secure in Deployment. Ensure that your systems are easy to administer and update, so that security vulnerabilities may be addressed. Educate users on how to use the application securely. Provide a continuing program of security assessments and testing.

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 longer shipped with Windows XP SP1a or Windows Server 2003. Support for MSJVM will be discontinued from the end of September 2004, and no bug fixes will be 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

Session: Essentials of Application Security

65

Session Summary

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

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.

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 Web sites:
!

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

68

Session: Essentials of Application Security

Questions and Answers

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

Session: Writing Secure Code Best Practices


Contents
What We Will Cover Session Prerequisites Secure Development Process Threat Modeling Risk Mitigation Security Best Practices Demonstration 1: ASP.NET Applications Security Session Summary Clinic Evaluation 1 2 3 8 22 27 29 51 55

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2004 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Windows Server, Active Directory, and ASP.NET are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Session: Writing Secure Code Best Practices

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 coding stages 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.

Session: Writing Secure Code Best Practices

Session Prerequisites

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

Session: Writing Secure Code Best Practices

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.

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 successful delivery of trustworthy software products requires process improvements throughout the application development process. Often, security is considered as an afterthought, with security review of the product left until late in the development process. Although implementing security measures at this late stage does yield some benefits, it cannot substitute for considering security as an integral part of the process right from the beginning of the design phase, through development, to deployment. In short, you must build security into your application development lifecycle. For step-by-step guidance on how to achieve this, see Fast Track How to Implement the Guidance at http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMFastTrack.asp

Session: Writing Secure Code Best Practices

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 an integral part of the entire development process. The Secure Windows Initiative team at Microsoft has adopted a simple set of strategies called SD3. The SD3 framework has three core concepts: secure by design, secure by default, and secure in deployment. These concepts have shaped the development process to help deliver secure systems. Secure by design means that you have taken appropriate steps to ensure that the overall design of the product is secure from the outset. Include threat modeling at the design phase and throughout the project to identify potential vulnerabilities. Use secure design, coding and testing guidelines. Secure by default means that the product is shipped and that it is secure out of the box. If features are optional, turn them off by default. If a feature is not activated, then an attacker cannot use it to compromise your product. Ensure that only the least amount of privilege is required by user accounts to run your application. That way, a compromise has less serious consequences than if an attacker is able to run malicious code under an account with administrator 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 is hard 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 vulnerability is discovered and a patch is necessary, ensure that the fix is fully tested internally and issued in a timely fashion.

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 development timeline. 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 as well. At the commencement of a project, during interviews with potential team members, ask security questions to assess the level of security knowledge. This will help you to select security conscious developers, 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 identifying security 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 how to 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 of attacking the software, looking for security defects. After the product is shipped, there must be an appropriate plan of response for any security defects that are uncovered. At the least, this should involve education of developers so that the same or similar security issues can be uncovered. It may also involve the timely issuing of patches to existing installations.

Session: Writing Secure Code Best Practices

Secure By Design

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


!

Education is the key ingredient of an effective secure development process. You must ensure that all designers and programmers are informed about common security flaws in software so they can avoid repeating past mistakes. Perform regular training to raise security awareness and ensure that security remains a primary concern of all team members. Problems discovered late in the development cycle are much more expensive to fix than those discovered early on. This is particularly true for security issues. Be sure to consider the security of your application right at the beginning of the design phase. The security goals of the product should be considered with equal (or greater) importance to the other functional goals. If security is designed as a product feature, rather than considered as a value-add feature to be added on if there is time, the resulting product will be much more secure than if it is added as an afterthought. Threat modeling during the design phase as well as the development phase has proven to be extremely effective in determining the highest level security risks that are posed to the product and how attacks can occur.

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.

Session: Writing Secure Code Best Practices

What Is Threat Modeling?

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


!

Threat modeling is an analysis approach that helps designers to define the security aspect of the design specifications. The overriding driver of threat modeling is that you cannot build secure systems unless you understand your threats. The process aims to evaluate the threats to the application with the goal of reducing the consequences of an attack. Threat modeling is simple although it does require significant time investment and some practice to get it right. However, time spent during this phase is time well invested. Bugs found during this phase 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 than applying security features in a haphazard manner. Without threat modeling, you may not know precisely what threats each feature is supposed to address. It leads naturally to a solid security design 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 to affect your system. An asset is also referred to in threat parlance as an attack target. It is anything that is worth protecting. 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.

! !

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 application in a structured manner inevitably end up with a deeper understanding of how the application works. Find bugs: The additional scrutiny of the threat modeling process leads to the discovery of other, non-security related bugs. Identify complex design bugs: The analytical nature of the process can reveal complex multistep security bugs where several small failures combine to cause a major failure. This kind of vulnerability may be missed by unit testing performed by the developer and the majority of test plans. Integrate new members: Threat modeling is a useful tool for new team members to become familiar with the architecture of the product.

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

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 architecture of your application, including subsystems, trust boundaries, and data flow. 3. Decompose the application. Decompose the architecture of your application, including the underlying network and host infrastructure design, to create a security profile for the application. 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 the architecture and potential vulnerabilities of your application, identify the threats that could affect the application. 5. Document the threats. Document each threat using a common threat template that defines a core set 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 threat against damage that could result should an attack occur. It might turn out that certain threats do not warrant any action when you compare the risk posed by the threat with the resulting mitigation costs.

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.

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, its architecture and physical deployment configuration, and the technologies that form part of your solution. There are three main parts to the application overview: Identify what the application does. Document use cases to help you and others understand how your 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 your application and its subsystems as well as its physical deployment characteristics. Depending on the complexity of the application, this may need to split into several diagrams that focus on specific areas Identify the technologies. This helps you focus on technology-specific threats later in the process. It also helps you determine the correct and most appropriate mitigation techniques.

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 each subsystem, consider whether the upstream data flows, user input or calling code is trusted, and if not, consider how the data flows and input can be authenticated and authorized. Also consider server trust relationships. Analyze the data flow between different subsystems, paying particular attention to data flows crossing trust boundaries. Carefully consider all entry points to your application such as Web pages or socket servers as these are potential routes for attack. Also consider entry points on internal subsystems or components. Although these entry points may only exist to allow internal communication between components in your application, they could also serve as points of attack, if the attacker manages to bypass the normal front door security controls. Consider code that accesses secure resources such as DNS servers, directory services, environment variables, 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 the security system (for example .NET code access security) demands special vigilance. Create a security profile for the application by documenting the design and implementation approaches for input validation, authentication, authorization, configuration management, and the remaining areas where applications are most susceptible to vulnerabilities. Data flow diagrams (DFDs) are a useful tool for decomposing an application into its key components. They provide the basis of a good technique for illustrating the flow of data between processes. An alternative is UML activity diagrams, which are similar in purpose, although focus more on the transfer of control between processes. The guiding principle for DFDs is that an application or a system can be decomposed into subsystems, and subsystems can be decomposed into still lower-level subsystems. Ignore the inner workings of the application, but focus on the scope of the application, not functional details. Decompose the application down only two, three or four levels deep just deep enough to understand the threats to the application. Do not fail in the threat modeling process by analyzing too deeply and losing sight of the original objective.

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 best way to do this is to assemble a team consisting of members of the development and test teams to conduct 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. Ensure your 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 of the threat modeling process. Focus on application threats, technology-specific threats, and code threats. Look for things such as poor input validation, passing authentication credentials over unencrypted network connections, or using weak password or account policies.

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 the threats, you can identify and develop security policies that apply to a range of threats in a category and not just to individual threats. The STRIDE categories are: Spoofing: Illegally accessing and then using another users authentication information, such as user name and password. For example, a hacker can bypass authorization by using SQL injection and assuming the sa role. Tampering with Data: Maliciously modifying data. An example would be making unauthorized changes to persistent data such as data in a database or alternating data as it flows between two computers over an open network, such as the Internet. Repudiation: Threats associated with users denying (repudiating) an action when other parties do not have any way of proving otherwise. Information disclosure: Exposing information to unauthorized individuals. An example would be reading data in transit between two companies. Another example is using cross-site scripting to steal somebodys cookies. Denial of service: Denying service to valid users. An example would be making a Web server temporary unavailable or unusable. Another example is exploiting a buffer overrun that causes a server to restart. Elevation of privilege: An unprivileged user gaining privileged access and thereby having sufficient access to compromise or destroy the entire system. An example would be exploiting a buffer overrun to gain a command shell and adding the hacker to the Administrators group.

Session: Writing Secure Code Best Practices

17

Threat Modeling Process Identify the Threats by Using Attack Trees

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


!

Building threat trees is an effective method for determining computer system security issues. The idea behind threat trees is that an application is composed of threat targets and that each target could have vulnerabilities that when successfully attacked could compromise the system. The threat tree describes the decision-making process an attacker would go through to compromise the software component. The decomposition process has helped you to identify all the system components. You then identify potential threats to each component. Threat trees then help you decide how that threat could manifest itself. The way to write a threat tree is to identify goals and sub-goals of an attack, as well as what must be done so that the attack succeeds. The threat tree on this slide shows the ways in which an attacker could view another users confidential payroll data. Although threat trees communicate data well, they can become cumbersome when building large threat models. An alternative way of representing the threat tree is using an outline, as illustrated on the slide.

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.

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 a risk in the range of 1 100. You can divide the scale into three bands to generate a High, Medium and Low risk rating. This way of assessing risk is too simplistic for some, so at Microsoft, the DREAD model is used to refine this calculation to add a dimension that assesses what the impact of a security threat really 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 relative to one another. You just need to be consistent.

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 the priority value. Within each DREAD category, use a score of 3 for high risk, 2 for medium risk, and 1 for low risk. Assess each threat in your threat tree and assign the risk rating for each of the DREAD categories and 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 medium risk, and 5 7 as low risk.

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. It allows you to identify the most vulnerable parts of your application so you can focus your efforts on 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 process to revisit and retest security decisions made in the design phase and to direct focus in security code reviews. The results of the threat modeling process provide the information necessary to select appropriate security 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 for identifying all inputs to your application. Any inputs are a particular source of security vulnerabilities.

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 has uncovered. Specifically, we will discuss:
! ! !

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

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 threats from 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 is rarely a good choice as the fault will lie latent in the application and it is likely that it will be discovered and you will be forced to fix it. This is bad for your users and bad for your business reputation. Option 2: Warn the user. Inform the user of the problem and allow them to decide whether to use the feature. However, you cannot expect users to have sufficient detailed knowledge of the system 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 consider pulling the feature from the product before shipping. It is better to fix it for the next release than allow it to go out and compromise your users computers. Option 4: Fix it. Select the technologies required to fix the problem.

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-step process. 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, the technologies that can mitigate this include authentication or protecting secret data such as security credentials. If authentication is selected as the appropriate mitigating technique, the technologies you can use for authentication include NTLM, X.509 certificates, PGP (Pretty Good Privacy) Keys, Digest authentication, Kerberos, and SSL/TLS.

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 the slide. 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.

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.

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 can mitigate a wide range of attacks and should be used when developing any application on any platform. Some attacks can be mitigated by specific methods. In this topic, we will discuss a common set of techniques that developers can apply to mitigate security threats. Specifically, we will 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.

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, if you have a buffer overrun that runs under the security context of an administrator, a hacker can overwrite 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 elevated privileges. 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 it makes development easier. Although the developer may intend to lower the required privileges later on, time pressures frequently mean that this does not happen. This results in applications going live with elevated privileges, because system admin staff discover that If we do not run as administrator, the application does not work!

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 a nonprivileged account by default. You will show how the secure developer grants access to an ASP.NET application to access the file system, write to a custom event log, and access the registry.

Investigating ASP.NET Application Privileges


Perform 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.

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 Levels


1. 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 the security error. 8. Close Internet Explorer.

Sandboxing Privileged Code


1. 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 EventLogger project.

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 function and 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.

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 permission EventLogPermission 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 Build EventLogger. 25. Install the assembly in the GAC by switching to the command window, and then typing cd bin\debug 26. Type gacutil -i eventlogger.dll and press ENTER.

Session: Writing Secure Code Best Practices

33

Using Sandboxed Assemblies


1. 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:.
<compilation defaultLanguage="c#" debug="true"> <assemblies> <add assembly="eventlogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ea...d6"/> </assemblies> </compilation>

3. Replace ead6 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 button and 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 in EventLogger, 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.

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, to compromise 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.

! !

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 close to 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), or file traversal characters (..\).

Use the mantra: Constrain, Reject, and Sanitize. One of the most powerful ways to constrain data input is through validation controls and regular expressions. The example regular expression ( \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* ) checks that the input string is of the correct form for an Internet e-mail address.

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 Form application. ASP.NET developers have the benefit of having a large number of controls to help with input validation. In Windows Forms, the developer must write more code to achieve the same result. However, it is still easy to implement.

Viewing a Non-Validating Application


Perform the steps on the LONDON VPC. 1. If you are not already logged on, log on to London by using the OrdinaryUser account with a password 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) to show that no validation is being performed. 4. No errors occur. Close the application

Session: Writing Secure Code Best Practices

37

Adding Input Validation


1. 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 it in 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-hand dropdown box. 6. Inside the nameTextBox_Validating method, type the following:
If (nameTextBox.Text = "") Then ErrorProvider1.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 righthand 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") Else ErrorProvider1.SetError(eventDateTimePicker, "") End If

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

Validating the Complete Form


1. 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 a name and a date during the week. 4. Close all applications.

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 building multiple layers of defense, you can increase the security of a system. Software architects should design systems with multiple defense barriers. For example, if you are exposing sensitive data in a server running SQL Server on a Web page, you can place a firewall in front of the Web server to prevent unauthorized access to it. In addition, you can require clients to connect by using Secure Sockets Layer (SSL). You can strengthen the security perimeter by placing an additional firewall in front of the server running SQL Server and requiring all the computers on the internal network to use Internet Protocol security (IPSec). Threat modeling defines the location and importance of defensive strategies.

Session: Writing Secure Code Best Practices

39

Defense in Depth (2 of 3) Apply Appropriate Measures for Each Layer

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


!

In addition to implementing multiple layers of security in systems, you can also add layers of security in applications. For example, you can have an application .exe file authenticate and authorize users. Then, each supporting application .dll file can also authenticate and authorize users. If only the application .exe file authenticates and authorizes users, then a hacker might circumvent it 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 the envisioning phase.

! !

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 the application 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 during installation. 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 Deny Access. Other dangerous access control entries (ACEs) include WRITE, WRITE_DAC, WRITE_OWNER, and DELETE.

! !

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 security mechanism. You should always assume that an attacker knows everything you do, and has access to all source code and diagrams.

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 Microsoft Windows Server 2003 and Microsoft Windows XP. DPAPI is a powerful encryption class built into the operating system that uses a users password to derive user-specific or computer-specific encryptions. The Data Protection API can be used to protect security-sensitive data, such as database connection strings and service account credentials. It is password-based, and can store data in either a user or machine store. There are two ways to use it: the user store approach, where you protect data such that only the data owner can access it, or the machine store approach, where any user on the machine can access it. You select the latter case by setting the CRYPTPROTECT_LOCAL_MACINE flag in the dwFlags field when calling the API. The user store approach affords an additional layer of security because it limits who can access the secret. Only the user who encrypts the data can decrypt the data. However, use of the user profile requires 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 automatically load a user profile. The machine store approach is easier to develop because it does not require user profile management. However, unless an additional entropy parameter is used, it is less secure because any user on the computer can decrypt data. (Entropy is a random value designed to make deciphering the secret more difficult.) The problem with using an additional entropy parameter is that 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 ACL when you store it in persistent storage.

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 connection string. 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 Techniques using the Trusted Subsystem Model in the session Essentials of Application Security. If you have not 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 the User must change password at next logon checkbox is not selected. Ensure that the Password never 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 system folder security, click Yes. Create a local account on Denver called OrderReaders with password Passw0rd. Ensure that the User must change password at next logon checkbox is not selected. Ensure that the Password never 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.

44

Session: Writing Secure Code Best Practices

Storing Connection Strings in Web.config


Perform the steps on the LONDON VPC. 1. If you are not already logged on, log on to London by using the OrdinaryUser account with a password 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 message checkbox 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 connection string 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 the connection string definition to the configuration file.

Encrypting Connection Strings with DPAPI


1. 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 the calls to the data protection API. 4. In Solution Explorer, right-click the EncryptString project, point to Debug, and click Start new 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 click Paste. 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.

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 encrypted version. 14. Save Web.config. 15. In default.aspx.cs, expand the WebDesigner Generated Code region if it isnt 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 Utility


1. View Web.Config again. Find the <Identity > element. 2. Notice that this application uses impersonation, and the username and password are in the file in clear 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.

46

Session: Writing Secure Code Best Practices

Using Encrypted Attributes in a Configuration File


1. 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 of P@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 or Machine.config file so that ASP.NET will use these keys to read that information from the registry. 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,userN ame" password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,passw ord" />

Granting Permissions on Registry Keys


1. 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 Check Names. 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 Replace permission entries on all child objects with entries shown here that apply to child objects checkbox. 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.

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, always follow 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 everything else.

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 error messages 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.

! !

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 provide valuable feedback. Most testing is designed to prove product features work correctly. Security testing should be designed to make features fail. Examples of testing security include attempting to spoof user identities, submitting bad input, or creating DoS attacks. To defend against hackers, you must ensure that your test team has the same level of knowledge and access to the same technologies as hackers. Decomposing an application involves logically separating components, interfaces, and data to identify important assets and likely vulnerabilities. Use threat modeling to define security testing strategies. Attack every conceivable and inconceivable vulnerability. Explicitly test security, not just features. 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.

! !

! ! !

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 from experience. Archibald McLeish (1892 1982), American poet. Approach every bug as a learning opportunity. If you fail to learn from a mistake, it is highly probable that you will make the same mistake in the future.

Session: Writing Secure Code Best Practices

51

Session Summary

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

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.

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 Web sites: 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

54

Session: Writing Secure Code Best Practices

Questions and Answers

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

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 your learning experience. At a convenient time before the end of the clinic, please complete a clinic evaluation, which is available at http://www.CourseSurvey.com. Microsoft will keep your evaluation strictly confidential and will use your responses to improve your future learning experience.

Session: Writing Secure Code Threat Defense


Contents
What We Will Cover Session Prerequisites The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-Site Scripting Defending Against SQL Injection Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service Session Summary 1 2 3 8 15 21 29

Defending Against Canonicalization Issues 35 41 44 48 51

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 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 United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Session: Writing Secure Code Threat Defense

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.

Session: Writing Secure Code Threat Defense

Session Prerequisites

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

Session: Writing Secure Code Threat Defense

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.

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 the ever-increasing complexity of software and systems, the need for secure code has never been so urgent. 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 news headline.

Session: Writing Secure Code Threat Defense

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 area network (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 greater range of potential target points. When designing, developing, and testing software, a developer should consider the different mechanisms that are and will be used to access data. Each access point should be considered, tested, and proven to be secure.

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 plays host to a wide range of potential attackers, ranging from hobby hackers to professional data thieves. When your software system goes live, you should not be surprised if it falls under attack.

Session: Writing Secure Code Threat Defense

Common Types of Attack

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


!

Organizational attacks involve one organization breaking into your network to try to access confidential information in order to gain a business advantage. Hackers enjoy exercising their skills by attempting to bypass security safeguards and gain illegal access to your network. Automated attacks use software to scan for network vulnerabilities or to implement an electronic brute force attack. Brute force attacks involve trying many different user names, passwords, or other credentials to gain access to your resources. Denial of service (DoS) attacks flood a server with requests for action, thus rendering it incapable of providing its normal service. Viruses, Trojan horses, and worms are harmful programs that act by exploiting some known vulnerability to install themselves on a computer (perhaps by entering as an attachment to an email). Once they are present on a computer, they distribute copies of themselves to other connected computers, and these copies also replicate themselves, resulting in a rapid infection of the computer network. Accidental breaches in security often result from poor practices or procedures. For example, if security information, such as user names and passwords, is exposed, an attacker can exploit that information to gain access to your network.

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.

Session: Writing Secure Code Threat Defense

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 and the memory buffer is overwritten with the extra data. Buffer overruns are one of the most common and, potentially, one of the most damaging security risks. Buffer overruns primarily exist in C/C++ code because of the low level of memory management that 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 overrun exploits 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 Internet Information Services (IIS).

Buffer overruns are sometime called buffer overflows. These terms are synonymous.

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 of the calling code is placed on the stack. As a result, when the procedure finishes executing, control returns to the original location. Following the return address, parameters and local variables are pushed on the stack. At the end of the procedure, the stack unwinds and memory space is reclaimed. 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 the buffer. Hackers can overwrite nearly anything on the stack. The hacker can also control the values that are placed on the stack, for example, the return address. If the hacker overwrites the return address with the address of a malicious procedure, that procedure executes with the same privileges 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 the program. At worst, the hacker overwrites the return address, and malicious code may be executed with the same privileges as your process. This can result in severe damage if your process runs with administrator or elevated privileges. Therefore, you must always apply the general risk mitigation strategy of running processes with the least possible privileges.

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, it defines 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 stack works from top to bottom (high memory address to low memory address), the strcpy function could overwrite the return address in the stack. This is very dangerous, because if the return address is overwritten with the address of a malicious procedure, that procedure executes with the same privileges as the original program.

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 in those buffers. If the heap is used to store pointers to functions or classes, then a hacker can exploit the unchecked input buffer in a way similar to a stack-based overrun. However, the hacker must do much more investigative work to make the exploit than with a buffer overrun. For example, they must determine whether a function pointer is adjacent to the input buffer.

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 that uses 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 of strcpy because it only copies the string up to the zero terminator or up to the size specified, it can also result in access violations. For example, you want to make sure that the string in the buffer is zero-terminated; however, the zero can be added past the end of the buffer. While this cannot lead to code injection attacks, hackers can use potential programming flaws like this to achieve access violations and, as a result, software disruption. Be alert to the risks posed by CopyMemory and MultiByteToWideChar. Both these functions rely on you passing in buffer sizes and destination addresses and getting them right! If you get them wrong, your program crashes, at best. At worst, a clever hacker can corrupt your functions 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 overruns by placing a random value into the stack between the local data and the return address. When the function returns, the random value is verified. This does not prevent all buffer overruns and does not replace careful programming. This compile option is for unmanaged code and does not affect managed code. Strsafe.h provides a set of safer string-handling functions for the C programming language. You can download it as part of the Microsoft Windows Core SDK.

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 pathprocessing 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 write does not have direct access to pointers, computer registers, or memory. However, any unmanaged code that you call, either through PInvoke or COM components, may still suffer from buffer overruns.

! !

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.

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 and 65535, 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, if two numbers are multiplied and produce a value less than that, and the result is stored in a double variable, an underflow occurs.

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.

! !

18

Session: Writing Secure Code Threat Defense

Demonstration 1: Memory Issues and Data Type Errors

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

Investigating Buffer Overruns


1. 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 font size. 4. On the File menu, click Open, and then open the file C:\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 press ENTER. 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 stack overrun. Click OK. 10. Close the command window and Notepad.

Session: Writing Secure Code Threat Defense

19

Using the /GS Compiler Switch


1. 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\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 then press 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 stack overrun but that the application will not be allowed to continue. Click OK. 10. Close the command window and Notepad.

Using STRSAFE.H
1. 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\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 press ENTER. 7. Type SafeStrings and then press ENTER. 8. Explain the output in the command window. 9. Press ENTER.

20

Session: Writing Secure Code Threat Defense

Performing Safe Arithmetic Calculations


1. 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\DemoSafeIntegerAddition and 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.

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 will discuss:
! ! ! !

What cross-site scripting is. Two common exploits of cross-site scripting. Form-based attacks. Defending against cross-site scripting attacks.

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 these applications embed user input in the pages they generate, hackers can include content in those pages 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 believes the script came. The malicious script can perform a variety of actions, such as monitoring the users Web session and forwarding data to the hacker. The script can also modify what is displayed on the users screen, giving them incorrect information. The script can make itself persistent so that the malicious 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 is currently on the market. There is no single patch to fix it.

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 a client reads the message or posting with a browser, the malicious HTML tags are interpreted and executed on the client browser. Use HTML <form> tags to redirect private information. The hacker embeds HTML <form> tags into 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 of the <form> tag is modified so that session information can be posted to the hackers Web site.

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 will read by using a Web browser. When the user opens the e-mail or reads the discussion board with her browser, the script is interpreted and executed on the client browser. Fortunately, most Web-based e-mail providers and discussion board administrators are aware of this type of attack and validate user input before rendering it arbitrarily to clients.

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 the querystring parameter. A hacker, who owns www.nwtraders.msft, sends an e-mail to an unsuspecting user with a link in it. When the user clicks the link, the name is echoed to the users browser by the welcome.asp page at www.contoso.msft. The problem is that in this case the name is actually a collection of HTML and Microsoft JScript. In this example, the HTML is a form that posts a hidden field named cookie to www.nwtraders.msft, which is owned by the hacker. The script fills the hidden field with Marys cookie 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.

26

Session: Writing Secure Code Threat Defense

Demonstration 2: Cross-Site Scripting

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

Investigating Cross-Site Scripting


1. 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 the C:\Courses\DeveloperSecurity\Democode\Websites\DemoCSS folder. 14. Double-click csslinks.html to open it with Microsoft Internet Explorer.

Session: Writing Secure Code Threat Defense

27

15. If prompted about enhanced security configuration, select the In the future, do not show this message 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.

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 zone settings 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, and throws an exception if any are found. The HTMLEncode and URLEncode methods, which can prevent scripts from running and hyperlinks from being active.

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.

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. The hacker can add their own commands to the SQL statement via the user input, thereby performing operations 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)/OLE DB error messages returned in Active Server Pages (ASP) to investigate the design of a database. Bypassing authorization. Hackers can modify authorization-based SQL statements to gain entry to a database. Executing multiple SQL statements. Hackers can append additional SQL statements to the ones written by the developer. Calling system stored procedures on Microsoft SQL Server. Hackers can execute some of the built-in stored procedures that ship with SQL Server to access server functionality.

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 SQL statements with input supplied by a user. Imagine that the user input is read directly from a textbox on a Web form or a Windows form, and then stored in the ID variable used in the code. A hacker can easily exploit this design by adding their own SQL statements as well as the expected query criterion. The developer expects a discrete value to be typed in the textbox, and then inserts that value between two single quotes in the SQL querys WHERE clause. If the user simply enters a discrete value 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, and then included an OR clause that always resolves to true. They have included the SQL comment marker (--) so that the database server ignores the trailing quote in the developer's code. The resulting SQL statement that would be executed is: SELECT HasShipped FROM OrderDetail WHERE OrderID = 'ALFKI1001' OR 1=1 --' This statement returns all rows from the OrderDetail table, rather than the single row intended by the 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 query criterion, but has then included a data definition language (DDL) statement that permanently deletes another table in the database. Even though there are now two distinct statements, the database server will process them both in a single batch. Again, the hacker has included the SQL comment 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, the hacker calls an extended stored procedure on the server, xp_cmdshell, which is capable of running any operating system command. For this example, the hacker runs the FDisk.exe command, which is capable of deleting and creating disk partitions.

32

Session: Writing Secure Code Threat Defense

Demonstration 3: SQL Injection

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

Investigating SQL Injection Issues


1. 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 of P@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 execute correctly. 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.

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 Injection


1. 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 of P@ssw0rd 16. Click OK. 17. Click Execute Sql. 18. Click Execute Sql Using PQ. 19. Close all applications.

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 than writing your own search and replace routines.

Run with least privilege. Do not execute an SQL SELECT statement as sa. Create low-privilege accounts to access data. 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 not process multiple statements as a batch.

! !

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 will discuss:
! ! !

What the canonicalization issues are. Examples of canonicalization issues. Defending against canonicalization issues.

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 allows an 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 might use 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 are alternate representations that might elude your security implementation. There are alternate representations for file names, URLs, and devices that you may be unaware of and for which you do not have a security strategy. Additionally, hackers can also traverse file and Internet directories by using canonicalization to execute files in critical folder paths.

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 provide access to the same file:
!

MyLongFile.txt This 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 and removes it in this file name. MyLong~1.txt Legacy file allocation table (FAT) systems require file names to have a maximum of eight characters, followed by three characters that represent the file type. Later file systems, such as FAT32 and NTFS, allow longer file names. For backward compatibility, later systems automatically generate an 8.3-format file name that includes the first six legal characters, followed by an incrementing digit and a tilde (~). MyLongFile.txt::$DATA In the NTFS file system, $DATA returns the default data stream for a file. This was exploited in IIS with ASP pages. The hacker can request the default stream of an ASP file, such as http://www.nwtraders.com/Default.asp::$DATA, and have the source code for this file returned.

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 in URLs and Web pages. This includes US-ASCII, hexadecimal escapes, legal and illegal Unicode Transformation 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%2fsecurity This is an example of a hexadecimal escape. %2e is the hexadecimal escape sequence for a period (.), and %2f is the hexadecimal escape sequence for a backslash (/). http://www.microsoft.com%c0%aftechnet%c0%afsecurity UTF-8 can be misrepresented by using varying byte sizes to represent the same character. This is an example of an alternate form of UTF-8. %c0%af is the double-byte UTF-8 representation of a backslash (/). http://www%25%32%65microsoft.com/technet/security This is an example of double escaping the period (.), which is first escaped to %2e and then escaped 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://2888530444 This is the alternate IP address for a Web site. This is an example of a dotless IP address. You can calculate a dotless IP address by using the following formula: (1st octet X 224) + (2nd octet 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 not be able to check for potentially dangerous strings.

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 file name alone.

Investigating File Name Security Decisions


1. 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\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.

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 be changed by the end user. Making sure that file names are well formed (if you must accept file names as input) and validating them within the context of your application. For example, you would check that they are 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.

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.

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 CryptoAPI provides 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 how strong the encryption algorithm is, if the hacker gets the key, the hacker can access your data.

A hacker only needs three of the four cryptography components to decrypt data. For example, if the 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 of weaknesses associated with it: Inappropriate use of algorithms. This includes attempting to create your own algorithms, using weak 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 be compromised. No algorithm remains secret for long. Most modern algorithms are standardized and 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.

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 Microsoft Windows XP. DPAPI is a powerful encryption class built into the operating system that uses a users password to derive user-specific or computer-specific encryption. Do not implement your own cryptographic routines.

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.

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 vice versa). Misusing MultiByteToWideChar, potentially causing a buffer overrun. Validating data before and not after conversion. When validating a Unicode string, the string may pass your validation tests. However, when the string is converted to ASCII, some characters 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.

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 is a byte. Be aware that Chinese language standard GB18030, which states that 4 bytes are used per character. Convert Unicode strings to ASCII before validating. This will prevent dangerous characters from remaining undetected. Use IsNLSDefinedString. This method checks whether each character in a string has a defined result for a specified NLS (National Language Support) capability. Always ensure that your target buffers are large enough when calling MultiByteToWideChar.

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 UNICODE strings.

Investigating Unicode Issues


1. 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\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.

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 will discuss:
! !

Denial of service attacks. Defending against denial of service attacks.

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 attacks deny 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.

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 sure to design mitigation techniques into your applications to prevent DoS attacks. You should also create 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 by expensive resources, such as database connections. Fail intelligently. Do not consume expensive resources for lengthy periods of time in the event of a failure. Test security. Create scripts or test applications to automate attacks. Look for memory leaks over time.

Session: Writing Secure Code Threat Defense

51

Session Summary

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

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.

Session: Writing Secure Code Threat Defense

53

For More Information

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

54

Session: Writing Secure Code Threat Defense

Questions and Answers

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

Session: Implementing Application Security Using the Microsoft .NET Framework


Contents
What We Will Cover Session Prerequisites ET Framework Security Features Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services Session Summary Clinic Evaluation 1 2 3 12 24 33 40 48 52 56

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2004 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Windows Server, SQL Server, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Session: Implementing Application Security Using the Microsoft .NET Framework

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.

Session: Implementing Application Security Using the Microsoft .NET Framework

Session Prerequisites

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

Session: Implementing Application Security Using the Microsoft .NET Framework

.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.

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 Framework security system is part of the common language runtime. The .NET Framework includes many features that you will learn about in this presentation, such as type checking for safe type-conversions, secure exception management, and code access security control. .NET Framework security is designed to complement the security provided by Microsoft Windows. It does not override Windows-based security. For example, if a Windows access control list (ACL) restricts access to a file, the .NET Framework does not override this security.

Session: Implementing Application Security Using the Microsoft .NET Framework

A Type-Safe System

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


!

Type-safety verification is the cornerstone of .NET Framework security because it prevents access to unauthorized memory locations. This allows you to consistently enforce security policy. For example, code cannot overrun a buffer and cause execution to jump to an arbitrary memory location. Type-safety verification allows the common language runtime to run more than one type-safe assembly in the same process. These sub-processes are called application domains. Application domains are especially useful in server scenarios in which the overhead of using many processes may slow system performance. In the past, the use of dynamic-link library (DLL)-based components was preferred for efficiency reasons, because EXE-based components were seen to be more secure and robust (due to the Microsoft Win32 virtual address space architecture). However, .NET supports the concept of an App Domain. An App Domain can be thought of as a process within a process, which provides good performance (like a DLL-based component), excellent security, and robustness.

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 .NET runtime uses classes such as System.String and System.Text.StringBuilder, which are managed by .NET type-verification checks. A String is an immutable object, which vastly alleviates the buffer overrun issue. Consider the following code: void CopyString (string src) { stringDest = src; }

When the code executes, a new resultant string object will be created, and the reference stringDest will 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 a robust class and will throw an exception if an attempt is made to overwrite its internal buffer.

Session: Implementing Application Security Using the Microsoft .NET Framework

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 Visual C# 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 checked keyword in your code. If you have turned arithmetic checking on at the project level, you can override the settings by using the unchecked keyword in your code. This is useful if you are certain that arithmetic errors cannot occur in specific blocks of code and you want to optimize those blocks when your code is compiled.

Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 1: Type Safety

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

Investigating .NET Data-Type Safety


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

Session: Implementing Application Security Using the Microsoft .NET Framework

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 Keyword


1. 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 directory C:\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.

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 then use them to digitally sign your assemblies. Strong-naming solves problems (such as version control and backward compatibility issues) that are caused when components are shared by multiple applications. In effect, strong names associate a distinct build of a component assembly with the client application. A distinct build is indicated by a combination of a version number and a special value that is called the publicKeyToken. You can generate a public/private key pair for signing your assembly by using the Strong Name tool (Sn.exe). When you have a private key, you can specify the key file and the version number to be assigned when 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 assemblys code, and allows confirmation of the assembly publishers identity. Strong-named assemblies also allow side-byside components to co-exist, which aids version control and backward compatibility.

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 from sources that are not trusted, the basic file system does not provide the necessary isolation and safety. Isolated storage is a data storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data. Administrators can use tools that are designed to manipulate isolated storage to configure file storage space, set security policies, and to delete unused data. With isolated storage, developers no longer have to invent unique paths to specify safe locations in the file system. Developers can now access safe locations by using either the applications identity or the users identity. The code sample on the slide show an example of how to access the isolated storage based on a users identity.

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.

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 a user 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 of the logged on user. Therefore, the application (which may be malicious) will have all of the system privileges granted to the user in question. .NET provides you with the concept of evidence-based security. This security works on top of Win32 security; it does not replace it. Irrespective of the logged on user, the .NET Framework collects evidence about an assembly and presents it to the security system. After the evidence has been gathered, the runtime will decide on whether 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, strong names and Authenticode signatures are considered stronger than URL or zone evidence, because it is more difficult for an attacker to fake values for these elements. Developers can create their own unique evidence. For example, they can create evidence that indicates an assembly was developed internally and reviewed by the IT department for security flaws.

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 assembly identity, 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 when determining 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 a variety of evidence. Administrators can use Active Directory to ease the deployment of security policies.

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 approach prevents an assembly without permissions, using your assemblies to perform unauthorized actions.

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 and invoking methods on them, such as the Demand method. For example, the developer may create an instance of the FileIOPermission object, and demand the Read permission for a specific file. If the call to the Demand method succeeds, execution continues, otherwise, a security exception is thrown. With declarative security checks, permissions are specified by using attributes instead of creating Permission objects at run time. At design time, developers specify permissions (such as the FileIOPermission Read access permission for a specific file) by including the attributes in class definitions or individual methods. Although the same types of permission can be managed as with the imperative approach, the declarative process makes it easier to review the required permissions for a class or method. However, because the permissions apply only to classes or methods, this approach is slightly less flexible than imperative checking. While obtaining evidence for both imperative and declarative security checks, the runtime will walk the stack, assuring that less privileged code further up the stack is not trying to execute code for which it does not normally have permission. However, you can use the Assert method to change the behavior of the stack walk. When the method in which you call Assert is reached, the stack walk stops. This means that permissions for the callers of your code are not checked. The Assert method is most useful when your code needs access to a protected resource, but your code does not give access to that resource to its callers.

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 not receive its minimum permission request at load time, it does not load, rather than waiting until an unauthorized operation is attempted and then failing. In the slide example, an assembly requests the Unmanaged code permission. If that permission is denied at load time, the assembly will not continue.

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 Tool


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

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 Checks


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

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 the file). 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 Permissions
1. 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.

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.

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 meant that code access security could not be applied to them. The .NET Framework 1.1 allows an administrator to define the trust levels for all Web applications within the machine.config file, thereby gaining control on what code access is available. Five trust levels are available, as follows: Full. Unrestricted permissions enable applications to access any resource that is subject to operating system security, and all privileged operations are supported. High. Cannot call unmanaged code, message queues, serviced components, or OLE DB data sources. 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.

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 privileged code 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 it to be called from a partial-trust Web application. Install the wrapper assembly in the global assembly cache (GAC). This automatically assigns the assembly full trust. Configure the Web application to use an appropriate trust level.

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.

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 a password, from a user and then validating those credentials against some authority, such as a database. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. For example, all users must provide a user name and password every time they log on to a network. These credentials are then validated against an authority, such as a database or a Windows-based domain server. After an identity has been authenticated, the authorization process determines whether that identity has access to a specified resource. The authorization process limits access rights by granting or denying specific permissions to an authenticated identity. For example, you can authorize one user to access the color printer, but deny access to another user. Similarly, you can authorize only the users 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.

26

Session: Implementing Application Security Using the Microsoft .NET Framework

Identities and Principals

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


!

An identity contains information about the users identity, such as their logon name and whether the 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 Windows credentials for a user. GenericIdentity and GenericPrincipal objects enable the developer to implement their own authentication technique.

! !

The following slides show how to create Windows and Generic principals and identities, and then demonstrates how to use them to make role-based security checks.

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 code sample is more efficient, if the principal and identity are retrieved for a single check, whereas the second sample is more efficient if multiple checks will be made. After you have created Windows identities and principals, you can use them to perform security checks.

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 implement custom authentication techniques, such as finding credentials in a database, rather than perform authentication based on a users 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.

! !

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 perform security checks in your code. The slide demonstrates two examples.
!

The first code example performs a case-insensitive string comparison of the current identitys Name 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.

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 objects 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 a class or an individual method, so that a security check is performed when the class or method is used. Although the same types of check can be performed as with the imperative approach, the declarative 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 less flexible than imperative checking.

Session: Implementing Application Security Using the Microsoft .NET Framework

31

Demonstration 3: Role-Based Security

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

Using Windows Role Based Security


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

32

Session: Implementing Application Security Using the Microsoft .NET Framework

Using Generic Role Based Security


1. 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: configureSecurity DecPermButton_Click ImpPermButton_Click PrincipalButton_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.

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.

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 the secret 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 encrypted with 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 data that 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 this signature with the data. When a recipient receives the data, the recipient can decrypt the data with the senders public key and compare it with the hash value of the data. If the values match, the integrity of the data is guaranteed.

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 for working with symmetric encryption, such as the TripleDESCryptoServiceProvider the RijndaelManaged classes. 2. Generate a secret key by using the .NET wrapper class that you have chosen. Symmetric algorithms require this key to encrypt and decrypt data. The class constructor can create these values or you can provide your own. 3. Use the same key to encrypt and decrypt data. You can encrypt data by using any class that derives from the Stream class, including FileStream, MemoryStream, and NetworkStream.

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 for working with asymmetric encryption, such as the RSACryptoServiceProvider and the DSACryptoServiceProvider classes. These classes use the well-known algorithms after which they 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. Other operations, 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 encrypting data, you would use the public key, whereas if you are decrypting data you would use the private key. You can encrypt and decrypt data by using any class that derives from the Stream class, including FileStream, MemoryStream, and NetworkStream.

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 will want to sign data so that other's can be assured of your identity, whereas at other times, you will want 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 asymmetric algorithm to verify the signature.

38

Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 4: .NET Framework Encryption

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

Performing Symmetric Encryption


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

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 Data
1. 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.

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.

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 in conjunction with Internet Information Services (IIS) authentication. With Windows-based authentication, the user requests a secure Web page from the Web application, and the request then passes through IIS. If the users credentials do not match those of an authorized user, IIS rejects the request. The user then has to enter his or her name and password in the logon form. The credentials are again verified by IIS. If these credentials are accepted, IIS directs the original request 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 Hypertext Markup Language (HTML) form. The user provides their credentials and submits the form. If the application validates the credentials on the form, the system issues an authentication cookie to the user. Subsequent requests from the user are issued with the authentication cookie in the request headers, and then the user is authenticated on that basis. You will see how to set up forms-based authentication in the next slide. You will then see the .NET enhancements that are associated with forms-based authentication. Passport authentication is a centralized authentication service, provided by Microsoft, which offers a single logon option and core profile services for member sites. Users who sign up to use Passport are authenticated by Web sites with a single Passport account. Microsoft Passport is an XML Web service, and is an integral part of the .NET Framework.

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 four tasks: Configure IIS to use Anonymous authentication so that the user is authenticated by ASP.NET and not by IIS. Set the authentication method to 'Forms' for the application in an <authentication> subsection of the <system.web> section in Web.config, If you set the authentication mode to 'Forms', you must add a <forms> element to the <authentication> section, as shown in the slide example. In the <forms> section, configure the settings of the cookie. Set the name attribute to the suffix to be used for the cookies and the loginUrl attribute to the Uniform Resource Locator (URL) of the page to which unauthenticated requests are redirected. Set up the <authorization> section in Web.config to deny or allow users access to your Web application. You can also mark the entire Web application as needing authorization or specify authorization 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 a password. The page requires the users to enter their user name and password to access to your Web application.

Although you can perform these tasks in any order, ensure they are all completed before deploying your solution, otherwise forms-based authentication will not work.

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 each request 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 can ensure 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 compliant browsers will only return the cookie over SSL. One consideration with secure cookies is the use of validation and decryption keys. These can be automatically generated for the application. However, it is possible for the same key to be generated for several Web applications on the same computer. To avoid this, developers can use the IsolateApps parameter within the machineKey element in the web.config file.

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 option with some browsers. The validation controls in ASP.NET have both client-side and server-side support. Client-side validation uses JavaScript and dynamic HTML (DHTML) scripts. Server-side validation can be written in any .NET-based language. Client-side validation enhances the usability of the Web Form by checking user input as the user enters data. By checking for errors when data is being entered, client-side validation allows errors to be detected on the client before the Web Form is submitted. Writing multiple versions of validation code to support both the server and several different browsers can be extremely time-consuming for developers. ASP.NET validation controls eliminate this problem because the validation logic is encapsulated within the controls. The controls create browser-specific code so that users with client-side script support will have client-side input validation. 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 posted back to the server until all client-side validation is true. In Internet Explorer 5 or later, using the TAB key to move from one input control to the next runs the client-side validation for the completed input control. All input validation controls also run on the server side. Client-side validations are repeated on the server side when the page is posted back to the server. This repetition avoids attackers bypassing the client-side script and trying to use provide input.

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 validation expression. 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 can verify 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 by a 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 the validation controls on the page. This control is typically placed near the Submit button to provide immediate feedback on the page input status.

46

Session: Implementing Application Security Using the Microsoft .NET Framework

Demonstration 5: ASP.NET Web Application Security

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

Configuring Forms Authentication


1. 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 security configuration, 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.

Session: Implementing Application Security Using the Microsoft .NET Framework

47

Using Validation Controls


1. 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 the RegularExpressionValidator to TextBox1. 11. In the properties window, set the ErrorMessage property for the RegularExpressionValidator to Invalid input. 12. In the properties window, set the RegularExpressionValidators ValidationExpression to Internet 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 someone@microsoft.com into the textbox. 17. Press the button. 18. Close Internet Explorer and Visual Studio .NET 2003.

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.

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 administrators cannot usually secure both end-points in this type of communication, so the actual message itself needs 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 SOAP headers. The security tokens may include Kerberos tickets, X.509 certificates, or a custom binary token. Secure communication is provided by digital signatures to ensure message integrity and by XML encryption for message confidentiality. WS-Security can be used to construct a framework for exchanging secure messages in a heterogeneous Web services environment. It is ideally suited to heterogeneous environments and scenarios where you are not in direct control of the configuration of both endpoints and intermediate 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 intermediate application nodes. Supports multiple encryption technologies. Supports non-repudiation.

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 to implement security within a SOAP message, rather than relying on security features of other protocols (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 are defined in the WS-Security standard, or binary tokens, such as an X.509 Certificate token. On the server-side, you can implement your own mechanism for storing user names and passwords. Message encryption. This is implemented through input and output filters, which allows developers to use both the SOAPWebRequest and SOAPWebResponse, thereby applying whichever encryption mechanism they require to the messages. Message signing. This is a signature element generated from an X509 security token. The signature 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 the header 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 in Microsoft.Web.Services.dll.

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 Service


1. SWITCH TO THE LONDON VPC 2. Using Internet Explorer, open the file UsernameToken.xml, which you can find in the folder C:\Courses\DeveloperSecurity\Democode\Session04\WSE. 3. Highlight the wsse:UsernameToken element. 4. Open the file X509Sign.xml, which you can find in the folder C:\Courses\DeveloperSecurity\Democode\Session04\WSE. 5. Within wsse:Security element, highlight the wsse:BinarySecurityToken. 6. Close all applications.

52

Session: Implementing Application Security Using the Microsoft .NET Framework

Session Summary

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

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.

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 Web sites:
!

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

Session: Implementing Application Security Using the Microsoft .NET Framework

55

Questions and Answers

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

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 your learning experience. To complete a clinic evaluation, go to http://www.CourseSurvey.com. Microsoft will keep your evaluation strictly confidential and will use your responses to improve your future learning experience.

You might also like