CPS 353: Internet Programming
Sessions and Security
Marcos Elugardo
Gordon College
Last Modified: 11/17/2015
Selected content adapted from material by Marty Stepp, Jessica Miller, and Victoria Kirst © 2012. Used by permission.
 
Agenda
- Check-in
- Sessions
- Web Security
- Homework 7
 
	14.1: Cookie Basics
	
		- 
			14.1: Cookie Basics
		
- 
			14.2: Programming with Cookies
		
- 
			14.3: Sessions
		
 
	Stateful client/server interaction
	
	
		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?
	
	
		- HTTP is a stateless protocol; it simply allows a browser to request a single document from a web server
- today we'll learn about pieces of data called cookies used to work around this problem, which are used as the basis of higher-level sessions between clients and servers
 
	What is a cookie?
	
	
		- cookie: a small amount of information sent by a server to a browser, and then sent back by the browser on future page requests
		
		
- cookies have many uses:
			
			- authentication
- user tracking
- maintaining user preferences, shopping carts, etc.
 
- a cookie's data consists of a single name/value pair, sent in the header of the client's HTTP GET or POST request
 
	How cookies are sent
	
	
		- when the browser requests a page, the server may send back a cookie(s) with it
- if your server has previously sent any cookies to the browser, the browser will send them back on subsequent requests
		- 
			alternate model: client-side JavaScript code can set/get cookies
		
 
	Myths about cookies
	
		- Myths:
			
				- Cookies are like worms/viruses and can erase data from the user's hard disk.
- Cookies are a form of spyware and can steal your personal information.
- Cookies generate popups and spam.
- Cookies are only used for advertising.
 
- Facts:
			
				- Cookies are only data, not program code.
- Cookies cannot erase or read information from the user's computer.
- Cookies are usually anonymous (do not contain personal information).
- Cookies CAN be used to track your viewing habits on a particular site.
 
 
	A "tracking cookie"
	
	
		- 
			an advertising company can put a cookie on your machine when you visit one site, and see it when you visit another site that also uses that advertising company
		
- 
			therefore they can tell that the same person (you) visited both sites
		
- 
			can be thwarted by telling your browser not to accept "third-party cookies"
		
 
	Where are the cookies on my computer?
	
	
		- IE: HomeDirectory\Cookies
			
				- e.g. C:\Documents and Settings\jsmith\Cookies
- each is stored as a .txtfile similar to the site's domain name
 
- Chrome: C:\Users\username\AppData\Local\Google\Chrome\User Data\Default
- Firefox: HomeDirectory\.mozilla\firefox\???.default\cookies.txt
			
				- view cookies in Firefox preferences: Privacy, Remove Individual Cookies...
  
 
 
	How long does a cookie exist?
	
		- session cookie : the default type; a temporary cookie that is stored only in the browser's memory
			
				- when the browser is closed, temporary cookies will be erased
- can not be used for tracking long-term information
- safer, because no programs other than the browser can access them
 
- persistent cookie : one that is stored in a file on the browser's computer
			
				- can track long-term information
- potentially less secure, because users (or programs they run) can open cookie files, see/change the cookie values, etc.
 
 
	14.2: Programming with Cookies
	
		- 
			14.1: Cookie Basics
		
- 
			14.2: Programming with Cookies
		
- 
			14.3: Sessions
		
 
	Cookies in JavaScript
	
document.cookie = "username=smith";   
document.cookie = "password=12345";
document.cookie = "age=29; expires=Thu, 01-Jan-1970 00:00:01 GMT";  
...
	
var allCookies = document.cookie.split(";");    
for (var i = 0; i < allCookies.length; i++) {
	var eachCookie = allCookies[i].split("=");    
	var cookieName = eachCookie[0];               
	var cookieValue = eachCookie[1];              
	...
}
	
		- JS has a global document.cookiefield (a string)
- 
			you can manually set/get cookie data from this field (sep. by ;), and it will be saved in the browser
- 
			to delete a cookie, set it to 'expire' in the past
		
 
	Setting a cookie in asp.net
	
	
Response.Cookies["name"] =  "value";
	
Response.Cookies["UserSettings"]["Font"] = "Arial";
Response.Cookies["UserSettings"]["Color"] = "Blue";
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);
	
		- adding a value to Response.Cookiescauses your script to send a cookie to the user's browser
- Response.Cookiesmust be called before any output statements (HTML blocks,- print, or- echo)
- you can set multiple cookies (20-50) per user, each up to 3-4K bytes
		
			- technically, a cookie is just part of an HTTP header, and it could be set using ASP.Net's Headercollection
				Response.Headers.Add("UserSettings", "Font=Arial");
		
	 
 
	Retrieving information from a cookie
	
var variable = Request.Cookies["name"];   
	
	if (Request.Cookies["UserSettings"] != null)
{
    string userSettings;
    if (Request.Cookies["UserSettings"]["Font"] != null)
    { 
		userSettings = Request.Cookies["UserSettings"]["Font"]; 
	}
}
	
		- any cookies sent by client are stored in Request.Cookies
 
	Deleting a cookie
	
	
	if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}
	
		- You cannot delete a user's cookies
- But you can set them to expire at some point in the past
 
	14.3: Sessions
	
		- 
			14.1: Cookie Basics
		
- 
			14.2: Programming with Cookies
		
- 
			14.3: Sessions
		
 
	What is a session?
	
		- session: an abstract concept to represent a series of HTTP requests and responses between a specific Web browser and server
			
				- HTTP doesn't support the notion of a session, but ASP.net and PHP do
 
- sessions vs. cookies:
			
				- a cookie is data stored on the client
- a session's data is stored on the server (only 1 session per client)
 
- sessions are often built on top of cookies:
			
				- the only data the client stores is a cookie holding a unique session ID
- on each page request, the client sends its session ID cookie, and the server uses this to find and retrieve the client's session data
 
 
	How sessions are established in ASP.NET
	
	
		- client's browser makes an initial request to the server
- server notes client's IP address/browser, stores some local session data, and sends a session ID back to client
- client sends that same session ID back to server on future requests
- server uses session ID to retrieve the data for the client's session later, like a ticket given at a coat-check room
 
	Sessions in ASP.Net: Session_OnStart Event
	
Session_OnStart();
	
		- Session_OnStartsignifies your script wants a session with the user- 
				- If it is implemented in global.asax, it will be called
- Most languages require a session state to start before any content is sent to the user
 
- when Session_OnStartis called:
				- if the server hasn't seen this user before, a new session is created
- otherwise, existing session data is loaded into Sessionobject
- you can store data in Sessionand retrieve it on future pages
 
 
	Accessing session data in ASP.Net
	
Session["name"] = value;        
varvariable = Session["name"];     
if (Session["name"] != null) { } 
	
if (Session["points"] != null ) {
	points = Session["points"];
	
} else {
	Session["points"] = 0;  
}
	
		- the Sessionassociative array reads/stores all session data
 
	Session timeout
	
		- because HTTP is stateless, it is hard for the server to know when a user has finished a session
- ideally, user explicitly logs out, but many users don't
- client deletes session cookies when browser closes
- server automatically cleans up old sessions after a period of time
			
				- old session data consumes resources and may present a security risk
- defaults to 20 mins
- adjustable in time out using Session.Timeout
 
 
	Ending a session
	
Session.Abandon();
	
		- Session.Abandon()ends your current session
 
	Session best practices
	
	- Don't store sensative data in sessions (i.e. login credentials, credit card numbers, etc.)
- Don't store personally identifiable data in sessions (i.e. email, username, etc.)
- Use sessions to store IDs that can be used as lookup keys to retrieve data about objects on the server
	
	  - Avoids direct object mapping
 
- Invoke session management logic (login, authentication, logout) at a single "choke point" in the application
	
	  - Application controller
- Controller callback functions
 
 
	Implementing user logins
	
	
	
		- many sites have the ability to create accounts and log in users
- most apps have a database of user accounts
- when you try to log in, your name/pw are compared to those in the database
 
	"Remember Me" feature
	
	
	
		- How might an app implement a "Remember Me" feature, where the user's login info is remembered and reused when the user comes back later?
- Is this stored as session data?  Why or why not?
- What concerns come up when trying to remember data about the user who has logged in?
 
	15.1: Security Principles
	
		- 
			15.1: Security Principles
		
- 
			15.2: Cross-Site Scripting (XSS)
		
- 
			15.3: Validating Input Data
		
- 
			15.4: SQL Injection
		
- 
			15.5: Session-Based Attacks
		
 
	Our current view of security
	
	
		- Basic assumptions:
			
				- valid user input
- non-malicious users
- nothing will ever go wrong
 
- this is unrealistic!
 
	The real world
	
	
		- in order to write secure code, we must assume:
			
				- invalid input
- evil users
- incompetent users
- everything that can go wrong, will go wrong
- everybody is out to get you
- botnets, hackers, script kiddies, KGB, etc. are out there
 
- assume nothing; trust no one
 
	Attackers' goals
	
	
	
	
		Why would an attacker target my site?
	
	
	
		- Read private data (user names, passwords, credit card numbers, grades, prices)
- Change data (change a student's grades, prices of products, passwords)
- Spoofing (pretending to be someone they are not)
- Damage or shut down the site, so that it cannot be successfully used by others
- Harm the reputation or credibility of the organization running the site
- Spread viruses and other malware
 
	Tools that attackers use
	
	
	
	
		Assume that the attacker knows about web dev and has the same tools you have:
	
	
	
		- 
			
		
- 
			extensions e.g.
			
		
- 
			, e.g.
			
		
- network sniffers, e.g.
			,
			,
			
		
 
	Some kinds of attacks
	
	
	
	
		- Denial of Service (DoS): Making a server unavailable by bombarding it with requests.
- Social Engineering: Tricking a user into willingly compromising the security of a site (e.g. phishing).
- Privilege Escalation: Causing code to run as a "privileged" context (e.g. "root").
- Information Leakage: Allowing an attacker to look at data, files, etc. that he/she should not be allowed to see.
- Man-in-the-Middle: Placing a malicious machine in the network and using it to intercept traffic.
- Session Hijacking: Stealing another user's session cookie to masquerade as that user.
- Cross-Site Scripting (XSS) or HTML Injection: Inserting malicious HTML or JavaScript content into a web page.
- SQL Injection: Inserting malicious SQL query code to reveal or modify sensitive data.
 
	Information leakage
	
	
	
	
		when the attacker can look at data, files, etc. that he/she should not be allowed to see
	
	
	
		- 
			files on web server that should not be there
			
				- or have too generous of permissions (read/write to all)
 
- 
			directories that list their contents (indexing)
			
				- can be disabled on web server
 
- 
			guess the names of files, directories, resources
			
				- see loginfail.aspx, tryloginsuccess.aspx
- see user/?id=123, tryuser/?id=456
- see /data/public, try/data/private
 
 
	15.2: Cross-Site Scripting (XSS)
	
		- 
			15.1: Security Principles
		
- 
			15.2: Cross-Site Scripting (XSS)
		
- 
			15.3: Validating Input Data
		
- 
			15.4: SQL Injection
		
- 
			15.5: Session-Based Attacks
		
 
	Cross-site scripting (XSS)
	
		a flaw where a user is able to inject and execute arbitrary JavaScript code in your page
	
	
insecure.aspx?question=<script type='text/javascript'>alert('pwned');</script>
	
<h1>Your question is: @Request['question']</h1>
	
	
	
		- injected script code can:
			
				- masquerade as the original page and trick the user into entering sensitive data
- steal the user's cookies
- masquerade as the user and submit data on their behalf (submit forms, click buttons, etc.)
- ...
 
- Reflected XSS rendered back to the user clicks on the link containing or activating it
- Stored XSS when bad code is persisted so that other users are vulnerabilt to it
 
	Securing against XSS
	
		- one idea: disallow harmful characters
			
				- XSS is impossible without < >
- can strip those characters from input, or reject the entire request if they are present
 
- another idea: allow them, but escape them
var text = "<p>hi 2 u & me</p>";
text = Server.HTMLEnconde(text);   
		
	
 
	15.3: Validating Input Data
	
		- 
			15.1: Security Principles
		
- 
			15.2: Cross-Site Scripting (XSS)
		
- 
			15.3: Validating Input Data
		
- 
			15.4: SQL Injection
		
- 
			15.5: Session-Based Attacks
		
 
	What is form validation?
	
		- validation: ensuring that form's values are correct
- some types of validation:
			
				- preventing blank values (email address)
- ensuring the type of values
					
						- integer, real number, currency, phone number, Social Security number, postal address, email address, date, credit card number, ...
 
- ensuring the format and range of values (ZIP code must be a 5-digit integer)
- ensuring that values fit together (user types email twice, and the two must match)
 
 
	A real form that uses validation
	
 
	Client vs. server-side validation
	
		Validation can be performed:
	
	
		- client-side (in JavaScript, before the form is submitted)
			
				- can lead to a better user experience, but not secure (why not?)
 
- server-side (in PHP code, after the form is submitted)
			
				- needed for truly secure validation, but slower
 
- by the model (in Rails or within storage engine, after the form is submitted)
			
				- often specific to the backend database being used
 
- all three
			
				- best mix of convenience and security, but requires most effort to program
 
 
	An example form to be validated
	
		
<form action="http://foo.com/foo.aspx" 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>
		
	 
	
		- Let's validate this form's data on the server...
 
	Basic server-side validation code
	
var city  = Request["city"];
var state = Request["state"];
var zip   = Request["zip"];
if ( String.IsNullOrEmpty(city) || String.IsNullOrEmpty(state)  || String.IsNullOrEmpty(zip) || state.Length != 2 || zip.Length != 5) {
	Console.WriteLine( "Error, invalid city/state/zip submitted.");
}
	
		- basic idea: examine parameter values, and if they are bad, show an error message and abort.  But:
			
				- How do you test for integers vs. real numbers vs. strings?
- How do you test for a valid credit card number?
- How do you test that a person's name has a middle initial?
- (How do you test whether a given string matches a particular complex format?)
 
 
	Regular expressions
	
/^[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}$/
	
		- regular expression ("regex"): a description of a pattern of text
			
				- can test whether a string matches the expression's pattern
- can use a regex to search/replace characters in a string
 
- regular expressions are extremely powerful but tough to read
 (the above regular expression matches email addresses)
- regular expressions occur in many places:
			
				- supported by asp.net. PHP, JavaScript, and other languages
- many text editors (TextPad) allow regexes in search/replace
 
 
	Regular expressions in JavaScript
	
		- string.match(regex)- 
				- if string fits the pattern, returns the matching text; else returns null
- can be used as a Boolean truthy/falsey test:
 var name = $("name").value;
 if (name.match(/[a-z]+/)) { ... }
 
- an ican be placed after the regex for a case-insensitive match
				- name.match(/Aardvark/i)will match- "aardvark",- "AaRdVaRk", ...
 
 
	Replacing text with regular expressions
	
		- string.replace(regex, "text")- 
				- replaces the first occurrence of given pattern with the given text
- var str = "Marty Stepp";
 - str.replace(/[a-z]/, "x")returns- "Mxrty Stepp"
- returns the modified string as its result; must be stored
 str = str.replace(/[a-z]/, "x")
 
- a gcan be placed after the regex for a global match (replace all occurrences)
				- str.replace(/[a-z]/g, "x")returns- "Mxxxx Sxxxx"
 
- replace with empty string to use a regex as a filter
			
				- str = str.replace(/[^A-Z]+/g, "")turns- strinto- "MS"
 
 
	15.4: SQL Injection
	
		- 
			15.1: Security Principles
		
- 
			15.2: Cross-Site Scripting (XSS)
		
- 
			15.3: Validating Input Data
		
- 
			15.4: SQL Injection
		
- 
			15.5: Session-Based Attacks
		
 
	SQL injection
	
	
		a flaw where the user is able to inject arbitrary SQL into your query
	
	
		- 
			This flaw often exists when a page accepts user input and inserts it bare into the query.
		
- 
			What kinds of SQL can we inject into the query?  Why is this bad?
		
 
	Too true...
	
	
		- injected SQL can:
			
				- change the query to output others' data (revealing private information)
- insert a query to modify existing data (increase bank account balance)
- delete existing data (; DROP TABLE students; --)
- bloat the query to slow down the server (JOIN a JOIN b JOIN c ...)
 
 
	Securing against SQL injection
	
		- similar to securing against XSS, escape the string before you include it in your query
var username = Request["username"]).Replace("'","\'");
var password = Request["password"]).Replace("'","\'");
var query = "SELECT name, ssn, dob FROM users
WHERE username = $username AND password = $password";
	
		- replaces 'with\', etc., and surrounds with quotes
 
	Parameterized Queries
	
		- An even better approach...
 fred_users = Users.where( u => u.Name == Request["Name"] );
- Yields the following SQL query
 selct * from users where Name = 'Fred'
			- Passes Request["Name"]as a parameter
- Has additional advantages
		
			- Avoides annoying database-specific quoting issues
			
				- In Oracle:
				
					- 'Aardvark's' gets escaped to 'Aarkdvark''s'
- 'Moe > Larry' gets escaped to 'Moe '||'>'||' Larry'
 
 
- More efficient: database may compile the query one time and then call it with different values for bind variables (like a function)
 
 
	Injection attacks are not limited to SQL
	
 
	15.5: Session-Based Attacks
	
		- 
			15.1: Security Principles
		
- 
			15.2: Cross-Site Scripting (XSS)
		
- 
			15.3: Validating Input Data
		
- 
			15.4: SQL Injection
		
- 
			15.5: Session-Based Attacks
		
 
	Man-in-the-middle attack
	
	
	
	
		when the attacker listens on your network and reads and/or modifies your data
	
	
	
		- 
			works if attacker can access and compromise any server/router between you and your server
		
- 
			also works if you are on the same local area or wifi network as the attacker
		
- 
			often, the attacker still sends your info back and forth to/from the real server, but he silently logs or modifies some of it along the way to his own benefit
		
- 
			e.g. listens for you to send your user name / password / credit card number / ...
		
 
	Secure HTTP (HTTPS)
	
	
	
	
		- 
			: encrypted version of HTTP protocol
		
- 
		all messages between client and server are encrypted so men in the middle cannot easily read them
		
			- Client encrypts messages using the server's public key
- Server decrypts client's messages using its private key
 
- 
			servers can have certificates that verify their identity
		
 
	Session hijacking
	
	
	
	
		when the attacker gets a hold of your session ID and masquerades as you
	
	
	
		- 
			exploit sites that use HTTPS for only the initial login:
			
			
				- HTTPS: browser → server (POST login.aspx)
- HTTPS: browser ← server (login.aspx + Session cookie)
- HTTP: browser → server (GET whatever.aspx + Session cookie)
- HTTP: browser ← server (whatever.aspx + Session cookie)
 
- attacker can listen to the network, get your session ID cookie, and make requests to the same server with that same session ID cookie to masquerade as you!
- example: 
 
	Cross-Site Request Forgery (CSRF)
	
	 when the attacker tricks you into submitting a malicious request on their behalf 
	
		- Based on user's identity or authenticated state
- Performs undesired actions on the victim's behalf (i.e. make purchase, transfer money, etc.)
- Can occur when a user loads a page with an embedded CSRF attack - i.e. forum, blog post, email
- Example
		
		
 
	Defending against CSRF attacks
	
		- Limit the number and scope of single-request actions available to users
- Require additional authentication from users prior to allowing sensitive requests
- Anti-CSRF Token - require that a unique and expected token is included and verified with sensitive requests
		
		
 
	OWASP Top 10
	OWASP (Open Web Application Security Project) provides tools and information to make software more secure.
	
		- Injection
- Broken Authentication and Session Management
- Cross-Site Scripting (XSS)
- Insecure Direct Object References
- Security Misconfiguration
- Sensitive Data Exposure
- Missing Function Level Access Control
- Cross-Site Request Forgery (CSRF)
- Using Components with Known Vulnerabilities
-  Unvalidated Redirects and Forwards
 
	Secure Development Best Practices
	
		- Keep security in mind from the start of and throughout the development process
- Break your own code because the bad guys will if you don't
- Defense in-depth
		
			- Engineer multiple levels of security
- If an attacker gets by one level, they may be thwarted by a subsequent level
- Example
			  
				  - Secure encrypted communication via SSL/HTTPS
- Role based user authentication
- Strict input validation (to defend against XSS, SQL ingjection, CSRF, etc.)
- Backend data validation (in case data within internal storage systems is compromised)
- Sensitive data stored with strong encryption (i.e AES with at least 256 bit key)
 
 
- Use two-factor authentication -- User needs multiple pieces of data to access a restricted resoruc
		
			- Something you know (i.e. passcode)
- Something you have (i.e. cell phone with authentication token)
- Something you are (i.e. fingerprint, retina scan)
 
 
	Secure software development from a Christian perspective
	
		- Defending the weak
- Fighting against evil
- An ongoing mission
			- Success in secure software development is measured by what does not happen
 
	
Homework 7