Defending Web Applications
Introduction
• Who am I?– Security assessor for ITSO-SPA– Worked for TSB beginning March, 1999• Technical support of national web applications• Security testing
– Moved to ITSO October, 2012– Am NOT a developer• Wrote the TSB portal and first instances of defect
tracking used by the Judiciary
Overview
Guidance for security controls• Specifying baseline requirements– “Lock a user account for 30 minutes after 10 invalid
authentication attempts in a 30 minute period”
• Specifying “best practices”– Store passwords as a salted hash
• Specifying security principles– Never trust any input that comes from the client
Overview
• Authentication– Login Page– Passwords– Password Storage– Password Reset
• Session Management– Session Management– Session Token– Cookies
• Specific Attacks– Clickjacking– Cross Site Request Forgery
(CSRF)– SQL Injection (SQLi)– Cross-site Scripting (XSS)
• Configuration– SSL – HTTP Response Headers– Miscellaneous
Who are our threats?
• Nation-states• Political activists• Motivated criminals – organized crime• Attackers with no motive against the organization• Script kiddies• Automated attacks – worms, virus, Trojan horse• Disgruntled staff• End users
How do we defend against these varied threats?
Some basic principles
• Do not “roll your own”– Do not create your own encryption algorithms– Do use Web development frameworks when possible– Do use a secure random number generator
• java.security.SecureRandom• System.Security.Cryptography.RNGCryptoServiceProvider
• Never trust any input that comes from the client• Never store secrets in plain text• Don’t be helpful• Employ a mechanism to detect important events• Assume a potential attacker knows• Assume eventual compromise
AUTHENTICATIONDefending Web Applications
Login Page
• System Use notification• Only load login page over HTTPS• Submit over HTTPS• Do not echo password when entered• Do not retain password in cache• Provide consistent, standard error messages
to prevent username enumeration
System Use notification
Load and submit login page over SSL
Do not echo or retain passwords
Login error messages
For example• Invalid account, invalid password– “Invalid username/password”
• Valid account, invalid password– “Password is incorrect”
Passwords
• Complexity Requirements– At least eight characters long– No more than three repeated characters – At least four alphabetic characters– At least one number– Changed every 180 days
Passwords
• Brute Force Protections– Enforce a limit of 10 consecutive invalid access
attempts by a user during a 30-minute time period– Automatically lock the account minimum of 1 hour
when the maximum number of unsuccessful attempts is exceeded
These considerations should be addressed anywhere in the application the user is asked to authenticate
Passwords
• Do not transmit the password in plain text– The URL– Logs– Error messages
• Do not store in plain text– Database– Client-side– Email
Password Storage
• Do store the password as a salted hash• Do use a random number generator to create the salt• Do use a salt that is the same size as the hash output
function• Do use a secure hash, such as SHA256• Do always hash on the server• Do not use a salt more than once• Do use a standard library, such as PBKDF2 or bcrypt,
for Key Stretching
Password Storage – bcryptpublic class BcryptHashingExample { public static void main(String[] args) throws NoSuchAlgorithmException { String originalPassword = "password"; String generatedSecuredPasswordHash = BCrypt.hashpw(originalPassword, BCrypt.gensalt(12)); System.out.println(generatedSecuredPasswordHash); boolean matched = BCrypt.checkpw(originalPassword, generatedSecuredPasswordHash); System.out.println(matched); }} Output: $2a$12$WXItscQ/FDbLKU4mO58jxu3Tx/mueaS8En3M6QOVZIZLaGdWrS.pKtrue
Password Reset
• Do not send the password to the user• Do not disable the user’s account• Do not let the user change the password after
answering security questions• Do email a random, single-use token• Do not send any user account information in the link• Do expire the token
– After a set amount of time– After use– After a successful login
SESSION MANAGEMENTDefending Web Applications
Session Management
• Do use a Web development framework• Do implement an inactivity and absolute
timeout• Do provide a means for the user to logout• Do destroy the session server-side on logout
or after timeout• Do not allow concurrent logins from different
workstations
Session ID
• Generated by the application• Do renew after any privilege level change• Do change the default name to prevent
fingerprinting• Do have a length greater than 20 bytes (160 bits)• Do have sufficient entropy (randomness)• Do not store secret data in the session ID• Do not allow in URLs, logs or error messages• Do treat as any other client-side input
Cookies
• Do set – HTTPOnly– Secure– Path– Domain– Expire
• Do not store sensitive data in cookies
SPECIFIC ATTACKSDefending Web Applications
Clickjacking
• Set HTTP Header (X-Frames-Options)
CSRF
• Include an anti-CSRF token– Unique per user and per session– Tied to a single user session– Large random value– Generated by a cryptographically secure RNG
CSRF
• One way to implement– Generate Token, store server side for the session– Add token as a hidden parameter to a form– When form is submitted, check that the submitted
token matches the token saved server-side
SQL Injection
• Parameterize QueriesThe following is an example of Java code which is vulnerable to SQL injection: String query = "SELECT * FROM users WHERE userid ='"+ userid + "'" + " AND password='" + password + "'";Statement stmt = connection.createStatement();ResultSet rs = stmt.executeQuery(query);
SQL Injection
• Parameterize QueriesHere is the same code properly parameterized: PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE userid=? AND password=?");stmt.setString(1, userid);stmt.setString(2, password);ResultSet rs = stmt.executeQuery();
XSS
On submit• Enforce input field type and lengths• Validate fields• Ensure option selects and radio contain only sent valuesOn render:• Set correct content type• Set safe character set (UTF-8)• Output encode all user data according to context• Set input constraints
File Upload
• Do– Scan with Anti-Virus– Check for expected file extension– Check file content-type– Check file size– Use a new name– Store outside of web root– Deny access to file except through application– Strip away extraneous content
CONFIGURATIONDefending Web Applications
SSL
• Do use secure ciphers suites• Do force HTTPS (all points from login to
logout)• Do use valid SSL certificates• Do not allow mixed mode – All CSS, images, JavaScript, etc. must be served
over SSL
Headers - Remediation
• Unset: Server, X-Powered-By, X-AspNet-Version
• X-Frame-Options• Cache-Control• Content-Type
Headers - Preventative
• X-Content-Type-Options• X-XSS-Protection• Strict-Transport-Security• X-Content-Security-Policy• Character set (UTF-8)
Misc.
• Do not enable directory browsing• Do not allow direct access to objects• Do not allow verbose error messages• Do implement sufficient auditing and logging
Summary
Questions & Answers
References• http://howtodoinjava.com/2013/07/22/how-to-generate-secure-password-hash-md5-sha-pbkdf2-b
crypt-examples/
• https://crackstation.net/hashing-security.htm• http://arr.gr/blog/2012/02/password-hashing-revisited/• https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet• https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet• https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet• https://www.owasp.org/index.php/Secure_Coding_Cheat_Sheet• https://www.owasp.org/index.php/Authentication_Cheat_Sheet• https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet• https://www.owasp.org/index.php/Secure_Coding_Principles• https://
www.owasp.org/index.php/Session_Management_Cheat_Sheet#Session_Management_Implementation
• https://www.owasp.org/index.php/OWASP_Top_Ten_Cheat_Sheet#OWASP_Top_Ten_Cheat_Sheet• http://www.troyhunt.com/2013/05/hack-yourself-first-how-to-go-on.html#PasswordStorage• http://www.troyhunt.com/2012/06/our-password-hashing-has-no-clothes.html