Writing Secure Code

Posted by Brett Hardin on September 24th, 2009

Reading time: 2 – 2 minutes

324177162 8276d0472a Writing Secure Code

Photo: Brajeshwar

If you are a developer, I guarantee that you have written insecure code. Universities train people to write code, but very little time is taken to help them focus on writing secure code.

As with anything, being able to identify security vulnerabilities and writing code securely takes practice. But how does a developer, who is already overburdened with enough work, find the time or resources to help him identify security vulnerabilities?

This is where spotthevuln.com comes in.

The purpose of the project is two fold, help developers write better code by enabling them to identify insecure code and hopefully work the project into teaching curriculum’s at colleges and universities in order to help new developers write more secure code.

Here is how the site works. On Monday at 8:00am PST, a piece of vulnerable code is posted. An business week is given to people in order to attempt to identify the vulnerability in the code. On Friday at 8:00am PST, the code fix is shown with a description of what was wrong with the code. All of the vulnerabilities are taken out of open source projects in order to show developers “real-life” scenarios. The fixes are the fixes that were actually deployed.

The whole point of spotthevuln.com is to help developers identify poor development choices when programming. What are your thoughts? Do you think this will help developers? If you are an instructor and would like to work spotthevuln.com into your curriculum, I suggest for you to reach out to spotthevuln.com.

The more developers know about security, the better off we all are.

Categories: The Basics
Sep2009

Understanding Cookies

Posted by Brett Hardin on September 22nd, 2009

Reading time: 2 – 4 minutes

1117398599 b86f47800a Understanding Cookies

Photo: Mrs. Magic

When testing web applications, penetration testers should look at how the session is handled. Session management is commonly overlooked by developers and system administrators. It is so often overlooked that it is one of the OWASP Top 10, refereed to as “Broken Authentication and Session Management.”

This article will cover certain attributes that cookies typically have. In the future we will address how to use attribute tags to help aid developers in securing their applications. This article assumes the reader has a basic understanding of what a cookie is.

Here is a sample HTTP response. This is what the server responds with after a client request is made. The response has been edited for brevity.

HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: session=YnJldHQ6bXlwYXNzd29yZA==;expires=Thu, 30 Dec 2037 00:00:00 GMT;path=/;domain=.misc-security.com
Content-Length: 8400

For those unfamiliar with cookies, a cookie consists of a name/value pair. In this case the cookie name is “session” and the cookie value is “YnJldHQ6bXlwYXNzd29yZA==

Following the cookie name/value pair are the attribute/value pairs that apply to that cookie and are delimited with a semicolon. In this example their are three attribute/value pairs: expires, path, and domain.

Expires Attribute

expires=Thu, 30 Dec 2037 00:00:00 GMT

The expires attribute is used to tell the browser when the cookie should no longer be used. Browsers will cache this cookie locally until the expires date is reached. When the expires date is reached the browser will stop sending the cookie after the browser is closed. In our example the cookie will remain valid until December 30th, 2037.

Path Attribute

path=/

The Path attribute specifies the subset of URLs to which this cookie applies. In this case, the cookie will be sent for any request to this server. If a user requests /bobsapp/ or /tomsapp/ this cookie will be sent.

Domain Attribute

domain=.misc-security.com

The Domain attribute specifies the domain for which the cookie is valid. An explicitly specified domain must always start with a dot. In our example, this cookie will be sent to misc-security.com and any sub-domains of misc-security.com (e.g. asparagus.misc-security.com).

In a future article we will continue looking at the attribute/value pairs that cookies can have and will even revisit these attributes explaining how each needs to be understood to securely handle a user’s session.

Further Reading:

RFC 2109 – HTTP State Management Mechanism

RFC 2965 – HTTP State Management Mechanism (New Version)

Categories: The Basics
Sep2009

Insecure Cryptographic Storage

Posted by Brett Hardin on September 16th, 2009

Reading time: 3 – 4 minutes

2452639579 e165388718 Insecure Cryptographic Storage

Photo: fpsurgeon

This is the eighth-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What is Insecure Cryptographic Storage

Insecure cryptographic storage occurs when an application doesn’t securely encrypt it’s sensitive data when it is stored into a database. This definition is similar to the picture above, recursive.

Simply stated, insecure cryptographic storage occurs when one of following happens:

  1. The developers don’t encrypt the data that is being stored in the database.
  2. The developers do encrypt the data being stored in the database, but they rely on encryption methods they have developed. (Also known as home-grown cryptography)

After reading these two points you may say, “only an idiot wouldn’t encrypt sensitive data being stored in the database.” I refer you to number two in the list above.

If you think you are smart enough to write your own cryptographic algorithms, you my friend, are the idiot.

The main business concern with not encrypting sensitive data is that it can lead to confidentiality loss. All companies are concerned with unauthorized individuals viewing their sensitive data. In addition, encrypting sensitive data is be a regulatory compliance. (See PCI-DSS requirement 3.)

An Example of Insecure Cryptographic Storage

Here is a simplified example. Selecting the users table from a database we are returned the following:

> select * from users;

id username password
2 brett 5f4dcc3b5aa765d61d8327deb882cf99
2 dan 3c3662bcb661d6de679c636744c66b62

The passwords in these table are 32 characters long. Could these passwords be MD5 hashes?

As with all hashing algorithms, MD5 hashes can’t be reversed. However, they can be pre-computed. Using a hash table lookup we can identify what the password is before it was ran through the MD5 hashing algorithm.

After inserting 5f4dcc3b5aa765d61d8327deb882cf99 into the online form the resulting password is returned. In this example, the password is “password.”

How Do You Prevent Insecure Cryptographic Storage From Occurring

If the data is sensitive and stored it NEEDS to be encrypted. Examples of items that are considered to be sensitive can include:

  • Credit Cards
  • User Names
  • Passwords
  • User data

There are other things to keep in mind when making sure you securely store information. This includes not creating your own cryptographic algorithms. No matter how smart you or your peers think you are DO NOT attempt to invent a new encryption algorithm. Leave this work to the experts.

Ensure that the data stored is not easy to decrypt. This can usually be averted by not using known weak algorithms such as RC3, RC4, MD5 and SHA-1.

If you are using asymmetric key encryption make sure to store your private keys carefully. If an attacker gets hold of the private key, you might as well not encrypt the data in the first place.

Categories: Vulnerabilities
Sep2009

Broken Authentication and Session Management

Posted by Brett Hardin on August 26th, 2009

Reading time: 3 – 4 minutes

4266314914 0ab7cac5c4 Broken Authentication and Session Management

Photo: Rinoninha

This is the seventh-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What is Broken Authentication and Session Management

When developers are programming web application based solutions they rarely focus on how the user’s session is managed. Failing to keep this in mind can lead developers to introduce session management vulnerabilities in their applications.

Session management vulnerabilities occur when developers fail to protect their users sensitive information such as user names, passwords, and session tokens.

Broken authentication vulnerabilities occur when developers fail to use authentication methods that have been adequately tested and rely on their own, often flawed, method for authenticating users.

These vulnerabilities are very hard for developers to identify on their own due to the far-reaching aspect of the code that handles session and authentication.

An Example of Broken Authentication and Session Management

Due to the broad reach of this vulnerability there are many examples of broken authentication and session management occurring. Examples include forgotten password functionality, emailing user credentials, relying on IP address for session, not authenticating a user before changing a password, and not having adequate timeouts for inactive sessions.

Forgotten Password Functionality

Web applications often have a forgotten password functionality that allows a user to submit their user name to the application and are taken to a page with secret questions or a temporary password reset function.

Attackers can exploit this functionality to enumerate valid user name for the application. Developers often forget that a user name is half the puzzle to an attacker. Is an attacker knowing a password damaging if they don’t know a user name to go along with it?

How Do You Prevent Broken Authentication and Session Management

Protecting credentials and session cookies is one of the most difficult tasks for a developer. Protecting this critical pieces of data can touch on many lines of code in several different files.

To prevent these types of vulnerabilities from occurring in your application, developers should first ensure thatSSL is used for all authenticated parts of the application. In addition, verify that all credentials are stored in a hashed form.

As with all prevention methods preventing these vulnerabilities takes careful planning from the design stage of the application. The following should all be considered:

  • Only use the native session management mechanism. Do not write your own session handlers. Do not use home-grown cookies for authentication or session-management.
  • Use a single authentication mechanism. Again, do not write your own authentication mechanism.
  • Do not allow the login process to happen from an unencrypted page.
  • Once a user authenticates, issue them a new session cookie and invalidate the previous session cookie. This will prevent session hijacking attacks from occurring.
  • Verify that every page of the application has a logout link that is easily identified by the user.
  • Have adequate timeouts for inactive sessions. Shorter is better.
  • Verify the user knows their old password before changing their password.
  • Do not send credentials (including the user name) over insecure channels, such as email.
  • Do not expose session identifiers, such as the session token, in the URL.
Categories: Vulnerabilities
Aug2009

Information Leakage and Improper Error Handling

Posted by Brett Hardin on August 12th, 2009

Reading time: 2 – 4 minutes

3058009462 f59cb3ed1a Information Leakage and Improper Error Handling

Photo: bitzcelt

This is the sixth-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What is Information Leakage and Improper Error Handling

Information leakage and improper error handling happen when web applications do not limit the amount of information they return to their users. A classic example of improper error handling is when an application doesn’t sanitize SQL error messages that are returned to the user. Upon receiving a SQL error message an attacker will immediately identify a place for identifying injection flaws.

Although preventing error messages from reaching users will not prevent vulnerabilities from occurring, it does make it difficult for an attacker to accomplish his goal and it is also an industry best practice.

An Example of Information Leakage

Common examples of information leakage include helpful error messages and service banners. Developers and system administrators often forget or disregard how something as simple as a server banner can be used by an attacker.

As an example, if your server is running Apache and you return the server header with your responses, an attacker could leverage this to fingerprint the version of the web server you are running.

Using nmap an attacker could send a few packets at your application server using the command, nmap -sV -p 80 192.168.1.100 and identify the following:

Interesting ports on 192.168.38.132:
PORT    STATE SERVICE  VERSION
80/tcp  open  http     Apache httpd 1.3.37

The attacker has now identified your Apache version and can now search for vulnerabilities affecting that version of Apache.

An Example of Improper Error Handling

Attackers attempt to leverage information that applications freely volunteer. If an application displays an error messages to the user (attacker), there is not guarantee that the user will “ignore” this error message.

Developers typically forget to properly handle their error messages. Stack traces and SQL errors are two examples of very commonly forgotten errors that should be handled.

Attackers love seeing error messages such as:

ERROR:  unterminated quoted string at or near "'''"

How Do You Prevent Information Leakage and Improper Error Handling

When developing applications, developers should assume all of the users are hostile. As a developer having this mentality will greatly aid you in developing secure applications.

All information returned from a web server should be reviewed for potential leakage. This can be automated by a QA team using a fuzzer.

Developers should also use a standard exception handling architecture to prevent information leakage from occurring. This architecture should be used and shared across the entire development team. All developers should handle their errors the same way.

Developers or product managers may also decide to create a default error handler which returns sanitized error messages for most users in production for all error paths. Doing this will greatly reduce the attack surface that can be exploited through error message generation.

Categories: Vulnerabilities
Aug2009

Cross Site Request Forgery (CSRF)

Posted by Brett Hardin on August 5th, 2009

Reading time: 2 – 4 minutes

2689052349 07738f5902 Cross Site Request Forgery (CSRF)

Photo: Joe Penniston

This is the fifth-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What is Cross-Site Request Forgery (CSRF)

Cross-Site request forgery is a client-side vulnerability that allows an attacker to make requests on the user’s behalf. Although, most CSRF exploits require a user to be authenticated to the susceptible site to be successful, this is not always the case.

An Example of Cross-Site Request Forgery

A user (victim) opens their browser and logs on to their online banking application located athttp://bank.com

After checking their balance they browse away from the site (without logging off) and start reading web pages about olives from Madagascar. One of these olive sites is owned by an attacker. The attacker’s website has the following img src tag:

<img src="http://bank.com/transfer.asp?to_acct=445544&amount=1000">

When the victim’s browser loads the malicious page that contains this img src tag, the victims browser makes the transfer request (/transfer.asp?to_acct=445544&amount=1000) to bank.com using the authenticatedcookie from the earlier session. Upon making this request, the bank then transfers $1,000 from the victim’s account to account 445544. The attacker has now successfully executed a cross-site request forgery attack against a user of bank.com

How Do You Prevent Cross-Site Request Forgery

Any sensitive request that is generated by the user should force the user to “re-authenticate.” A simple example is that of change password functionality. You always want to verify the user knows the old password before changing their password, even if they are currently authenticated.

If you determine that “re-authentication” may be an inconvenience for the user or if all of your requests are considered sensitive then the application developers should include a random token that is unique to the user session. This token should not be present in the cookie, but rather as a hidden field in the HTML and then appended to the URL during any form submission.

When the attacker attempts to trick the users browser into making a request, the web application will look for this random token. The random token will not exist for the request, and the request will be denied. This prevents the CSRF attack from being successful.

Note: Having SSL does not protect your application from CSRF vulnerabilities.

Categories: Vulnerabilities
Aug2009

Insecure Direct Object Reference

Posted by Brett Hardin on July 22nd, 2009

Reading time: 2 – 4 minutes

2538415572 b61ff16742 Insecure Direct Object Reference

Photo: tim_norris

This is the fourth-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What is Insecure Direct Object Reference

Insecure Direct Object Reference is when a web application exposes an internal implementation object to the user. Some examples of internal implementation objects are database records, URLs, or files.

An attacker can modify the internal implementation object in an attempt to abuse the access controls on this object. When the attacker does this they may have the ability to access functionality that the developer didn’t intend to expose access to.

Examples of Insecure Direct Object Reference

Insecure direct object reference is a very broad category of vulnerabilities. There are many examples of these types of vulnerabilities found in the wild by other names. Open Redirects and Directory Traversal are two classic examples of an insecure direct object reference vulnerability.

Open Redirect

This is where the web application has a parameter that allows the website to redirect the user somewhere else. If this parameter is not implemented properly using a white list, attackers can use this in a phishing attack to lure potential victims to a site of their choosing. More information about Open Redirects can be found here.

Directory Traversal

Assume a web application allows for a file to be rendered to a user that is stored on the local machine. If the application isn’t verifying what files should be accessed, an attacker can request other files on the file system and those will also be displayed.

For instance, if the attacker notices the URL:

http://misc-security.com/file.jsp?file=report.txt

The attacker could modify the file parameter using a directory traversal attack. He modifies the URL to:

http://misc-security.com/file.jsp?file=../../../etc/shadow

Upon doing this the /etc/shadow file is returned and rendered by file.jsp demonstrating the page is susceptible to a directory traversal attack.

How Do You Prevent Insecure Direct Object Reference From Occurring in Your Application
As always, web application developers can prevent these attacks through good planning.

Developers should use indirect reference maps. Direct mapping can easily be guessed by attackers. Developers should avoid exposing private objects to users. File names, external/internal URL’s, and database keys are all examples of things that should not be displayed to the user.

If direct objects must be used, then the developers should ensure through validation that the user is authorized to view what they are attempting to access. In the directory traversal example, determine what files the user should access and only grant them privileges to those files. This is known as an “accept known good” approach and is always a good idea when it comes to developing secure applications.

Categories: Vulnerabilities
Jul2009

Injection Flaws

Posted by Brett Hardin on July 8th, 2009

Reading time: 3 – 4 minutes

4561376850 6f002abeb9 Injection Flaws

Photo: doug88888

This is the second-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What are Injection FlawsInjection flaws are a class of security vulnerability that allows a user to “break out” of the web application context. If your web application takes user input and inserts that user input into a back-end database, shell command, or operating system call, your application may be susceptible to an injection flaw.

A user exploits this by breaking out of the intended “context” and appends additional and often unintended functionality. By allowing injection flaws in your application you are allowing an attacker to create, read, update, or delete any arbitrary data available to the application.

Examples of Injection Flaws

There are many types of injection flaws. The most common being SQL injection. In addition there is LDAP injection, XML Injection, XPath Injection, OS command injection, and HTML injection. Injection flaws however are not limited to just these. If your web application inserts user input into any interpreter or process, your web application can contain these vulnerabilities. You can see an example of how an injection flaw works here.

How Do You Prevent Injection Flaws

Before calling an external function, verify that the data is what you expect. This is referred to as validation. For instance, if you expect your function to be passed a string that contains a user’s first name, should it contain any special characters? John is a valid name. But, J<o>hn isn’t. Both user names need to be ran through a validation function and in order for the web application to determine whether the data is what the developer expects.

There are certain exceptions however that can get you in trouble. Single Quotes (‘) are valid characters in people’s last names. However, if you allow a single quote in a last name field, you can be introducing SQL injection into your application.

In cases where you need to allow a single quote (‘), in addition to validation, you should also sanitize (encode) the input. Sanitizing the input is determining a way that the input can be transformed into “non-threatening” data. This needs to be done on a case by case basis.

For example, If you understand that the sanitized data will always be returned in a browser, you could simple HTML encode or URL encode the string. A quote becomes, ' (HTML encoding) or %27 (URL encoding).

When sanitizing input, it is important to make sure you decode the string before it is displayed to the user. It can be embarrassing if John O’Brien’s name is printed as: Tim O%27Brien

Categories: Vulnerabilities
Jul2009

Malicious File Execution

Posted by Brett Hardin on July 8th, 2009

Reading time: 2 – 4 minutes

photo unavailable Malicious File Execution

Photo: Ŕooners

This is the third-part in a ten-part-series describing the OWASP Top 10. (See all the OWASP Top 10)

What is Malicious File Execution

Some web applications allow the user to specify input that is used directly into file streams or allows the user to upload files to the server. At a later time the web application accesses the user supplied input in the web applications context. By doing this, the web application is allowing the potential for malicious file execution.

When an application allows user to modify file streams, the application is trusting the user to operate within certain “rules” and may assume the user won’t break these rules.

If there aren’t preventions in place, an attacker can exploit the rules by attempting to include files stored on remote or local file systems.

Web applications that are vulnerable to malicious file execution break the simple security rule of trusting user input.

Allowing malicious file execution to exist in a web application can lead to the complete compromise of the server.

Examples of Malicious File Execution

Typical examples of malicious file execution are remote file includes and local file includes. Most people think of these as PHP functions, however, that does not mean an ASP or JSP server isn’t susceptible to malicious file execution vulnerabilities.

Here is a common example, Imagine the PHP function:

include $_REQUEST['filename'];

An attacker can then specify a file name of a remote URL that they control, say http://evilhacker.com/attack.php

How Do You Prevent Malicious File Execution

Malicious file execution needs to be prevented from the design stage. If the design stage of the web application has already been completed, then extra precaution needs to be taken.

Developers need to pay particular attention to code access security mechanisms to ensure that file names supplied by or influenced by the user do not allow security controls to be obviated.

Web applications should not allow users to insert input into a server-based resource. However, if the ability is needed, then developers need to be extra cautious about what input they accept. Developers should insure that file names supplied by the user do not allow security controls to be bypassed.

General preventions that can be taken include:

  • Strongly Validating user input using an only “accept known good” input.
  • Adding firewall rules that prevent web servers from making new connections to external websites will aid in preventing remote file include vulnerabilities.
  • Implementing a sandbox to isolate applications from one another.

Depending on your environment, specific preventions can also be taken. For instance, with J2EE developers should ensure that the security manager is enabled and properly configured. More information about specific environment preventions can be found at OWASP’s full article on malicious file execution.

Categories: Vulnerabilities
Jul2009

OWASP Top 10 – 2007

Posted by Brett Hardin on July 6th, 2009

Reading time: 2 – 2 minutes

When developing a security strategy for web applications many companies have no idea where to begin. The Open Web Application Security Project (OWASP) understood this problem and developed the OWASP Top 10.

The OWASP top 10 are the top 10 vulnerabilities that are found in web applications. If you have an hour or don’t want to read all of these posts, you can simply watch a video.

If you are a developer, you should understand these vulnerabilities. Understanding them is critical into introducing less vulnerabilities into your code.

The OWASP Top 10:
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

Jul2009