cfml sessions for dummies

61
CFML Sessions for Dummies Eric Peterson

Upload: coldfusionconference

Post on 22-Jan-2018

303 views

Category:

Technology


0 download

TRANSCRIPT

CFML Sessions for DummiesEric Peterson

What this talk isn't!

· Live coding· Outlining best practices

· For people who use sessions and either already know or don't care that much how they work

What this talk is!

· Theory — definitions and examples· Understanding the what and the why rather

than the when would I use this· For people who use sessions and don't know

how they work

Other Sessions Right Now

· PostCSS: A Dumb Name For An Awesome ThingRoom 238

· SQL Server Tips For Everyday ProgrammersRoom 334

· Crash Course In Ionic & AngularJSAuditorium

Who am I?Eric Peterson! Utah

" O.C. Tanner

# 1 wife, 1 kid

What is a session?

Disclaimer:Out of the box setup

(Other setups later)

What is a session?· Data stored in memory on the server

· Client variables used to access the data on the server

Data stored in memory on the server

Data stored in memory on the server· Data is lost when not accessed within a time-out

period· Data is available only to a single client and

application· Any CFML data type can be stored

Data stored in memory on the serverData is accessed by using a combination of a CFID

and a CFTOKEN· CFID: A sequential client identifier

· CFTOKEN: A random client security token

What do you get in the session scope by default?

And any data you add yourself!session.simpleValue = 5;

session.complexValue = [ { id = 1, permissions = [/* ... */] }];

session.user = new User(/* ... */);

Other Facts

· CFID and CFTOKEN are reused by the client when starting new sessions (if possible)

· Someone with your CFID and CFTOKEN could access your session

· For this, reason it's bad to pass it in the query string. Use Client Variables instead

Client variables used to access the data on the

server

Client Variables = Cookies

Default Cookies stored when using Sessions

Client variables used to access the data on the serverIf you didn't use cookies, you'd have to pass

these values in the url or form every time

Which makes them very easy to steal and hijack a session

So don't do that!!

Enabling Sessions in your CFML Applications

Enabling Sessions in your CFML Applicationscomponent { // Required this.name = 'MyAwesomeApp'; this.sessionManagement = true;

// Optional: default timeout is 20 minutes this.sessionTimeout = createTimeSpan(0, 0, 45, 0);}

Session Lifecycle

What starts a session?

A user coming to your website

During a Session

Reading and Writing to the Session// write values to the sessionsession.favorites = [1, 45, 67, 109];

// read values from the sessionlocal.favorites = session.favorites;

// though, it is smart to check that// the value exists first.if (structKeyExists(session, 'favorites')) { local.favorites = session.favorites;} else { local.favorites = [];}

Session Locks

Session Locksfunction getProductCount() { lock scope="session" type="read" timeout="2" throwontimeout="true" { return session.items; }}

function incrementProductCount(count) { lock scope="session" type="exclusive" timeout="2" throwontimeout="true" { session.items += count; }}

When do you use session locks?Race Conditions

SessionRotate()Available in ACF10+ and Lucee 4.5+

1. Invalidates the current session2. Creates a new session

3. Migrates the data from the old to the new4. Overwrites the old cookies with the new

"Best Practices"· Keep your session scope small

· Only store lookup values in your session scope (like userId)

· Especially avoid storing values shared between users in the session scope

· SessionRotate() a!er a successful login11 See Learn CF in a Week for more session security tips

Ending a Session

What does not end a session?· Logging out

· Closing the browser· structClear(session)

What does end a session?· Session Timeout

· sessionInvalidate()(ACF10+ and Lucee 4.5+)

Session Lifecycle Methodsfunction onSessionStart() { // set defaults for session values // you want to make sure are available session.sessionStartedAt = Now();}

function onSessionEnd(applicationScope, sessionScope) { if (sessionScope.isShopping) { // clean up any long standing objects // Log any important messages applicationScope.shoppingInsightLogger.info( 'User timed out while shopping at #Now()#' ); }}

J2EE Sessions

J2EE Sessions· Uses the servlet (e.g. Tomcat) for session

management· Share session information between ColdFusion

and other servlet applications

J2EE Sessions· Does not reuse the session identifiers

· Generates a new identifier for each session, reducing the impact of the the! of the token

· Can terminate the session manuallygetPageContext().getSession().invalidate();

ColdFusion Sessions vs. J2EE Sessions

Which should you use?

Storing your session data elsewhere

(Not in memory on the server)

First off,Why?

Server Clusters

Server ClustersIf your session information is being stored in the

memory of a server,then only that one server can handle all your

requests.In other words, you can't scale.

What are our options?· Don't use the session scope

!

· Store the session scope somewhere else"

The Hard Way:

Manual Session Management

Do it yourself !function onRequestStart() { var urlToken = 'CFID=' & cookie.cfid & '&CFTOKEN=' & cookie.cftoken; var sessionClient = new cfcouchbase.CouchbaseClient({ bucketName = 'sessions' }); StructAppend( session, sessionClient.get(id = urlToken, deserialize = true), true );}

function onRequestEnd() { var urlToken = 'CFID=' & cookie.cfid & '&CFTOKEN=' & cookie.cftoken; var sessionClient = new cfcouchbase.CouchbaseClient({ bucketName = 'sessions' }); sessionClient.set(id = urlToken, session );}

One Easy Way:

Session Storages(Requires ColdFusion 2016+ or Lucee 4.5+)

Done

Another Easy Way:J2EE Sessions

Sticky sessions at the servlet level

Done

Extras

First, Session FixationAn attacker provides the session identifiers in

order to try and know them<a href="http://a-legitimate-site.com/?CFID=b1c8-30f3469ba7f7&CFTOKEN=2"> Click here for free stuff!</a>

How this can cause Session LossMore than one CFML application on

the same domain2

2 Pete Freitag, Session Loss and Session Fixation in ColdFusion, March 01, 2013

HTTPOnly Cookies· These cookies are only available over HTTP

connections, NOT Javascript

HTTPOnly CookiesSet once for the entire application

// CF 10+ & Lucee 4.5+this.sessioncookie.httponly = true;

# Java JVM args (CF 9.0.1+)-Dcoldfusion.sessioncookie.httponly=true

HTTPOnly CookiesOR set them manually

<!-- CF 9+ & Lucee 4.5+ --><cfcookie name="CFID" value="#sessoin.cfid#" httponly="true" />

<!-- CF 8 and lower --><cfheader name="Set-Cookie" value="CFID=#session.cfid#;path=/;HTTPOnly" />

SSLEnable the secure flag on your cookies

// CF 10+ & Lucee 4.5+this.sessioncookie.secure = true;

<!-- CF 9+ & Lucee 4.5+ --><cfcookie name="CFID" value="#sessoin.cfid#" httponly="true" secure="true" />

<!-- CF 8 and lower --><cfheader name="Set-Cookie" value="CFID=#session.cfid#;path=/;HTTPOnly;secure" />

Turning off client managementIf you are setting your own cookies,

remember to turn off client management// Application.cfccomponent { this.clientmanagement = false;}

Questions!

Other talks at dev.Objective()

Live Testing a Legacy AppThursday

1:45 PM to 2:45 PM

Thank You!! elpete

@_elpete! dev.elpete.com