csc 2720 building web applications web application security

31
CSC 2720 Building Web Applications Web Application Security

Upload: susanna-mills

Post on 26-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

CSC 2720Building Web Applications

Web Application Security

Objectives Prevent your application from failing Prevent your application from being hacked Protect sensitive data

Protect yourself Protect the users

1. Securing Your Application

Outline

1. Input validation

2. Handling File Upload

3. Protection of Sensitive Data

4. Authentication

5. Session Management

6. Exception Management

7. Dealing with Denial of Services

1.1. Securing Your Application

Input validation

Data in a HTTP request cannot be trusted. Attackers can easily tamper with any parts of a HTTP

request (URL, query string, headers, cookies, form fields, hidden fields, etc.)

Client-side validation cannot guarantee anything. Why should we still need client-side validation?

You should always validate every input value.

Dangers of using Non-validated Input Using non-validated input in the HTML output stream

Corrupted display, Cross-site scripting attack

Using non-validated input in SQL queries SQL injection

Using non-validated input as filenames Canonicalization Attacks A canonicalization attack occurs when someone enters a filename

requesting a file they aren’t allowed to have or overwrites a file they shouldn’t.

Not checking or limiting the size of the input values Buffer Overflow

Cross-Side Scripting (XSS) Flaw XSS vulnerabilities occur when an attacker uses a web

application to send malicious code, generally in the form of a script, to a different end user.

Can occur to web applications that use input from a user (without validation) in the output the application generates (e.g.: Forums, Blogs)

Other users may not aware of the risk because the script comes from a trusted website.

Script can access cookies, session ID, modify content

If input text is to be treated as plain text, always encode the special characters in the text before using them in the output. e.g., Replace < by &lt;

Replace > by &gt;

Replace & by &amp;

If you allows certain HTML elements in the input text, derive an XML schema that defines what tags and attributes are allowed and use an XML validating function to validate the input text.

If you need to support certain markups in the input text (e.g., text formatting, list, and table), consider using different markup styles. e.g., Use "[…]" instead of "<…>", and replace '<', '>', '&' in the input.

XSS Flaw (Prevention)

// SQL Injection example// Bad SQL query for authenticating user// This query is suppose to return one row of data if both username// and password match. $query = "SELECT Username FROM Users WHERE " . "Username='$username' AND Password='$password'";

$result = @mysqli_query($dbc, $query);$loginSuccess = $result && @mysqli_num_rows($result) == 1;

However, if a user provides the Username and Password asLogin: ' OR ''='Password: ' OR ''='

The value of $query would becomeSELECT Username FROM Users WHEREUsername='' OR ''='' AND Password='' OR ''=''

which always return the 1st row of data in the Users table.

Encode special characters such as ' and " in the input value before using the value in an SQL query In PHP, use mysqli_real_escape_string()

Alternatively, use prepared SQL statements

In php.ini, set "magic_quotes_gpc = off" If set to "on", then single quotes, double quotes, backslashes and n

ull characters in the POST, GET, and Cookie data are automatically prepended with a backslash.

Default is "On" in PHP 5 but removed from PHP 6. You should not depend on this setting

For more info about SQL injection, see PHP Manual: Database Security: SQL Injection

SQL Injection Flaw (Prevention)

Guidelines for Input Validation Validate all input values

When filtering input values, think "what values to accept?" instead of "what values to reject?".

Encode input values (if necessary) before using them e.g., in HTML output, SQL query string, filename

Keep all validation schemes or functions in one place (easier to maintain)

Use a "clean" set of variables to keep validated/clean input and write your code to access the input values from the clean variables.

Guidelines for Input Validation – What to check?

Each parameter should be checked against a strict format that specifies exactly what input is allowed: Data type (string, integer, real, etc…) Allowed character set Minimum and maximum length Whether null is allowed Whether the parameter is required or optional Whether duplicates are allowed Numeric range Specific legal values (enumeration) Specific patterns (regular expressions)

Useful PHP Functions string urlencode (string $str )

Convert all non-alphanumeric characters so that they can be represented correctly in the URL.

string htmlspecialchars (string $str ) Convert <, >, ", ', and & to HTML entities

string htmlspecialchars_decode (string $str ) Opposite of htmlspecialchars()

string htmlentities (string $str ) Similar to htmlspecialchars() except that this

function also converts all characters that have equivalent HTML entities to HTML entities

Useful PHP Functions

string html_entity_decode (string $str)

Opposite of htmlentities()

string strip_tags ( string $str, [string $allowable_tags ]) This function tries to return a string with all HTML and

PHP tags stripped from a given $str. e.g.:

// Allow <p> and <a>$stripped_text = strip_tags($text, '<p><a>');

Note: Most of these functions have additional parameters. Please refer to the PHP online manual for more info about each function.

Using Regular Expressions Regular Expressions (Perl-Compatible)

http://www.php.net/manual/en/book.pcre.php

Regular Expression (POSIX Extended) http://www.php.net/manual/en/book.regex.php

Useful for validating input and removing unwanted characters from a string.

e.g., Remove all non-alphanumeric characters in $str

$new_str =

ereg_replace("[^A-Za-z0-9]", "", $str);

1.2. Securing Your Application

Handling File Upload Validate file name if you want to retain the file

name. Otherwise rename the file (and store original filename somewhere else) Check for possible use of "../" for path traversal

Don't store uploaded files in folders that is directly accessible from the web Files can be executable Files may contain copyrighted materials

Check for file size and available disk space

1.3. Securing Your Application

Protection of Sensitive Data e.g. of sensitive data: passwords, credit card data

Use POST (instead of GET) method to transmit data

Don't keep sensitive data in cookies

Store passwords in hashed or encrypted forms e.g., use SHA1() or MD5() functions

Avoid storing credit card data

Use HTTPS to transfer sensitive data

HTTPS HTTP over Secure Socket Layer (SSL)

Use "https:" in the URL to indicate that HTTPS is to be used The web server need to be setup to accept HTTPS

HTTPS encrypts the data in the header and the body of a HTTP request. Data encoded in the URL are not encrypted i.e., HTTPS does not encrypt data sent via GET method

Can ensures reasonable protection from eavesdroppers and man-in-the-middle attacks

1.4. Securing Your Application

Authentication Enforce strong password strength

To prevent password guessing After some numbers of unsuccessful login attempts, delay or block t

he future login attempts from the same user

Use more than just a session ID to check if a user has already logged in e.g., check also the value of the "User-Agent" field in the HTTP hea

der

When a user wants to change password, ask the user for new and old passwords

Cache controls Request the web client not to cache form data so that no one can

use the browser "Back" button to resubmit login data

1.5. Securing Your Application

Session Management Don't keep session ID in URL

Limit the lifespan of the cookie that holds the session ID

If the host serves multiple users Make sure the "path" of the cookie is set in such a way

that the web client will only return the cookie to the scripts in your application folder

Make sure the files that keep session data are not accessible by other users on the same host

When a user of your web application logouts, make sure all session related data are deleted.

1.6. Securing Your Application

Exception Management

Don't showing detailed error messages to the users The less a hacker knows about how your application

works the better.

Log all errors and their details

1.7. Securing Your Application

Denial of Services (What is it?) In addition to network DoS, an attacker can also flood your

web application with computer generated HTTP requests.

A web application can't easily tell the difference between an attack and ordinary traffic. IP address can be easily faked

If a web server is flooded with requests, resources such as bandwidth, DB connection, disk storage, CPU, memory, threads may dry out.

An attacker can also deny services for a user by sending invalid credentials until the system locks out the account of the user.

Securing Your Application –

Dealing with Denial of Services

Use firewall

Limit the resources allocated to any use to a bare minimum (introduce quotas) Keep minimal amount of data in session object In certain programming language, you can limit one

request per user at a time by synchronizing on the user's session.

Avoid granting unnecessary access to databases or other costly resources to unauthorized user For example, costly operations are only granted to

registered users who have logged in

2. Securing Your Host (Servers)

Have a through understanding of the servers' configuration

Don't rely on default values

Disable directory listing and directory traversal through symbolic links

Disable unnecessary modules and services e.g., remote administration

2. Securing Your Host (Servers)

Don't run servers in privileged accounts (e.g., admin) Don't run web application as root or Adminstrator Don't access a database as DBADMIN

Log all activities

Use security scanning tools to check for possible vulnerabilities Perform both internal and external scanning

2. Securing Your Host (Servers)

Patch security flaws in the server software as often as possible

Check if any configuration settings is modified after applying a patch or upgrade

Do the files and directories have the right permission? If your application stores sensitive data in files, can othe

r users on the same host read the files?

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

Summary Never trust the input – Validate, validate, validate!

Be careful with where and how you store sensitive data

Know your applications, servers, and systems well

If something is not needed, turn it off (reduce the chance of introducing security vulnerabilities)

Keep yourself updated with the security info.

Useful Tools and References Useful Tools

Nessus Open Source Vulnerability Scanner (http://www.nessus.org)

Nikto – Open Source Web Server Scanner (http://www.cirt.net/code/nikto.shtml)

References OWASP Top Ten Most Critical Web Application Security

Vulnerabilities (http://www.owasp.org/documentation/topten.html)

http://advosys.ca/papers/web-security.html

References Web Application Vulnerability Scanners

http://samate.nist.gov/index.php/Web_Application_Vulnerability_Scanners.html

Chapter 1- Web Application Security Fundamentals http://msdn.microsoft.com/en-us/library/aa302417.aspx

Web Application Security http://www.phpwact.org/security/web_application_security

Cheat Sheet: Web Application Security Frame http://msdn.microsoft.com/en-us/library/ms978518.aspx

Self-test Questions How should you implement a secure

login/authentication mechanism?

How should you prevent XSS? e.g., a message board in which any one can leave a

message that may contain hyperlinks and images.

Why you should run the web servers on a separate low-privilege user account?

How to keep page specific data safely in the URL?

Self-test Questions How to combat password guessing attack

How to prevent session hijacking

How to handle transmission and storing of Credit Card #

How and where you should store passwords?