10.5. Security Guidance

You don't know what you don't know, so how do you know what you don't know? In recent years the IT industry has seen an increased awareness about IT security. Evidence can be seen by the abundance of resources on the subject. Security awareness resources can take many forms from books, articles, conferences, and communities.

Nothing beats curling up alongside a fire and reading the latest IT security book! Some managers and developers alike do not find IT security fun and exciting. They understand the importance of strong security in their application, but would rather be learning about something that is more exciting (such as new language features in the next version of C#). This mindset is very common, and because of this, security communities have emerged that not only help stress the importance of security, but help developers and managers learn how to solve the most common IT security issues.

10.5.1. Web Application Security Consortium

The Web Application Security Consortium (WASC) is an international group of experts, industry practitioners, and organizational representatives who work to produce open source tools and who agree on the best practice security stands for web applications.

The WASC is an open forum to discuss security issues, educate developers and managers about security issues, and act as a vendor natural voice of the web application security industry.

10.5.1.1. Notable Projects

There are many extremely useful projects that are maintained under the WASC project, but there are two projects that have helped make the WASC a leader in web security reference.

  • Web Security Threat Classification. The Threat Classification project is a cooperative effort to organize and provide insight to web application threats. This document contains a list of known attacks and discusses key points about each attack. After reading the Web Security Threat Classification, the reader will have gained a great insight into the many different types of web application attacks.

  • Web Application Security Statistics. The WASC Security Statistics project is a collection of web application vulnerability statistics. The intent of this project is to help identify the existence and proliferation of web application security issues.

10.5.2. Open Web Application Security Project (OWASP)

OWASP is a not-for-profit organization that is focused on improving the security of web applications. OWASP is an open community with more than 130 local chapters that organize conferences and hold monthly "user group" meetings to discuss application security. Many developers have contributed to the OWASP with their knowledge about application security by presenting at these conferences and user group meetings, while others contribute to the project by submitting code to one of the many security tools that are maintained under the OWASP.

10.5.2.1. OWASP Tools

The OWASP contains tools written in numerous different languages, with .NET and Java being the most prominent. All the tools are free and most are released under some type of open source license. The OWASP tools are organized into three categories:

  1. Protect. Tools and documentation that can be used to guard against implementation flaws and other security-related issues.

  2. Detect. Tools and documents that can be used to find implementation flaws and other security-related issues.

  3. Life Cycle. Tools and documents that can be used to add security-related tasks to the software development life cycle.

10.5.2.2. OWASP Top 10

The OWASP Top 10 project is a document created from a broad consensus of security experts, as to what they feel are the most critical web application security attacks. The intention of the OWASP Top 10 project is to increase awareness of these most critical security attacks in hopes to change the software development community to produce code that is more secure. The project team meets regularly to assess the attacks in the document. The document is updated sporadically based on input from the OWASP Top 10 project team.

The OWASP Top 10 project is very similar to the WASC Web Security Threat Classification discussed previously with the difference being that the OWASP Top 10 only discusses the most critical security attacks. It is because of this reason that the OWASP Top 10 project is a great place to start when testing the security of web applications:

A1 - Cross-Site Scripting (XSS)

A2 - Injection Flaws

A3 - Malicious File Execution

A4 - Insecure Direct Object Reference

A5 - Cross-Site Request Forgery (CSRF)

A6 - Information Leakage and Improper Error Handling

A7 - Broken Authentication and Session Management

A8 - Insecure Cryptographic Storage

A9 - Insecure Communications

A10 - Failure to Restrict URL Access

10.5.3. Testing for the OWASP Top 10

This section talks specifically about how to test each vulnerability in the OWASP Top 10 List of 2007. This section is intended to give you a good introduction to the attack and how to test to see if your web application is vulnerable to this attack. This section will not give you an entire set of data to test with though. For example, we will teach you about cross-site scripting, provide some examples, but will not provide a comprehensive set of malicious inputs that can be used. It's better to get attack data online, because it is more recent.

When learning about the OWASP Top 10 attacks, it's useful to have a system that is vulnerable to the attacks, so you can learn exactly how the tools work. In the security world, these types of systems are called Honey Pots. The OWASP has just such a project, named Web Goat. Web Goat is a deliberately insecure application created in J2EE. Although the following sections provide pages created in ASP.NET that are not secure, Web Goat is an extensive application that has many online tutorials to assist with learning how to test for web application security.

10.5.3.1. A1 - Cross-Site Scripting (XSS)

A cross-site scripting (XSS) attack is a type of attack in which an attacker is able to inject code, usually in the form of client-side JavaScript, into an input field of a web application that is later rendered to other clients without any encoding performed. XSS attacks are extremely common and dangerous. The nature of the Web is to trust JavaScript on web applications. It is because of this that XSS attacks can execute malicious JavaScript to exploit users of the compromised web application. Nearly 80 percent of all documented security vulnerabilities as of 2007 were caused by XSS attacks. An attacker can use XSS attacks to exploit phishing schemas, identify theft, and annoying messages to just about any other malicious thing you can execute with JavaScript.

10.5.3.1.1. Testing for Cross-Site Scripting Attacks

There are many different tools that are available to test for cross-site scripting attacks. Throughout this section, most of the examples will be using WebScarab. WebScarab is a free tool created under the OWASP project that can be downloaded from http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project.

WebScarab acts a proxy, intercepting all requests between the web application and the browser. To start using WebScarab, you will first need to configure your web browser to use a proxy connection. Figure 10-1 shows the proxy configuration for Firefox with the default port of 8008 used by WebScarab.

After the proxy is configured in Firefox, you are ready to begin your WebScarab conversation. Figure 10-2 shows the Summary tab of WebScarab, which contains a list of the requests that have been captured during the conversations.

Clicking each request will allow the user to drill in and see the specific information about each request as in Figure 10-3.

To test for cross-site scripting flaws using WebScarab, we will be using a testing technique called fuzzing. Fuzzing will input invalid, random, or unexpected data into the inputs of a web application.

To fuzz using WebScarab you first need to right-click the request that contains the parameters you would like to fuzz and select Use as fuzz template, as shown in Figure 10-4.

Figure 10-1. Firefox proxy settings

Figure 10-2. WebScarab Summary tab

Figure 10-3. WebScarab conversation detail

Figure 10-4. Selecting the fuzz template

After the fuzz template has been created, you will navigate to the Fuzzer tab in WebScarab. The Fuzzer tab is where the inputs to be fuzzed will be set up. Input fields, query strings, hidden values, and more can be fuzzed as shown in Figure 10-5.

For your test you will only be fuzzing the username and password text boxes, so the other parameters can be removed as shown in Figure 10-6.

After you have decided which parameters you want to fuzz, you need to decide what type of data you would like to use. This is accomplished by clicking the Sources button on the Fuzzer tab. WebScarab allows the fuzzing data to either be a regular expression, or data from a text file.

  • Regular Expressions. For example, entering [0-9][0-9][0-9][0-9] in the Regular Expression field and giving it a description of 4 Digit Number, will submit all digits between 0000 and 9999 to the web application.

  • Attack Files. Because we are testing for XSS vulnerabilities, we are using a text file entitled XSS_Attacks that only includes strings that could be XSS attacks. Figure 10-7 shows the loaded XSS_Attacks file in the Fuzz Sources screen.

Figure 10-5. The fuzz template in place

It's important to note that for the purposes of demonstration we have limited the fuzzing to only test for XSS attacks. When performing a true security test, fuzzing data can include all types of data such as SQL injections, XSS, Path Traversal, and many more types of attacks. A good file to start out with is the All_attack.txt from neuro fuzz which can be downloaded from http://www.neurofuzz.com/modules/software/wsfuzzer/All_attack.txt.

Figure 10-6. Only fuzzing certain parameters

Figure 10-7. XSS Attack loaded as a fuzz source

This file contains more than 362 attack strings to use when looking for security vulnerabilities in web applications. The All_attack file is in the format of attack string :::type of attack. When using the attack files, the description of the attack will need to be stripped out of the attack. Here is an excerpt from the All_attack file:

A:::Meta-Character Injection
TRUE:::Meta-Character Injection
FALSE:::Meta-Character Injection
`id`:::OS Commanding
;id;:::OS Commanding
`dir`:::Directory Indexing
|dir:::Directory Indexing
<script>alert("XSS")</script>:::XSS
<script>alert(document.cookie)</script>:::XSS

After the fuzzing sources have been loaded, each parameter that will be fuzzed will need to have a fuzz source associated with it. For our example, we are fuzzing both the username and passwords fields for XSS attacks, so the XSS_Attacks fuzzing source will be selected as shown in Figure 10-8.

Figure 10-8. Setting the fuzz source for the parameter

To start the fuzzing test, click the Start button near the bottom of the tab. You will notice the Total Requests and Current Request number increase until the test is complete, as shown in Figure 10-9.

After the fuzzer has completed, you will need to review all the requests and see if any of the XSS attacks worked. To do this, go back to the Summary tab and manually inspect the results. You will be looking for "interesting differences" between their responses. Analyzing this data is not an exact science and "interesting differences" can manifest themselves in many different ways. This is where the tedious part of security testing comes into play. The response with the ID of 16 looked interesting. Mainly because of the 500 error it produced. Drilling into the response, as shown in Figure 10-10, we can see that ASP.NET threw an error stating that a dangerous form request was submitted, the behavior we would want in the website, but is considered a leakage of information.

Figure 10-9. Fuzzing in progress

Figure 10-10. WebScarab conversation detail

In the previous example, that particular page of the web application was not susceptible to a cross-site scripting attack. It's important to learn the attack files and what the results of a successful cross-site scripting attack would look like based on each attack in the file.

Using WebScarab is not the only way of testing for cross-site scripting attacks. You may choose to create tests with WatiN or another framework to accomplish the same results that WebScarab produced. The following example only tests one page, with one cross-site scripting attack string, but could be modified to use the attack files previously discussed:

[Test]
public void Should_Check_For_XSS_Attack_Samples()
{
    using (IBrowser ie = BrowserFactory.Create(
       BrowserType.InternetExplorer))
    {
        ie.GoTo("http://localhost:49278/AttackSamples.aspx");
        ie.TextField(Find.ByName(
           "ctl00$ContentPlaceHolder1$lngMain$UserName")).Value = "admin";
        ie.TextField(Find.ByName(
           "ctl00$ContentPlaceHolder1$lngMain$Password")).Value = "admin";
        ie.Button(Find.ByName(
           "ctl00$ContentPlaceHolder1$lngMain$LoginButton")).Click();

        ie.TextField(Find.ByName("txtXSS")).Value = GetXSSAttack();
        ie.Button(Find.ByName("btnXSS")).Click();

        Assert.IsTrue(ie.Title.ToLower() == "xss exploit");
    }
}

private string GetXSSAttack()
{
    return "<script type="text/javascript" +
       "">document.title='XSS Exploit'</script>";
}

10.5.3.2. A2 - Injection Flaws

Injection flaws are vulnerabilities in web applications that allow an attacker to relay malicious code through the target web application to another system/program. The code that is injected through injection flaws can be operating system calls, shell commands, entire scripts that have been written in a scripting language such as Perl, or calls to backend databases through SQL (SQL injections). Some injection flaws can be very easy to discover while others can be extremely obscure.

The most well-known injection flaw is the SQL injection flaw. These are SQL statements that are built by using string concatenation instead of a parameterized query

SQL query created using string concatenation:

string updateQuery = "INSERT INTO Stores (StoreId) VALUES (" + storeId + ")";

SQL query created using a parameterized query:

SQLCommand command = New SQLCommand("INSERT INTO Stores (StoreId)
   VALUES(@storeId");
Command.Parameters.Add("@storeId", storeId);

Many SQL injection attacks are made visible by disclosure of database specific information though error messages similar to the error shown in Figure 10-11.

Figure 10-11. Disclosure of sensitive information

A technique called Blindfolded SQL exposes techniques to inject SQL to a web application that does not disclose database information. Blindfolded SQL requires a great deal of patience and knowledge of SQL.

10.5.3.2.1. Testing for Injection Flaws

For this example we are going to use the AttackSamples.aspx page created for the previous example. This example uses the WroxPizza demo database, and we will be setting a query parameter named "CouponId," to load the selected coupon.

The first task when looking for injection flaws is to see if you can get the page to throw an error. Simple poking around using a manual technique will do for now. If the page throws an error, more than likely you will be able to inject malicious code.

Figure 10-12 shows the error produced by changing the request to the following http://localhost/AttackSamples.aspx?couponId=1 foobar.

Figure 10-12. Error caused by injection

Now that we have the page throwing an error (these yellow ASP.NET errors are the best for attackers because of all the information they provide), it's worth doing more investigation.

The next step typically performed is actually injecting valid SQL, as shown in Figure 10-13. The application appears to work correctly, but the Waitfor delay SQL command delays execution for 10 seconds http://localhost/AttackSamples.aspx?couponId=1 waitfor delay '0:0:10'.

Figure 10-13. Successful SQL injection attack

Knowing that the SQL injection was successful, it may be useful to dig deeper to see exactly what damage can be done using SQL injection. For this a free tool called Pangolin (http://www.nosec.org/en/pangolin.html) will do the trick.

As shown in Figure 10-14, pointing Pangolin to a URL can reveal a great deal of information, such as the name of the database, the server name, a list of other databases on the machine, and much more.

Figure 10-14. Pangolin results

Manual testing is not the only approach that can be used. As you have learned already, using the WebScarab fuzzer you can simulate different situations very quickly. Using the techniques discussed in Chapter 5, you can create methods using frameworks such as WatiN to test for injection flaws:

[Test]
public void Should_Check_For_Injection_Attack()
{
    using (IBrowser ie = BrowserFactory.Create(BrowserType.
       InternetExplorer))
    {
        ie.GoTo("http://192.168.1.9/AttackSamples.aspx");
        ie.TextField(Find.ByName("txtInjection")).Value = "OR 1=1 —";
        ie.Button(Find.ByName("btnInjection")).Click();

        Assert.IsTrue(ie.ContainsText("Server Error in '/' Application."));
    }
}

Keep in mind, if you find one SQL injection flaw it's more than likely there are more throughout the web application.

10.5.3.3. A3 - Malicious File Execution

Malicious file execution is a type of vulnerability where a malicious file is uploaded to the server hosting your web application and executed. Attackers are typically looking for web applications that fail to control the execution of uploaded files. The malicious files that attackers upload could execute remote code, exploit known operation system vulnerabilities, or simply contain a virus intended to wreak havoc on the system.

Web applications that are susceptible to this type of vulnerability break the simplest of security rules, trusting the input that the user has entered. If your web application needs to accept files from users, ensure that you are checking the type of file being uploaded. Checking the file extension is not good enough. Ensure that you are checking the MIME type of the incoming file as well. Along with proper file validation, a good virus scanner on the server and keeping the uploaded files on a separate partition than the web application, are also good practice.

Applications created in frameworks such as .NET and Java are abstracted from the environment in which they execute, so it's less common to see this vulnerability as opposed to applications that do not run in a sandboxed/isolated environment such as PHP.

This is not to say you can't get yourself into trouble by changing the trust level that your web application runs in. Trust levels are associated to security policies that enforce permissions as to exactly what actions the web application can perform within the framework. Actions such as file system, printer access, and sending mail via SMTP are types of actions that can be restricted with the .NET trust levels. The .NET Framework ships with five pre-built trust levels:

  • Full

  • High

  • Medium

  • Low

  • Minimal

It's recommended that applications run in Medium trust. Medium trust only allows for read, write, append, and path discovery on the file system, meaning malicious file execution could not happen.

10.5.3.3.1. Testing for Malicious File Execution

The first thing to think about when testing for malicious file execution exploits, is whether the web application allows the users to upload files, as in Figure 10-15.

Figure 10-15. File Upload Interface

If your web application allows for file upload, then you will need to test to ensure that files cannot be executed. It's helpful to think about these flaws as not only binary files, but scripts as well, such as ASPX files. If the permissions on the directory where the file was uploaded allows for execution as in Figure 10-16, your web application may be vulnerable to this type of attack.

Figure 10-16. Windows Directory Permissions for users

If no validation was performed on the type of file being uploaded, then it would be very easy for an attacker to upload a malicious ASPX file as shown in the following code sample:

<%@ Page Language="C#" AutoEventWireup="true" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <% Response.Write(System.Environment.MachineName); %>
    </form>
</body>
</html>

The attacker would only need to know where in the file system the file existed (in your case /Uploads/Attack.aspx) and they could execute their uploaded code. This sample did not contain malicious code, but you can see the danger in this. Depending on what trust level your application is running in, an attacker could cause a great deal of damage using this type of attack.

Most web applications only allow for file uploading in a few places, and a manual test will be sufficient. This is not to say that an automated test could not be created in WatiN or another framework to test for this type of vulnerability.

10.5.3.4. A4 - Insecure Direct Object Reference

Insecure Direct Object Reference vulnerabilities are caused when the implementation of an internal object is exposed to the public. Internal objects could be files, directories, or database records. The common example that is used to illustrate this vulnerability is a financial institution that uses an account number as the primary key of a table. Because the account number is the primary key, it's tempting to use the account number directly in the interface facing the Web, perhaps as a query string parameter used for pulling up the record. If this method is used, and there is no extra authentication to ensure that the account number is related to the user, then it would be very easy for an attacker to have access to all account numbers at that particular financial institution. This example may sound a little severe but there are documented cases where this has happened.

10.5.3.4.1. Testing for Insecure Direct Object Reference

Testing for Insecure Direct Object references within a web application can be tricky. Even if a developer has a direct object reference, many times developers will not name the parameters to match, for example, a direct reference to the primary key of an accounts table, via a query string. Although some developers will name the query string parameter "AccountId," others will name it something cryptic, so it may not be obvious at first sight and may require some digging to see these flaws. Using a tool such as WebScarab will help you examine each request and easily see the parameters as in Figure 10-17.

Figure 10-17. WebScarab parameters

When you have found pages that you believe to have direct object references that are insecure, you can begin to tamper with the data. An easy tool for this is TamperData, which is a free Firefox plug-in that can be downloaded from http://tamperdata.mozdev.org/. When the TamperData plug-in is enabled, you will be prompted to tamper with the data for each request received in the browser, as shown in Figure 10-18. You are presented with three options: Abort Request simply aborts the request; Submit passes the request along to the browser; and Tamper opens a new window with options to tamper with the data of the request.

Figure 10-18. TamperData request

Figure 10-19 shows the TamperData screen, which allows you to tamper with the parameters and try to find Insecure Object references. Finding these references in many situations will be trial and error.

Figure 10-19. Tampering the couponId parameter

10.5.3.5. A5 - Cross-Site Request Forgery (CSRF)

Cross-site request forgery (CSRF pronounced "sea-surf") is the lesser known cousin of the cross-site scripting attack (XSS). CSRF attacks exploit the trust that a given user/browser has already established with a web application to execute commands/scripts that would normally be unauthorized.

For example, take for instance an online forum that users have the ability to upload images to. If this forum was susceptible to a CSRF attack, the attacker could place something such as this in the image tag:

<img src="http://www.mcwherter.net/logout">

Although not malicious, this example of a CSRF attack could be quite troublesome to users trying to access the forum. A more malicious example could be a bank where your browser has already established a trusted connection:

<img src="http://www.BankOfEngland.Com/Transfer?FromAccount=Ben&ToAccount=
Jeff&amount=1000000 ">

This example would require the attacker to have knowledge about the user. In this case, the attacker Jeff knew that Ben has an account at the Bank of England.

10.5.3.5.1. Testing for Cross-Site Request Forgery

Cross-site request forgery attacks are very similar to cross-site scripting attacks, and the methods discussed previously in this chapter for testing for cross-site scripting attacks apply to cross-site request forgery attacks.

10.5.3.6. A6 - Information Leakage and Improper Error Handling

Developers and managers often dismiss information leakage, because they do not see how an attacker could use this information to attack their web application. The more information that is available about the web application, the more inviting it is to be the target of an attack. Information can be disclosed to attackers in many different ways, but the most common way for leak information is through error messages.

10.5.3.6.1. Error Messages

For a developer, having a detailed error message will make fixing the bug much faster. Many managers are aware of this, and like the ability for developers to resolve issues promptly. Fortunately for the attacker, having a detailed error message will make finding vulnerabilities much easier. Detailed error messages are designed to help developers track down the issue fast. This means a great deal of information is disclosed about the application. The detailed error information includes the version of the .NET Framework and state of the application, and could disclose information about the database. Figure 10-20 shows the default runtime error that is shown.

Figure 10-21 shows a runtime error that has occurred when accessing the web application on the server or if the custom error mode is set to "off" in the web.config.

Figure 10-22 is an example of what error screens should look like. The user is aware something unexpected has happened, but is given the opportunity to inform someone of the issue via email.

Figure 10-20. ASP.NET default error message

Figure 10-21. ASP.NET error message with mode=off

Figure 10-22. What the error message should look like

Best practices states that developers should implement some type of internal logging feature that is not externally visible. When error conditions happen, they can search the internal logs and have exactly the same level of detail to resolve the issue.

10.5.3.6.2. Comments

HTML comments are another place that information can be leaked. Some developers may place versioning history, to-do lists, infrastructure details, and ways to test inside the HTML comments. There are few stories on the Internet about such attacks, because a developer left the login information to an external application documented in the comments.

10.5.3.6.3. Testing for Information Leakage

The best way to test for information leaked by error messages is using a fuzzer to try to cause the web application under test to throw an error.

Remember to try to look for information contained within the HTML. WebScarab contains a tool (fragments) which lists all the comments contained on HTML pages within the WebScarab session. Figure 10-23 is an example of the fragments tool running on the AttackSamples.aspx page. The comments in Figure 10-23 are the comments attackers are looking for.

We have not covered many penetration tools or tools to network or server security. It's worth mentioning in this section that a good port scanner can also help leak information about the different applications that make up the web application runtime stack. There are many port scanners on the market today with many of them free. I like to use nmap, which is a free tool containing a port scanner and other tools helpful for security testing. nmap can be obtained from http://nmap.org/. Figure 10-24 shows a simple port scan of www.mcwherter.net using nmap.

Figure 10-23. Comments of a page in WebScarab

Figure 10-24. nmap port scan

The port scan in Figure 10-24 not only shows which ports are open, it gives a detailed description of the service.

10.5.3.7. A7 - Broken Authentication and Session Management

Believe it or not, there are many web applications that contain sensitive data that are deployed to production with flaws in the underlining authentication. ASP.NET developers have it great. The wonderful developers on both the ASP.NET and the .NET Framework teams have provided ASP.NET developers with a great set of tools within the .NET Framework for authentication. The developers on these teams have spent a great deal of time coding and testing to ensure the authentication tools within ASP.NET are secure. It's because of this attention to detail, and the amount of testing surrounding the built-in tools for authentication, that you should never try to create your own authentication. More than likely, you are going to miss something that will lead to vulnerabilities in your web application. There may be rare situations where the need may arise for custom authentication to be created, but be aware it is a long and tedious task to create authentication that is solid and it's best left to someone who does it every day.

With that being said, this OWASP vulnerability also covers Session Management vulnerabilities. Session Management vulnerabilities can lead to injection attacks. A few tips can help lead to secure session management:

  • Do not allow login to the website from an unencrypted page.

  • Make sure that every page has a logout link.

  • Set a reasonable session timeout (the shorter the better).

  • Do not expose any session identifiers.

  • Limit your code of custom cookies for session management.

10.5.3.7.1. Testing for Broken Authentication

Even if you decide to use the built-in authentication tools provided in the .NET Framework, there are situations you should test for. A good manual test of the underlaying authentication mechanism will do in most situations. The manual test should include the following elements:

  • Non-Existence User. Ensures that error messages returned from authentication mechanism do not disclose the existence of a user.

  • Valid User/Invalid Password Messages. Test to ensure error messages do not disclose which element of the authentication is invalid. Error messages that disclose which authentication element is invalid will help attackers narrow their attacks. Try to stick with generic authentication messages, such as "Invalid username or password entered."

  • Password Strength. Ensure that weak passwords are not accepted.

  • Number of Attempts. Test the number of login attempts users have before a system lockout. System lockouts should be time based. For example, the business rule may be after three invalid authentication attempts, the user will not be able to try to authenticate for 10 minutes. After the 10 minutes has passed, if they enter another invalid password, they will be locked out again.

    It's important not to lock out users of the system entirely. Locking users out of the system entirely after invalid authentication attempts can lead to a DoS attack against the user.

10.5.3.7.2. Testing Session Management

If developers find the need to manage sessions themselves, they need to test to ensure the session is secure. A common mistake that developers handling their own sessions make is creating predictable session IDs. Figure 10-25 is a request captured with WebScarab that shows predictable session IDs.

Figure 10-25. Predictable session ID caught in WebScarab

The following is a list of other authentication sessions, which illustrate how a session can be predicted.

1st Authentication:

User = jmcwherter; Password=foobar12?

Cookie = JCWrlW1102

2nd Authentication:

User = jmcwherter; Password=foobar12

Cookie = JCWrlW1104

3rd Authentication:

User = jmcwherter; Password=foobar12?

Cookie = JCWrlW1106

Guessable Cookie: Cookie = JCWrlW1108

10.5.3.8. A8 - Insecure Cryptographic Storage

Many web applications fail to encrypt sensitive data or do not even try to encrypt any of the data at all. Protecting data using cryptography is essential to creating secure web applications. Sensitive data such as passwords, social security numbers, and any other type of identifiable or sensitive data should be secured using some type of cryptography method. Insecure cryptographic storage of sensitive data can lead to the disclosure of sensitive data and violation of certain compliance standards.

Your best option is to avoid storing sensitive data locally, but if the data needs to be stored, ensure you are using the latest cryptography algorithms, and never try to create your own cryptography algorithms. The algorithms that are standard in the IT industry have been developed by teams and individuals that focus only on creating cryptography algorithms. These algorithms have been tested extensively and have been proven to be secure.

When storing user passwords, a one-way hashing algorithm is the preferred cryptography method. Oneway hash algorithms are easy to compute, but are difficult to revert. Many attackers make use of rainbow tables to try to break the cryptography of hashing algorithms. Another common attack of password hashing algorithms is looking for two different users that have the same exact hashed value for their password. This means that both these users have the same password, and if the password is determined, then the algorithm can be broken.

To help make hashing algorithms more secure, a random value called a salt can be added to the password hash. Both the hash and the salt would be stored. This technique eliminates the duplication of hashed values and therefore rainbow tables cannot be used.

10.5.3.8.1. ViewState

There is one area in ASP.NET where it's common to see developers place sensitive data that is not encrypted. This is ViewState. Have you ever opened the HTML rendered by an HTML page to see hundreds of lines of what look like garbage data in a hidden field named "__VIEWSTATE"? ViewState is one of the ways ASP.NET can maintain state between the different pages of a web application. ViewState is the state of all the controls on the page encoded in the encoding Base64 schema. Developers can place objects into ViewState using the following code:

ViewState["MySecureItem"] = "Jeff's Wife's Name is Carla";

By default, the ViewState of a page is not encrypted, but that's not to say that it can't be by a setting in the Web Config.

10.5.3.8.2. Query Strings

Query strings are another place that developers have a tendency to place data that should be encrypted. I have seen web applications where the primary key of a table is to store user information, which was the social security number of the user. The web page that listed the user information took in a query string of the primary key of the table. Although the name of the query string parameter was not obvious (the developers did not name it SSN), it was fairly obvious that the social security number was used. Not only was sensitive information about that user disclosed, query strings are easily manipulated and other sensitive information may have been exposed as well by manipulating this value.

10.5.3.8.3. Testing for Insecure Cryptographic Storage

Testing for insecure cryptographic storage is another one of the OWASP Top 10 that is difficult to black box test. Having an intimate knowledge of how data is stored will ensure that your web application is not vulnerable to attack.

Using the ViewStateDecoder application, which can be downloaded from http://alt.pluralsight.com/tools.aspx, ViewState is decoded and you can see exactly what was placed in there, as in Figure 10-26, which shows the value of the ViewState item named MySecureItem.

10.5.3.9. A9 - Insecure Communications

Sensitive data that is being transmitted should be encrypted. Usually SSL (Secure Socket Layer) certificates are used to ensure a secure communication between the browser and the server hosting the web application. Depending on the architecture of your web applications, applying SSL certificates to not only the pages exposed by your web applications, but also backend connections is necessary to ensure secure communication across all layers of your web application.

Adding SSL certificates may not always be a trivial task. Planning needs to be involved as to how strong of an encryption level is needed; what happens if someone tries to access a page that requires SSL (are they redirected), and even if an Extended Validation Certificate is required?

Figure 10-26. Unencrypted ViewState decoded

10.5.3.9.1. Testing for Insecure Communications

Web applications that require SSL have some type of process where the user is redirected from HTTP to the HTTPS equivalent. There are many different ways this can be accomplished, through hard-coded links such as https://MY_URL/Login.aspx or possibly via rewriting the URL on the web server. Rewriting URLs is a very popular technique, allowing the user to enter either HTTP or HTTPS, and the user ends up at the correct page that is secure. In IIS 6, third-party plug-ins were often used, whereas in IIS 7 the URL rewrite module http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1691 is an excellent solution. If a rewrite module is used, this pretty much means that if one page works, more than likely all the other pages will work as well.

The following test created with WatiN, will navigate to the login page of a test URL using HTTP. The test will then ensure that the request was redirected to the HTTPS equivalent. This is a type of integration test that could be run on the production server to ensure that the redirect logic is configured correctly. More than likely this type of test would not be run against a development or staging server, only against the production server:

[Test]
public void Should_Check_For_Secure_Communications_On_Login_Page()
{
    string url = "http://MY_URL/login.aspx";        // go to the http page


    using (IBrowser ie = BrowserFactory.Create(BrowserType.InternetExplorer))

{
        ie.GoTo(url);

        // ensure that the redirect to the https page happened
        string expectedURL = ie.Url.Substring(0, 5).ToLower();
        Assert.IsTrue(expectedURL == "https");
    }
}

10.5.3.10. A10 - Failure to Restrict URL Access

The Failure to Restrict URL Access OWASP vulnerability is simply a failure to fully restrict access to resources that should be secured. It's common to see that the only protection to secure pages contained within a web application is the links to these pages which are not visible to an unauthorized user. Attackers or lucky users can find these pages and have access to features that only authorized users should have access to. Security by obscurity is not a valid security practice. Not only should the links be disabled (or not visible at all) to pages that users do not have access to, authorization should also be included to ensure the user has access to view the page.

10.5.3.10.1. Testing for Failure to Restrict URL Access

Using black box testing methods to test for URL access restrictions can be a difficult task. Testers first need to discover which URLs are protected, then test to see if non-privileged users can obtain access. Site maps or logging in with a user that is known to have access to privileged pages is a start.

If you have a list of the pages that are secure, then creating a WatiN script is very simple to ensure they are secure. The following code first ensures that the cache and all the cookies are cleared (meaning the user is logged out), then tries to access pages which are known as secure and tests to see if the user was prompted for the login information:

[Test]
public void Should_Check_For_Proper_Authenicaion_On_Coupons_List()
{
    using (IE ie = new IE())
    {
        ie.ClearCache();
        ie.ClearCookies();
        ie.GoTo("http://localhost:49278/Reports/Coupons.aspx");
        Assert.IsTrue(ie.ContainsText("User Name"));
    }
}

If you wanted to you could test the Coupons page more thoroughly, checking to ensure that the user was in the correct role.

The following code is using a user named UserWithOutPermission to try to access the Coupons page. The user does not have permission to this page, and an information message is presented to the user indicating that they do not have the correct permission:

[Test]
public void Should_Check_For_Proper_Authenicaion_Roles_On_Coupons_List()
{

using (IE ie = new IE())
    {
        ie.ClearCache();
        ie.ClearCookies();
        ie.GoTo("http://localhost:49278/Reports/Coupons.aspx");
        ie.TextField(
           Find.ByName("ctl00$ContentPlaceHolder
           1$lngMain$UserName")).Value ="UserWithOutPermission";
        ie.TextField(Find.ByName(
           "ctl00$ContentPlaceHolder1$lngMain$Password")).Value ="Password";

        Assert.IsTrue(ie.ContainsText
           ("You Do Not Have Permission To Access This Page"));
    }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.163.158