Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional ASP.NET Security - Jeff Ferguson

.pdf
Скачиваний:
28
Добавлен:
24.05.2014
Размер:
13.26 Mб
Скачать

SQL Injection

Similar problems to those posed by script injection and cross-site scripting are caused if we do not treat input that will be sent to the database properly. Incorrect handling of such input can lead to malicious SQL code being executed on the database server. An exploit for this vulnerability will take the form of some specially crafted SQL code in user input.

The threats exposed by SQL injection depend largely on the permissions of the user account being used to access the database. They can run from exposure and altering of data through to execution of code on the database server and the denial of service and unauthorized access threats that that can present.

Techniques for preventing SQL injection are covered in Chapter 2.

Distributed Denial of Service

In the last couple of years, a new threat to web applications has emerged. A Distributed Denial-Of-Service (DDOS) attack involves using a number of machines to attack a single system. Together, a group of machines can launch so many spurious requests that the target system is overwhelmed -making it unable to service other users or even causing it to crash. This is known as a 'flood'.

The key thing that a would-be attacker has to do in order to launch a distributed denial of service attack is gain the use of sufficient machines from which to send the spurious requests. Malicious users are increasingly making use of the machines of unwitting users who do not realise their systems are being used to launch an attack. A number of techniques are used to gain control of these machines. Operating system or application vulnerabilities are exploited to allow the malicious user to place their own application (a Trojan Horse') on the machine. This application will then wait for an instruction, often delivered through an Internet Relay Chat (IRC) channel. Once the instruction is received, it will start sending spurious requests to the target, forming its part of the DDOS attack. Machines that have been exploited in this way to form part of a DDOS network are often referred to as 'zombies'.

DDOS attacks are being increasingly launched against a range of systems. The servers that host web applications are common targets but systems that form the network infrastructure such as routers are also being hit by such attacks. Even firewalls, intended to protect networks, are finding themselves under attack.

DDOS attacks are difficult to defend against because the traffic they generate is very difficult to distinguish from legitimate traffic. Preventing DDOS attacks requires good, efficient filtering of network traffic. A constant battle is being fought between security professionals, who are developing better ways to filter network traffic, and the people who develop DDOS software, who are always finding new ways to disguise the traffic they generate to defeat filters.

Although there is not much we can do within our application to defend against DDOS attacks, we need to be aware of them as a possible way in which our application could be attacked.

Social Engineering

Sometimes the vulnerability that is exploited is not a technological one but a human one. If users are badly trained in security issues, they can be easily misled and tricked into opening up a route into a system for an attacker.

16

Building Secure Web Applications

In the past, social engineering exploits relied on the attacker having the confidence to convince a user that they should hand over confidential information (for instance, by phoning the user and claiming to a computer administrator that needs their password for security reasons). In recent times, the vast majority of social engineering attacks are performed by e-mail. Users are tricked into replying to an e-mail with confidential information or, more commonly, are tricked into running an executable. Many e-mail viruses and worms use this method of propagation - they trick a user into executing an attachment, which then gains control of the e-mail software and uses it to send itself on to other recipients.

The threats of social engineering attacks can vary widely. Social engineering that is done in person usually has the aim of getting access to a system (getting a username and password) while worms and viruses are often only designed to propagate (although some do install 'trojan horse' programs that allow unauthorized access to each system they infect).

Brute Force Attacks

If we do not implement systems to prevent malicious users making an unlimited number of attempts to log in to our application, we are vulnerable to a large number of guesses being made in order to get the right password. This is known as a brute force attack.

A brute force exploit will consist of an application that can send very large numbers of requests to an application, with different passwords for each. Such applications typically use a dictionary of commonly chosen passwords as a starting point.

Another form of brute force password cracking is when an attacker is able to obtain encrypted passwords from the file or database where they are stored. While strong encryption will prevent them from gaining the passwords directly (we look at the critical technique for this, hashing, in Chapter 9), they can still run a brute force attack against the passwords, attempting to find passwords that will produce the same encrypted value.

The threat from a brute force attack depends on the privileges of the user whose password is cracked. Administrative users would, we would hope, have well chosen passwords that are much harder to crack but even a lowly user account can provide the foothold onto a system that an attacker needs.

We will look at how to enforce strong password practice in Chapter 5.

Everybody is Attacked Sooner or Later

It is the sad truth that any computer system connected to the Internet will, at some point, be the subject of an attempted security breach. This is true even for systems that are not directly targeted by individuals. The reason for this is the huge growth in automated tools that allow even users without in-depth technical knowledge to search for vulnerable systems and penetrate them.

Experienced programmers create these tools in order to show how vulnerabilities can be exploited or for their own use, but they soon find their way into the hands of less experienced users. An increasing number of these users (known in the security world as "Script Kiddies" because of their lack of technical experience) are using these tools to exploit vulnerabilities in a random selection of systems. Rather than targeting the specific systems they want to penetrate, these users 'fish' for systems that are vulnerable.

Another factor is self-propagating code such as viruses and worms. Strictly speaking, a virus is code that attaches itself to existing code while a worm is code that propagates itself in its own right. However, the word virus is commonly used to refer to both types of self-propagating code. An increasing proportion of viruses and worms are using vulnerabilities in networked applications to spread themselves to new systems.

1 7

Viruses and worms are typically completely indiscriminate in choosing the machines they will spread to, simply searching for vulnerable machines. Once a vulnerable system is found, it is infected and used to launch new attacks. This means that anyone's system can be a target (and probably will be if the virus spreads for long enough).

Security is Not Just about Keeping People Out

When we think of security, it is tempting to think of our application as a castle. We build a secure wall around it and restrict access through gateways. We can secure web applications like this but if we do nothing else, we have no way of identifying visitors once they are inside the wall.

Many of the advantages of web applications over static content are based on the idea of delivering different content to different users. This might be for the benefit of the users such as when we personalize the way content is displayed or show content that we know they will be interested in. It may also be done because there is some content that we only want to grant particular users access to. For instance, we probably would not want to grant all employees with access to an intranet permission to view the personal details of other employees. This permission would be restricted to those who require it.

If we design our application security so that it not only controls access to the application but also allows users to be identified while they use the application, we gain the ability to personalize content and control what content is accessed. Even if we do not think we will want to do these thing immediately, it is wise to ensure that we have the capability to do them in the future without completely changing our security systems.

Who is Responsible for Security?

The simple answer to this question is that that everyone bears some responsibility for the security of a system - from the day-to-day users to the architect who made the fundamental design decisions.

Things are obviously more complicated than that - different people are responsible for different aspects of developing and using the application and thus have different scopes for helping to ensure security. For example:

G Application designers need to ensure that the architecture for the application is secure Q Network Administrators need to keep the network and servers secure

Q Programmers need to ensure their code does not introduce vulnerabilities Q Managers need to ensure that their teams are aware of security issues

Q Database administrators need to ensure that database servers are not vulnerable Q Users need to be aware of issues such as social engineering attacks

There are, of course, many other roles with their own contributions to make to security.

18

Building Secure Web Applications

What is Outside Our Control as ASP.NET Developers?

As we have seen in the previous section, many different types of people can and should contribute to the security of an application. Sometimes, a single person will be responsible for more than one of these roles (for instance, in a small business where the application developer also administers the servers).

Sometimes, aspects of security will be divided among many people.

This book is about ASP.NET security so we will be concentrating on the contribution we can make as ASP.NET developers. It is, however, useful to acknowledge the aspects of security that may fall outside our immediate scope. It is important to communicate with the people who do deal with these areas. If their areas are not secure, our efforts in coding the application securely may be wasted.

The Network

Web applications, by their nature, rely on the network they operate over. If the network is brought down by a denial of service attack, our application will not operate. If a malicious user can listen to network traffic (known as 'sniffing'), they may be able to gather information that we do not want them to have access to.

Web Servers

The servers upon which our applications run must be secure. If they are not, a malicious user can make changes to our application, negating our security efforts.

In order to provide a secure foundation for ASP.NET, both Windows and Internet Information Services must be configured for security. Windows configuration is outside the scope of this book but, as many ASP.NET developers are also responsible for configuring IIS, Appendix A has information on steps that should be taken to configure IIS securely for use with ASP.NET.

Database Servers

Most ASP.NET applications rely on a database for their data. If the database is compromised then the application will be affected. In Chapter 4 we will discuss some techniques for preventing our application from exposing the database. The security of the database server itself is a topic that is beyond the scope of this book.

Client Machines

It can be easy to forget that, although client-side code can be useful to us, we ultimately have no control over client machines. For example, JavaScript code for validation can be useful but it can always be bypassed.

Any data arriving from client machines should be treated with suspicion. In Chapter 2, we discuss some techniques for dealing with data from client machines in a safe manner.

What Can We Do as ASP.NET Developers?

While there are many security issues that may be beyond our control when developing, deploying, and maintaining an ASP.NET application, there are some things that we should always do to contribute to good security.

1Q

Push for Security to be a Priority

Many people within a business will not appreciate the importance and difficulty of building and maintaining systems with an acceptable level of security. In the past, this has lead to security becoming a peripheral issue rather than a core consideration.

Clients and managers will never agree to spend money on a feature unless its benefits are clear to them. The risks of ignoring security need to be understood in order for the benefits of spending time and money on security to become apparent.

It is our duty as programmers to educate others in the business about the importance of security. We should ensure that security is introduced as a core feature of a system from the earliest stages of its discussion. We should make sure that security remains a priority right through to deployment of the application and beyond.

Security functionality should always be a core feature of the system. If it is not, we should demand that it is.

Implement Solid Security Features

Building features into the application to support security is the most obvious thing that we can do as ASP.NET developers to keep the system secure. The responsibility for making the right choices about how the use of our application should be controlled rests squarely on our shoulders.

It is important to remember that the most secure systems are those that have been subjected to wide scrutiny and testing. This means that it is almost always better to use an established solution to a security problem than to code our own. Even minor modifications to an established scheme should be examined closely to ensure they don't break its security.

In Chapters 6 to 12, we will be looking at the framework that ASP.NET provides for implementing commonly required security functionality. It is strongly recommended that you use the provided framework as the basis for your own systems rather than starting from scratch.

Avoid Adding Additional Vulnerabilities

Every piece of code added to an application can, potentially, add new vulnerabilities. All new code needs to be examined to ensure that it does not introduce any security holes that could be used to compromise the application. Chapter 2 discusses how we can avoid some common web application vulnerabilities. It is the responsibility of every ASP.NET programmer to ensure that their code does not introduce new vulnerabilities to an application.

It can be very tempting to implement features without solid security and then go back and secure them once the application is working. This can be risky because doing this can mean that there is a risk that vulnerabilities will 'slip through the net'. A much better approach is to develop each part of the application securely from the start. For example, as we will see in Chapter 2, user input needs to be processed properly in order for it to be dealt with securely. Coding this processing as the user input features are created can save a lot of headaches further down the process.

Another related problem is forgetting to remove 'trapdoors' from the application. Trapdoors are shortcuts around security systems, usually added for convenience during development and debugging. If left in the application, trapdoors can provide an easy route in for a malicious user. It is good practice to clearly mark such code. For example, if we use a clear, standard, comment to mark code that needs to be removed towards the end of development:

20

Building Secure Web Applications

public Boolean ValidateCreditCardfstring creditCardNumber) { //***TESTING CODE - TO BE REMOVED***

//Added by Jenny 03/02/2002 if(creditCardNumber == "0000")

return true;

//rest of method... }

we can simply search for the standard text * * * TESTING to locate any test code that may not have been removed.

Help Users to be Secure

It is helpful to educate users of the system about security issues. The popularity of social engineering attacks means that the users themselves now provide some of the most commonly exploited vulnerabilities.

No matter how much we educate our users, some will always ignore the advice they are given. This is why it is important not to rely on them. A better solution is to force them to be secure as much as is possible, taking decisions that could cause insecurity away from non-technical users. As an example of this, in Chapter 5 we will look at techniques for requiring users to use secure passwords.

Be Aware of Data Flows and Leaks

It is important for us to be aware of how data flows around our application. This is especially true when data will be flowing to client machines across communications lines that we do not control.

Try to maintain an accurate picture of data flows. It is important to distinguish between trusted data (that we are sure has not been tampered with) and untrusted data (that could possibly have been tampered with). A picture of data flow can help to identify places where untrusted data is introduced into the application or where trusted data becomes untrusted.

For example, all user input should be treated as untrusted until it has been validated. Once validated we can treat it as trusted (providing we are confident that our validation is water-tight). If we put this data into a hidden form field with no additional protective measures, we must treat it as untrusted when it comes back from the client.

Stay Up-to-Date

Computer security is a constantly shifting battleground where new vulnerabilities and exploits are being discovered as quickly as existing problems are solved. It is very important to ensure that we stay up to date with the 'state of the art1. Most vulnerabilities are resolved (usually by the software vendor releasing a patch) soon after they arise, but if we are not aware of them, we will not apply the patch and will not be protected.

The infamous 'Code Red' worm caused chaos on the internet as it spread through a buffer overflow vulnerability in the indexing service of IIS. The vulnerability that it exploited had, in fact, been addressed with a patch two months before the first known Code Red infection. If those with vulnerable IIS installations had applied the Microsoft patch, they would have been immune and the worm would not have been able to spread as it did.

Microsoft Security Bulletins

Since ASP.NET applications will typically run in environments dominated by Microsoft software, it makes a lot of sense for ASP.NET programmers to be aware of security issues with Microsoft products. Microsoft posts security bulletins whenever vulnerabilities are identified in their software. These are available at:

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

A better way of ensuring that you are up to date with the latest bulletins is to subscribe to have security bulletins sent to you by e-mail. You should be able to do this through the Microsoft.com profile center:

http://register.microsoft.com/regsys/Pic.asp

This requires a passport account. Note that at the time of writing, this system was not offering the security notification service in the list of newsletters it offers.

There is another way to sign up to receive the security bulletins by e-mail. You can send an e-mail to:

securbas@microsoft.com

The subject and text of the e-mail are not important. You will then get a confirmation e-mail. Replying to this with "OK" in the message body signs up your e-mail address for notifications.

Once signed up, you will receive notifications whenever Microsoft announces security vulnerabilities and their related patches. These announcements vary in their frequency. For instance, at the time of writing Microsoft is engaged in an intensive program of security testing, so security bulletins are unusually frequent.

Here is an example of a Microsoft security bulletin:

----- BEGIN PGP SIGNED MESSAGE ----

Title:

SQL Extended Procedure Functions Contain Unchecked

Date:

Buffers (Q319507)

17 April 2002

Software:

Microsoft SQL Server

Impact:

Run Code of Attacker's Choice

Max Risk:

Moderate

Bulletin:

MS02-020

Microsoft encourages customers to review the Security Bulletin at:

http://www.microsoft.com/technet/security/bulletin/MS02-020.asp.

Issue:

SQL Server 7.0 and 2000 provide for extended stored procedures, which are external routines written in a programming language such as C. These procedures appear to users as normal stored procedures and are executed in the same way. SQL Server 7.0 and 2000 include a number of extended stored procedures which are used for various helper functions

22

Building Secure Web Applications

Several of the Microsoft-provided extended stored procedures have a flaw in common - namely, they fail to perform input validation correctly, and are susceptible to buffer overruns as a result exploiting the flaw could enable an attacker to either cause the SQL Server service to fail, or to cause code to run in the security context in which SQL Server is running. SQL Server can be configured to run in various security contexts, and by default runs as a domain user. The precise privileges the attacker could gain would depend on the specific security context that the service runs in.

An attacker could exploit this vulnerability in one of two ways. Firstly, the attacker could attempt to load and execute a database query that calls one of the affected functions. Secondly, if a web-site or other database front-end were configured to access and process arbitrary queries, it could be possible for the attacker to provide inputs that would cause the query to call one of the functions in question with the appropriate malformed parameters.

Mitigating Factors:

-The effect of exploiting the vulnerability would depend on the specific configuration of the SQL Server service. SQL Server can be configured to run in a security context chosen by the administrator. By default, this context is as a domain user.

If the rule of least privilege has been followed, it would minimize the amount of damage an attacker could achieve.

-The vector for exploiting this vulnerability could be blocked

by following best practices. Specifically, untrusted users should not be able to load and execute queries of their choice on a database server. In addition, publicly accessible database queries should filter all inputs prior to processing.

Risk Rating:

- Internet systems: Moderate - Intranet systems: Moderate - Client systems: Moderate

Patch Availability:

- A patch is available to fix this vulnerability. Please read the Security Bulletin at http://www.microsoft.com/technet/security/bulletin/ms02-020.asp for information on obtaining this patch.

THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMSALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANYDAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL,LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION ORITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOMESTATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIALOR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

----- BEGIN PGP SIGNATURE ----

Version: PGP 7.1

lQEVAwUBPL3C440ZSRQxA/UrAQFzrQgAoPk7hIz9vDDsDoK93hb5EQ86FytDYOe2

FDC6be9BfRKyb46AJjmjwea+Z9tdObcWyqlleF8zzAI8VhKg7b9CsBhw+tSDAz/T

WZsCmqxhoMChjOApfJq/OqrlQzOmtcOylSiCXvhMRN/I/hVXseYtrZF9ofV75P3j

zJrtRuz/2PUsGm8cq4Ce6YJRrnM9Ctmmvs3ar8CQFSROHb9+O6/m/buIcZn3XyEZ

5RTdlJK31Y3oe9CecIBRIuvIoDbMP/IqQ/P44wCluaEv/UISJICOslhicCkthFMX glzMBNOqIETMDBzclxbfNuOelPkmg6Xm80oEZpAPNUXBL6/+ouUGYw= =

=JIJX

-- END PGP SIGNATURE ----

It is useful to read all of these posts but if you don't have time to do that, the important bit to look for is the Software: line near the top. If the software listed includes anything that you use to support your application, you should carefully read the bulletin and seriously consider implementing the advice as soon as possible.

Note that the message has a PGP signature attached. This means that anyone with PGP software can verify that the message actually came from Microsoft. The public key associated with these messages can be downloaded from:

http://www.microsoft.com/technet/security/MSRC.asc

BugTraq

If you are interested in reading about a wider range of security vulnerabilities, their exploits, and the solutions to these problems, the BugTraq list is a really good way to stay up to date. BugTraq (provided by securityfocus.com) has gained an unmatched reputation for being the first to publicize new vulnerabilities. Information is posted to BugTraq as soon as it becomes available so if you are serious about keeping up to date, BugTraq is an important list to subscribe to.

You can subscribe to BugTraq (along with many other security related lists) at:

http://www.securityfocus.com/cgi-bin/subscribe.pl

Posts to BugTraq are usually not so formally formatted as those sent out by the Microsoft bulletin service. They are made by a wide range of companies, organizations, and individuals.

BugTraq, by it nature generates a lot of traffic on a wide range of security issues. You may prefer to subscribe to one or more of the other lists provided by securityfocus.com. These other lists are more focused than BugTraq and usually have lower traffic. Some of the lists that are probably of interest are:

24

Building Secure Web Applications

MS-SecNews - this list summarizes issues related to Microsoft products

webappsec - this list is specifically intended for discussion of issues related to web applications

FocusMS - this list "picks up where bugTraq leaves off with deeper discussion of Microsoft products.

Some Security Advice

We will now look at some important security points. Remembering these points can help to design, implement, and maintain good security in our applications. Here are the points we will be looking at:

U There is no such thing as being 100% secure

Q 'Security through obscurity' is not security

Q The application is only as secure as its weakest link

Q Security is important at every stage of development

Q In security, the job is never done

Q Over restrictive security can be counter-productive

Q Security is not just about technology

Q We can't rely on users to maintain security

In the following sections, we will talk about each of these points in turn and present advice that follows from them.

There is No Such Thing as Being 100% Secure

A popular saying in computer security is that 'the only secure system is one that is unplugged and locked in a safe'. It seems strange to admit that our systems cannot be 100% secure but it is important to realize that if an attacker has sufficient determination and resources, there is always a possibility that they will find a way in. There are countless ways into a system and an attacker need only discover one that is unprotected in order to gain access.

So, if we can never achieve total security, what can we do? We can make it as difficult as possible to gain unauthorized access. By making access more difficult to gain we 'raise the bar' for attackers, forcing them to expend greater effort and resources. Many attackers are opportunistic - they will not bother with a system that is difficult to access when there are plenty of much easier targets available. There are exceptions - some attackers will see a well-secured system as a challenge, especially if it is advertised as such. In general though, the better our security, the greater the proportion of attackers that will give up and move on to an easier target.

Although we can't guarantee that our system is totally secure, we should 'raise the bar' as far as possible.

Соседние файлы в предмете Программирование