.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Session::Storage::Secure 3pm" .TH Session::Storage::Secure 3pm "2014-05-04" "perl v5.18.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Session::Storage::Secure \- Encrypted, expiring, compressed, serialized session data with integrity .SH "VERSION" .IX Header "VERSION" version 0.010 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 4 \& 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 ); .Ve .SH "DESCRIPTION" .IX Header "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. .PP Features include: .IP "\(bu" 4 Data serialization and compression using Sereal .IP "\(bu" 4 Data encryption using \s-1AES\s0 with a unique derived key per encoded session .IP "\(bu" 4 Enforced expiration timestamp (optional) .IP "\(bu" 4 Integrity protected with a message authentication code (\s-1MAC\s0) .PP The storage protocol used in this module is based heavily on A Secure Cookie Protocol by Alex Liu and others. Liu proposes a session cookie value as follows: .PP .Vb 1 \& 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 .Ve .PP Because \s-1SSL\s0 session keys are not readily available (and \s-1SSL\s0 termination may happen prior to the application server), we omit \f(CW\*(C`ssl\-key\*(C'\fR. This weakens protection against replay attacks if an attacker can break the \s-1SSL\s0 session key and intercept messages. .PP Using \f(CW\*(C`user\*(C'\fR and \f(CW\*(C`expiration\*(C'\fR to generate the encryption and \s-1MAC\s0 keys was a method proposed to ensure unique keys to defeat volume attacks against the secret key. Rather than rely on those for uniqueness (with the unfortunate side effect of revealing user names and prohibiting anonymous sessions), we replace \f(CW\*(C`user\*(C'\fR with a cryptographically-strong random salt value. .PP The original proposal also calculates a \s-1MAC\s0 based on unencrypted data. We instead calculate the \s-1MAC\s0 based on the encrypted data. This avoids an extra step decrypting invalid messages. Because the salt is already encoded into the key, we omit it from the \s-1MAC\s0 input. .PP Therefore, the session storage protocol used by this module is as follows: .PP .Vb 1 \& 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 .Ve .PP The salt value is generated using Math::Random::ISAAC::XS, seeded from Crypt::URandom. .PP The \s-1HMAC\s0 algorithm is \f(CW\*(C`hmac_sha256\*(C'\fR from Digest::SHA. Encryption is done by Crypt::CBC using Crypt::Rijndael (\s-1AES\s0). The ciphertext and \&\s-1MAC\s0's in the cookie are Base64 encoded by MIME::Base64 by default. .PP During session retrieval, if the \s-1MAC\s0 does not authenticate or if the expiration is set and in the past, the session will be discarded. .SH "ATTRIBUTES" .IX Header "ATTRIBUTES" .SS "secret_key (required)" .IX Subsection "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. .SS "default_duration" .IX Subsection "default_duration" Number of seconds for which the session may be considered valid. If an expiration is not provided to \f(CW\*(C`encode\*(C'\fR, this is used instead to expire the session after a period of time. It is unset by default, meaning that session expiration is not capped. .SS "old_secrets" .IX Subsection "old_secrets" An optional array reference of strings containing old secret keys no longer used for encryption but still supported for decrypting session data. .SS "separator" .IX Subsection "separator" A character used to separate fields. It defaults to \f(CW\*(C`~\*(C'\fR. .SS "sereal_encoder_options" .IX Subsection "sereal_encoder_options" A hash reference with constructor arguments for Sereal::Encoder. Defaults to \f(CW\*(C`{ snappy => 1, croak_on_bless => 1 }\*(C'\fR. .SS "sereal_decoder_options" .IX Subsection "sereal_decoder_options" A hash reference with constructor arguments for Sereal::Decoder. Defaults to \f(CW\*(C`{ refuse_objects => 1, validate_utf8 => 1 }\*(C'\fR. .SS "transport_encoder" .IX Subsection "transport_encoder" A code reference to convert binary data elements (the encrypted data and the \&\s-1MAC\s0) into a transport-safe form. Defaults to MIME::Base64::encode_base64url. The output must not include the \f(CW\*(C`separator\*(C'\fR attribute used to delimit fields. .SS "transport_decoder" .IX Subsection "transport_decoder" A code reference to extract binary data (the encrypted data and the \&\s-1MAC\s0) from a transport-safe form. It must be the complement to \f(CW\*(C`encode\*(C'\fR. Defaults to MIME::Base64::decode_base64url. .SH "METHODS" .IX Header "METHODS" .SS "encode" .IX Subsection "encode" .Vb 1 \& my $string = $store\->encode( $data, $expires ); .Ve .PP The \f(CW$data\fR argument should be a reference to a data structure. By default, it must not contain objects. (See \*(L"Objects not stored by default\*(R" for rationale and alternatives.) If it is undefined, an empty hash reference will be encoded instead. .PP The optional \f(CW$expires\fR argument should be the session expiration time expressed as epoch seconds. If the \f(CW$expires\fR time is in the past, the \&\f(CW$data\fR argument is cleared and an empty hash reference is encoded and returned. If no \f(CW$expires\fR is given, then if the \f(CW\*(C`default_duration\*(C'\fR attribute is set, it will be used to calculate an expiration time. .PP The method returns a string that securely encodes the session data. All binary components are protected via the \*(L"transport_encoder\*(R" attribute. .PP An exception is thrown on any errors. .SS "decode" .IX Subsection "decode" .Vb 1 \& my $data = $store\->decode( $string ); .Ve .PP The \f(CW$string\fR argument must be the output of \f(CW\*(C`encode\*(C'\fR. .PP 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). .PP An exception is thrown on any errors. .SH "LIMITATIONS" .IX Header "LIMITATIONS" .SS "Secret key" .IX Subsection "Secret key" You must protect the secret key, of course. Rekeying periodically would improve security. Rekeying also invalidates all existing sessions unless the \&\f(CW\*(C`old_secrets\*(C'\fR attribute contains old encryption keys still used for decryption. In a multi-node application, all nodes must share the same secret key. .SS "Session size" .IX Subsection "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 \f(CW\*(C`snappy\*(C'\fR compression option. Sereal plus Snappy appears to be one of the fastest and most compact serialization options for Perl, according to the Sereal benchmarks page. .PP 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. .SS "Objects not stored by default" .IX Subsection "Objects not stored by default" The default Sereal options do not allow storing objects because object deserialization can have undesirable side effects, including potentially fatal errors if a class is not available at deserialization time or if internal class structures changed from when the session data was serialized to when it was deserialized. Applications should take steps to deflate/inflate objects before storing them in session data. .PP Alternatively, applications can change \*(L"sereal_encoder_options\*(R" and \&\*(L"sereal_decoder_options\*(R" to allow object serialization or other object transformations and accept the risks of doing so. .SH "SECURITY" .IX Header "SECURITY" Storing encrypted session data within a browser cookie avoids latency and overhead of backend session storage, but has several additional security considerations. .SS "Transport security" .IX Subsection "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. \s-1SSL\s0 encryption of the transport channel is strongly recommended. .SS "Cookie replay" .IX Subsection "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 \*(L"negative rights\*(R". .PP 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 \f(CW\*(C`cookie_duration\*(C'\fR or \f(CW\*(C`default_duration\*(C'\fR to limit the window of opportunity for such replay attacks. .SS "Session authentication" .IX Subsection "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. .PP 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. .PP .Vb 6 \& # 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; \& } .Ve .PP The downside of this is that if there is a read-only attack against the database (\s-1SQL\s0 injection or leaked backup dump) and the secret key is compromised, then an attacker can forge a cookie to impersonate any user. .PP A more secure approach suggested by Stephen Murdoch in Hardened Stateless Session Cookies is to store an iterated hash of the hashed password in the database and use the hashed password itself within the session. .PP .Vb 6 \& # 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; \& } .Ve .PP 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. .PP 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. .SH "SEE ALSO" .IX Header "SEE ALSO" Papers on secure cookies and cookie session storage: .IP "\(bu" 4 Liu, Alex X., et al., A Secure Cookie Protocol .IP "\(bu" 4 Murdoch, Stephen J., Hardened Stateless Session Cookies .IP "\(bu" 4 Fu, Kevin, et al., Dos and Don'ts of Client Authentication on the Web .PP \&\s-1CPAN\s0 modules implementing cookie session storage: .IP "\(bu" 4 Catalyst::Plugin::CookiedSession \*(-- encryption only .IP "\(bu" 4 Dancer::Session::Cookie \*(-- Dancer 1, encryption only .IP "\(bu" 4 Dancer::SessionFactory::Cookie \*(-- Dancer 2, forthcoming, based on this module .IP "\(bu" 4 HTTP::CryptoCookie \*(-- encryption only .IP "\(bu" 4 Mojolicious::Sessions \*(-- \s-1MAC\s0 only .IP "\(bu" 4 Plack::Middleware::Session::Cookie \*(-- \s-1MAC\s0 only .IP "\(bu" 4 Plack::Middleware::Session::SerializedCookie \*(-- really just a framework and you provide the guts with callbacks .PP Related \s-1CPAN\s0 modules that offer frameworks for serializing and encrypting data, but without features relevant for sessions like expiration and unique keying. .IP "\(bu" 4 Crypt::Util .IP "\(bu" 4 Data::Serializer .SH "SUPPORT" .IX Header "SUPPORT" .SS "Bugs / Feature Requests" .IX Subsection "Bugs / Feature Requests" Please report any bugs or feature requests through the issue tracker at . You will be notified automatically of any progress on your issue. .SS "Source Code" .IX Subsection "Source Code" This is open source software. The code repository is available for public review and contribution under the terms of the license. .PP .PP .Vb 1 \& git clone https://github.com/dagolden/Session\-Storage\-Secure.git .Ve .SH "AUTHOR" .IX Header "AUTHOR" David Golden .SH "CONTRIBUTOR" .IX Header "CONTRIBUTOR" Tom Hukins .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is Copyright (c) 2013 by David Golden. .PP This is free software, licensed under: .PP .Vb 1 \& The Apache License, Version 2.0, January 2004 .Ve