CPS 353: Internet Programming

Sessions and Security

Simon Miner

Gordon College

Last Modified: 11/13/2013

Selected content adapted from material by Marty Stepp, Jessica Miller, and Victoria Kirst © 2012. Used by permission.

Agenda

Check-in

14.1: Cookie Basics

Stateful client/server interaction

amazon cookie

Sites like amazon.com seem to "know who I am." How do they do this? How does a client uniquely identify itself to a server, and how does the server provide specific content to each client?

What is a cookie?

om nom nom

How cookies are sent

cookie exchange

Myths about cookies

A "tracking cookie"

tracking cookie figure

Where are the cookies on my computer?

good enough for me

How long does a cookie exist?

14.2: Programming with Cookies

Cookies in JavaScript

document.cookie = "username=smith";   // setting two cookies
document.cookie = "password=12345";
document.cookie = "age=29; expires=Thu, 01-Jan-1970 00:00:01 GMT";  // deleting a cookie
...
// (later)
var allCookies = document.cookie.split(";");    // ["username=smith", "password=12345"]
for (var i = 0; i < allCookies.length; i++) {
	var eachCookie = allCookies[i].split("=");    // ["username", "smith"]
	var cookieName = eachCookie[0];               // "username"
	var cookieValue = eachCookie[1];              // "smith"
	...
}

Setting a cookie in PHP

setcookie("name", "value");
setcookie("username", "martay");
setcookie("favoritecolor", "blue");
  • technically, a cookie is just part of an HTTP header, and it could be set using PHP's header function (but this is less convenient, so you would not want to do this):
  • header("Set-Cookie: username=martay; path=/; secure");
    

Retrieving information from a cookie

$variable = $_COOKIE["name"];   # retrieve value of the cookie
if (isset($_COOKIE["username"])) {
	$username = $_COOKIE["username"];
	print("Welcome back, $username.\n");
} else {
	print("Never heard of you.\n");
}
print("All cookies received:\n");
print_r($_COOKIE);
  • unset function deletes a cookie

Setting a persistent cookie in PHP

setcookie("name", "value", timeout);
$expireTime = time() + 60*60*24*7;   # 1 week from now
setcookie("CouponNumber", "389752", $expireTime);
setcookie("CouponValue", "100.00", $expireTime);

Removing a persistent cookie

setcookie("name", "", time() - 1);
setcookie("CouponNumber", "", time() - 1);

Cookies in Rails

# Set a simple session cookie.
cookies[:user_name] = "aardvark" 

# Set a cookie that expires in 1 hour.
cookies[:login] = { :value => "XJ12", :expires => 1.hour.from_now }

# Get cookie informaion.
cookies[:user_name]  # => "david"
cookies.size         # => 2 

# Delete cookies.
cookies.delete :user_name

14.3: Sessions

What is a session?

How sessions are established in PHP

session

Sessions in PHP: session_start

session_start();

Accessing session data in PHP

$_SESSION["name"] = value;        # store session data
$variable = $_SESSION["name"];     # read session data
if (isset($_SESSION["name"])) {  # check for session data
if (isset($_SESSION["points"])) {
	$points = $_SESSION["points"];
	print("You've earned $points points.\n");
} else {
	$_SESSION["points"] = 0;  # default
}

Where is PHP session data stored?

session cookie

Session timeout

Browsers that don't support cookies

session_start();   # same as usual

# Generate a URL to link to one of our site's pages
# (you probably won't ever need to do this)
$orderUrl = "/order.php?PHPSESSID=" . session_id();

Ending a session

session_destroy();

Rails Sessions

Rails Sessions (Continued)

Storing data in a session...

class LoginsController < ApplicationController
  # "Create" a login, aka "log the user in"
  def create
    if user = User.authenticate(params[:username], params[:password])
      # Get brand new session data for this newly logged in user
      reset_session
      # Save the user ID in the session so it can be used in
      # subsequent requests
      session[:current_user_id] = user.id
      redirect_to root_url
    end
  end
end

Deleting data from a session...

class LoginsController < ApplicationController
  # "Delete" a login, aka "log the user out"
  def destroy
    # Remove the user id from the session
    @_current_user = session[:current_user_id] = nil
    redirect_to root_url
  end
end

Session best practices

Implementing user logins

user login

See chapter 14 of the Agile Web Development with Rails 4 text for a good example of developing a simple login function

"Remember Me" feature

user login

15.1: Security Principles

Our current view of security

group hug

The real world

orcs (dorks?)

Attackers' goals

burglar

Why would an attacker target my site?

Tools that attackers use

firebug

Assume that the attacker knows about web dev and has the same tools you have:

Some kinds of attacks

burglar

Information leakage

information leakage

when the attacker can look at data, files, etc. that he/she should not be allowed to see

15.2: Cross-Site Scripting (XSS)

Cross-site scripting (XSS)

a flaw where a user is able to inject and execute arbitrary JavaScript code in your page

insecure.php?question=<script type='text/javascript'>alert('pwned');</script>
<h1>Your question is: <?php $_GET['question'] ?></h1>
clippy

Securing against XSS

15.3: Validating Input Data

What is form validation?

validates :voting_age, numericality: { greater_than_or_equal_to: 18 }
	

A real form that uses validation

wamu

Client vs. server-side validation

Validation can be performed:

An example form to be validated

<form action="http://foo.com/foo.php" method="get">
	<div>
		City:  <input name="city" /> <br />
		State: <input name="state" size="2" maxlength="2" /> <br />
		ZIP:   <input name="zip" size="5" maxlength="5" /> <br />
		<input type="submit" />
	</div>
</form>

Basic server-side validation code

$city  = $_REQUEST["city"];
$state = $_REQUEST["state"];
$zip   = $_REQUEST["zip"];
if (!$city || strlen($state) != 2 || strlen($zip) != 5) {
	print "Error, invalid city/state/zip submitted.";
}

Regular expressions

/^[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}$/

Regular expressions in PHP (PDF)

function description
preg_match(regex, string) returns TRUE if string matches regex
preg_replace(regex, replacement, string) returns a new string with all substrings that match regex replaced by replacement
preg_split(regex, string) returns an array of strings from given string broken apart using given regex as delimiter (like explode but more powerful)

PHP form validation w/ regexes

$state = $_REQUEST["state"];
if (!preg_match("/^[A-Z]{2}$/", $state)) {
	print "Error, invalid state submitted.";
}

Basic regular expressions

/abc/

Wildcards: .

Special characters: |, (), \

Quantifiers: *, +, ?

More quantifiers: {min,max}

Anchors: ^ and $

Character sets: []

Character ranges: [start-end]

Escape sequences

Regular expression PHP example

# replace vowels with stars
$str = "the quick    brown        fox";

$str = preg_replace("/[aeiou]/", "*", $str);
                         # "th* q**ck    br*wn        f*x"

# break apart into words
$words = preg_split("/[ ]+/", $str);
                         # ("th*", "q**ck", "br*wn", "f*x")

# capitalize words that had 2+ consecutive vowels
for ($i = 0; $i < count($words); $i++) {
	if (preg_match("/\\*{2,}/", $words[$i])) {
		$words[$i] = strtoupper($words[$i]);
	}
}                        # ("th*", "Q**CK", "br*wn", "f*x")

Regular expressions in JavaScript

Replacing text with regular expressions

Regular expressions in Ruby and Rails

15.4: SQL Injection

SQL injection

grades

a flaw where the user is able to inject arbitrary SQL into your query

A SQL injection attack

Too true...

bobby tables xkcd comic

Securing against SQL injection

quote returns a SQL-escaped version of a string
$username = $db->quote($_POST["username"]);
$password = $db->quote($_POST["password"]);
$query = "SELECT name, ssn, dob FROM users
WHERE username = $username AND password = $password";

Parameterized Queries

Injection attacks are not limited to SQL

15.5: Session-Based Attacks

Man-in-the-middle attack

man in the middle

when the attacker listens on your network and reads and/or modifies your data

Secure HTTP (HTTPS)

insecure communications
https

Session hijacking

firesheep

when the attacker gets a hold of your session ID and masquerades as you

Cross-Site Request Forgery (CSRF)

CSRF-ish

when the attacker tricks you into submitting a malicious request on their behalf

Defending against CSRF attacks

OWASP Top 10

OWASP (Open Web Application Security Project) provides tools and information to make software more secure.

  1. Injection
  2. Broken Authentication and Session Management
  3. Cross-Site Scripting (XSS)
  4. Insecure Direct Object References
  5. Security Misconfiguration
  6. Sensitive Data Exposure
  7. Missing Function Level Access Control
  8. Cross-Site Request Forgery (CSRF)
  9. Using Components with Known Vulnerabilities
  10. Unvalidated Redirects and Forwards

Secure Development Best Practices

Secure software development from a Christian perspective

Homework 7