title: Detecting Rails 4 Session cookie tampering
body: <h2>Background</h2>
  
  <p>I'm an experienced web developer (mostly with Python and CherryPy) who has implemented secure session management from scratch before, and is now learning Rails. I'm investigating the behavior of Rails sessions as exposed by the <code>session</code> object that is available in the <code>ActionController</code> instance and view contexts.</p>
  
  <h2>Question/Problem</h2>
  
  <p>I have read that the default implementation of sessions in Rails 4 uses an encrypted and tamper-proof cookie. Cool, I guess that means I can use it to hold a user ID for user sessions without worrying about session forging (tamper-proof) or anyone being able to find out what their ID is (encrypted). I wanted to test this and see what rails would do if the session cookie was altered. </p>
  
  <p>So, I went and altered the content of the session cookie attribute using a browser add-on, and when I reload the page with the new cookie value, Rails just happily gives me different new values for <code>session_id</code> and <code>_csrf_token</code>.</p>
  
  <p>What happened to session cookie integrity!?</p>
  
  <p>Shouldn't rails detect (via HMAC signature) that the cookie was altered and then tell me about it somehow?</p>
  
  <p>I'm terrified that I'm missing something obscenely obvious, but I've been having no luck searching for an answer on the web, and the source code isn't giving it up easily either (I'm new to ruby).  Thanks in advance.</p>
  
  <h2>The Experiment</h2>
  
  <p>I created a new app and generated a controller with an <code>index</code> action:</p>
  
  <pre><code>$ rails new my_app
  $ cd my_app; rails g controller home index
  </code></pre>
  
  <p>Then I added these two lines to the <em>app/views/layouts/application.html.erb</em> file:</p>
  
  <pre><code>&lt;%= session.keys %&gt;&lt;br/&gt;
  &lt;%= session.values %&gt;
  </code></pre>
  
  <p>I started up the dev server and navigated my browser to "localhost:3000/home/index". As expected, the page has the following lines at the bottom:</p>
  
  <pre><code>["session_id", "_csrf_token"]
  ["8c1558cabe6c86cfb37d6191f2e03bf8", "S8i8/++8t6v8W8RMeyvnNu3Pjvj+KkMo2UEcm1oVVZg="]
  </code></pre>
  
  <p>Reloading the page gives me the same values, although the app sets a new value of the <code>_my_app_session</code> cookie attribute every time. That seems weird to me, but I'm getting the same session hash values, so I guess it's cool. </p>
  
  <p>Then, I used a cookie editing add-on for Chrome to alter the value of the <code>_my_app_session</code> cookie attribute (replacing the first character of the attribute value). Reloading the page shows completely different values without anything happening. WAT?</p>