Basic cookies security in rack

I run my own Task & Time tracking app SupTasks. It’s build on tiny ruby web framework Roda which itself is build on rack. I was curious how sessions and cookies are handled in rack and in general so i’v been investigating it a bit lately.

Rack offers 3 built in session storage mechanisms. Cookie, Memcache and Pool

All of them use cookies to store session_id but after that they differ in where other parts of session are stored.

Most of us will use Cookie and it might be like this:

use Rack::Session::Cookie

What’s actually stored in cookie is base64 encoded marshalled hash:

base64 marshalled hash

Let’s ‘decrypt’ it:

require 'base64'


=> {"session_id"=>"cc87d3101fc5f9ea709b1805895d34ae055e380c43202b805cf8e870999dc255",
 "user_name"=>"Premysl Donat"}

Wow! These are my credentials!

Ok, let’s try something. I know my friend also has an account on SupTasks. And i know his e-mail:

require 'base64'

 "user_name"=>"Roman Postolka"}))


If i replace cookie with this string i should be logged in as ‘’:

setting up a crafted cookie

And voilà, after page reload, it works:

logged in as different user

How to protect

Luckily, there is a simple fix for this:

use Rack::Session::Cookie, { secret: 'some_long_random_secret' }

Now the cookie looks like this:

base64 marshalled hash with appended digest

This new cookie has two parts - first is our base64 encoded marshalled hash and second is it’s SHA1 digest created with our new secret. Everytime session is loaded back from cookie, rack takes the first part and creates new digest from it. Then it’s compared to the one stored in second part of cookie. If they match it means that noone manipulated with the cookie. If someone did, our new digest would be different from the saved one.

The most important thing now is to save the secret somewhere safe, so nobody can read it. Otherwise attacker could easily create digest which would match the rack check. You can keep your secret in server environment or load it from some yaml file but never keep it in your version control.

By the way in future versions of Rack it won’t even be possible to use cookie session without secret. :)

About me

Hi, i'm Premysl Donat and this is a place where i share things i find interesting.

This is my picture:

Premysl Donat at Balaton lake

I'm a web developer and i work at UOL. I also have a tiny company named Imagine Anything under which i run few side projects. Imagine has a beautiful logo so you better check it out!

I release all of my code under MIT license and it's freely available at Github.

Have a good one, Premek

Follow @Masa331