The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
NAME
    Session::Storage::Secure - Encrypted, expiring, compressed, serialized
    session data with integrity

VERSION
    version 0.001

SYNOPSIS
      my $store = Session::Storage::Secure->new(
        secret_key   => "your pass phrase here",
        default_duration => 86400 * 7,
      );

      my $encoded = $store->encode( $data, $expires );

      my $decoded = $store->decode( $encoded );

DESCRIPTION
    This module implements a secure way to encode session data. It is
    primarily intended for storing session data in browser cookies, but
    could be used with other backend storage where security of stored
    session data is important.

    Features include:

    *   Data serialization and compression using Sereal

    *   Data encryption using AES with a unique derived key per encoded
        session

    *   Enforced expiration timestamp (optional)

    *   Integrity protected with a message authentication code (MAC)

    The storage protocol used in this module is based heavily on A Secure
    Cookie Protocol
    <http://www.cse.msu.edu/~alexliu/publications/Cookie/Cookie_COMNET.pdf>
    by Alex Liu and others. Liu proposes a session cookie value as follows:

      user|expiration|E(data,k)|HMAC(user|expiration|data|ssl-key,k)

      where

        | denotes concatenation with a separator character
        E(p,q) is a symmetric encryption of p with key q
        HMAC(p,q) is a keyed message hash of p with key q
        k is HMAC(user|expiration, sk)
        sk is a secret key shared by all servers
        ssl-key is an SSL session key

    Because SSL session keys are not readily available (and SSL termination
    may happen prior to the application server), we omit "ssl-key". This
    weakens protection against replay attacks if an attacker can break the
    SSL session key and intercept messages.

    Using "user" and "expiration" to generate the encryption and MAC keys
    was a method proposed to ensure unique keys to defeat volume attacks
    against the secret key. Rather than rely on those for uniqueness, which
    also reveals user name and prohibits anonymous sessions, we replace
    "user" with a cryptographically-strong random salt value.

    The original proposal also calculates a MAC based on unencrypted data.
    We instead calculate the MAC based on the encrypted data. This avoids
    the extra step of decrypting invalid messages. Because the salt is
    already encoded into the key, we omit it from the MAC input.

    Therefore, the session storage protocol used by this module is as
    follows:

      salt|expiration|E(data,k)|HMAC(expiration|E(data,k),k)

      where

        | denotes concatenation with a separator character
        E(p,q) is a symmetric encryption of p with key q
        HMAC(p,q) is a keyed message hash of p with key q
        k is HMAC(salt, sk)
        sk is a secret key shared by all servers

    The salt value is generated using Math::Random::ISAAC::XS, seeded from
    "/dev/random", if available, or from rand(), if not.

    The HMAC algorithm is "hmac_sha256" from Digest::SHA. Encryption is done
    by Crypt::CBC using Crypt::Rijndael (AES). The ciphertext and MAC's in
    the cookie are Base64 encoded by MIME::Base64.

    During session retrieval, if the MAC does not authenticate or if the
    expiration is set and in the past, the session will be discarded.

ATTRIBUTES
  secret_key (required)
    This is used to secure the session data. The encryption and message
    authentication key is derived from this using a one-way function.
    Changing it will invalidate all sessions.

  default_duration
    Number of seconds for which the session may be considered valid. If an
    expiration is not provided to "encode", this is used instead to expire
    the session after a period of time. It is unset by default, meaning that
    sessions expiration is not capped.

METHODS
  encode
      my $string = $store->encode( $data, $expires );

    The $data argument should be a reference to a data structure. It must
    not contain objects. If it is undefined, an empty hash reference will be
    encoded instead.

    The optional $expires argument should be the session expiration time
    expressed as epoch seconds. If the $expires time is in the past, the
    $data argument is cleared and an empty hash reference is encoded and
    returned. If no $expires is given, then if the "default_duration"
    attribute is set, it will be used to calculate an expiration time.

    The method returns a string that securely encodes the session data. All
    binary components are base64 encoded.

    An exception is thrown on any errors.

  decode
      my $data = $store->decode( $string );

    The $string argument must be the output of "encode".

    If the message integrity check fails or if expiration exists and is in
    the past, the method returns undef or an empty list (depending on
    context).

    An exception is thrown on any errors.

LIMITATIONS
  Secret key
    You must protect the secret key, of course. Rekeying periodically would
    improve security. Rekeying also invalidates all existing sessions. In a
    multi-node application, all nodes must share the same secret key.

  Session size
    If storing the encoded session in a cookie, keep in mind that cookies
    must fit within 4k, so don't store too much data. This module uses
    Sereal for serialization and enables the "snappy" compression option.
    Sereal plus Snappy appears to be one of the fastest and most compact
    serialization options for Perl, according to the Sereal benchmarks
    <https://github.com/Sereal/Sereal/wiki/Sereal-Comparison-Graphs> page.

    However, nothing prevents the encoded output from exceeding 4k.
    Applications must check for this condition and handle it appropriately
    with an error or by splitting the value across multiple cookies.

  Objects not stored
    Session data may not include objects. Sereal is configured to die if
    objects are encountered because object serialization/deserialiation can
    have undesirable side effects. Applications should take steps to
    deflate/inflate objects before storing them in session data.

SECURITY
    Storing encrypted session data within a browser cookie avoids latency
    and overhead of backend session storage, but has several additional
    security considerations.

  Transport security
    If using cookies to store session data, an attacker could intercept
    cookies and replay them to impersonate a valid user regardless of
    encryption. SSL encryption of the transport channel is strongly
    recommended.

  Cookie replay
    Because all session state is maintained in the session cookie, an
    attacker or malicious user could replay an old cookie to return to a
    previous state. Cookie-based sessions should not be used for recording
    incremental steps in a transaction or to record "negative rights".

    Because cookie expiration happens on the client-side, an attacker or
    malicious user could replay a cookie after its scheduled expiration
    date. It is strongly recommended to set "cookie_duration" or
    "default_duration" to limit the window of opportunity for such replay
    attacks.

  Session authentication
    A compromised secret key could be used to construct valid messages
    appearing to be from any user. Applications should take extra steps in
    their use of session data to ensure that sessions are authenticated to
    the user.

    One simple approach could be to store a hash of the user's hashed
    password in the session on login and to verify it on each request.

      # on login
      my $hashed_pw = bcrypt( $password, $salt );
      if ( $hashed_pw eq $hashed_pw_from_db ) {
        session user => $user;
        session auth => bcrypt( $hashed_pw, $salt ) );
      }

      # on each request
      if ( bcrypt( $hashed_pw_from_db, $salt ) ne session("auth") ) {
        context->destroy_session;
      }

    The downside of this is that if there is a read-only attack against the
    database (SQL injection or leaked backup dump) and the secret key is
    compromised, then an attacker can forge a cookie to impersonate any
    user.

    A more secure approach suggested by Stephen Murdoch in Hardened
    Stateless Session Cookies
    <http://www.cl.cam.ac.uk/~sjm217/papers/protocols08cookies.pdf> is to
    store an iterated hash of the hashed password in the database and use
    the hashed password itself within the session.

      # on login
      my $hashed_pw = bcrypt( $password, $salt );
      if ( bcrypt( $hashed_pw, $salt ) eq $double_hashed_pw_from_db ) {
        session user => $user;
        session auth => $hashed_pw;
      }

      # on each request
      if ( $double_hashed_pw_from_db ne bcrypt( session("auth"), $salt ) ) {
        context->destroy_session;
      }

    This latter approach means that even a compromise of the secret key and
    the database contents can't be used to impersonate a user because doing
    so would requiring reversing a one-way hash to determine the correct
    authenticator to put into the forged cookie.

    Both methods require an additional database read per request. This
    diminishes some of the scalability benefits of storing session data in a
    cookie, but the read could be cached and there is still no database
    write needed to store session data.

SEE ALSO
    Papers on secure cookies and cookie session storage:

    *   Liu, Alex X., et al., A Secure Cookie Protocol
        <http://www.cse.msu.edu/~alexliu/publications/Cookie/Cookie_COMNET.p
        df>

    *   Murdoch, Stephen J., Hardened Stateless Session Cookies
        <http://www.cl.cam.ac.uk/~sjm217/papers/protocols08cookies.pdf>

    *   Fu, Kevin, et al., Dos and Don'ts of Client Authentication on the
        Web <http://pdos.csail.mit.edu/papers/webauth:sec10.pdf>

    CPAN modules implementing cookie session storage:

    *   Catalyst::Plugin::CookiedSession -- encryption only

    *   Dancer::Session::Cookie -- Dancer 1, encryption only

    *   Dancer::SessionFactory::Cookie -- Dancer 2, forthcoming, based on
        this module

    *   HTTP::CryptoCookie -- encryption only

    *   Mojolicious::Sessions -- MAC only

    *   Plack::Middleware::Session::Cookie -- MAC only

    *   Plack::Middleware::Session::SerializedCookie -- really just a
        framework and you provide the guts with callbacks

    Related CPAN modules that offer frameworks for serializing and
    encrypting data, but without features relevant for sessions like
    expiration and unique keying.

    *   Crypt::Util

    *   Data::Serializer

SUPPORT
  Bugs / Feature Requests
    Please report any bugs or feature requests through the issue tracker at
    <https://github.com/dagolden/session-storage-secure/issues>. You will be
    notified automatically of any progress on your issue.

  Source Code
    This is open source software. The code repository is available for
    public review and contribution under the terms of the license.

    <https://github.com/dagolden/session-storage-secure>

      git clone git://github.com/dagolden/session-storage-secure.git

AUTHOR
    David Golden <dagolden@cpan.org>

COPYRIGHT AND LICENSE
    This software is Copyright (c) 2013 by David Golden.

    This is free software, licensed under:

      The Apache License, Version 2.0, January 2004