1Session::Storage::SecurUes(e3r)Contributed Perl DocumentSaetsisoinon::Storage::Secure(3)
2
3
4

NAME

6       Session::Storage::Secure - Encrypted, expiring, compressed, serialized
7       session data with integrity
8

VERSION

10       version 1.000
11

SYNOPSIS

13         my $store = Session::Storage::Secure->new(
14           secret_key   => "your pass phrase here",
15           default_duration => 86400 * 7,
16         );
17
18         my $encoded = $store->encode( $data, $expires );
19
20         my $decoded = $store->decode( $encoded );
21

DESCRIPTION

23       This module implements a secure way to encode session data.  It is
24       primarily intended for storing session data in browser cookies, but
25       could be used with other backend storage where security of stored
26       session data is important.
27
28       Features include:
29
30       •   Data serialization and compression using Sereal
31
32       •   Data encryption using AES with a unique derived key per encoded
33           session
34
35       •   Enforced expiration timestamp (optional)
36
37       •   Integrity protected with a message authentication code (MAC)
38
39       The storage protocol used in this module is based heavily on A Secure
40       Cookie Protocol
41       <http://www.cse.msu.edu/~alexliu/publications/Cookie/Cookie_COMNET.pdf>
42       by Alex Liu and others.  Liu proposes a session cookie value as
43       follows:
44
45         user|expiration|E(data,k)|HMAC(user|expiration|data|ssl-key,k)
46
47         where
48
49           | denotes concatenation with a separator character
50           E(p,q) is a symmetric encryption of p with key q
51           HMAC(p,q) is a keyed message hash of p with key q
52           k is HMAC(user|expiration, sk)
53           sk is a secret key shared by all servers
54           ssl-key is an SSL session key
55
56       Because SSL session keys are not readily available (and SSL termination
57       may happen prior to the application server), we omit "ssl-key".  This
58       weakens protection against replay attacks if an attacker can break the
59       SSL session key and intercept messages.
60
61       Using "user" and "expiration" to generate the encryption and MAC keys
62       was a method proposed to ensure unique keys to defeat volume attacks
63       against the secret key.  Rather than rely on those for uniqueness (with
64       the unfortunate side effect of revealing user names and prohibiting
65       anonymous sessions), we replace "user" with a cryptographically-strong
66       random salt value.
67
68       The original proposal also calculates a MAC based on unencrypted data.
69       We instead calculate the MAC based on the encrypted data.  This avoids
70       an extra step decrypting invalid messages.  Because the salt is already
71       encoded into the key, we omit it from the MAC input.
72
73       Therefore, the session storage protocol used by this module is as
74       follows:
75
76         salt|expiration|E(data,k)|HMAC(expiration|E(data,k),k)
77
78         where
79
80           | denotes concatenation with a separator character
81           E(p,q) is a symmetric encryption of p with key q
82           HMAC(p,q) is a keyed message hash of p with key q
83           k is HMAC(salt, sk)
84           sk is a secret key shared by all servers
85
86       The salt value is generated using Math::Random::ISAAC::XS, seeded from
87       Crypt::URandom.
88
89       The HMAC algorithm is "hmac_sha256" from Digest::SHA.  Encryption is
90       done by Crypt::CBC using Crypt::Rijndael (AES).  The ciphertext and
91       MAC's in the cookie are Base64 encoded by MIME::Base64 by default.
92
93       During session retrieval, if the MAC does not authenticate or if the
94       expiration is set and in the past, the session will be discarded.
95

ATTRIBUTES

97   secret_key (required)
98       This is used to secure the session data.  The encryption and message
99       authentication key is derived from this using a one-way function.
100       Changing it will invalidate all sessions.
101
102   default_duration
103       Number of seconds for which the session may be considered valid.  If an
104       expiration is not provided to "encode", this is used instead to expire
105       the session after a period of time.  It is unset by default, meaning
106       that session expiration is not capped.
107
108   old_secrets
109       An optional array reference of strings containing old secret keys no
110       longer used for encryption but still supported for decrypting session
111       data.
112
113   separator
114       A character used to separate fields.  It defaults to "~".
115
116   sereal_encoder_options
117       A hash reference with constructor arguments for Sereal::Encoder.
118       Defaults to "{ snappy => 1, croak_on_bless => 1 }".
119
120   sereal_decoder_options
121       A hash reference with constructor arguments for Sereal::Decoder.
122       Defaults to "{ refuse_objects => 1, validate_utf8  => 1 }".
123
124   transport_encoder
125       A code reference to convert binary data elements (the encrypted data
126       and the MAC) into a transport-safe form.  Defaults to
127       MIME::Base64::encode_base64url.  The output must not include the
128       "separator" attribute used to delimit fields.
129
130   transport_decoder
131       A code reference to extract binary data (the encrypted data and the
132       MAC) from a transport-safe form.  It must be the complement to
133       "encode".  Defaults to MIME::Base64::decode_base64url.
134
135   protocol_version
136       An integer representing the protocol used by
137       "Session::Storage::Secure".  Protocol 1 was the initial version, which
138       used a now-deprecated mode of Crypt::CBC.  Protocol 2 is the current
139       default.
140

METHODS

142   encode
143         my $string = $store->encode( $data, $expires );
144
145       The $data argument should be a reference to a data structure.  By
146       default, it must not contain objects.  (See "Objects not stored by
147       default" for rationale and alternatives.) If it is undefined, an empty
148       hash reference will be encoded instead.
149
150       The optional $expires argument should be the session expiration time
151       expressed as epoch seconds.  If the $expires time is in the past, the
152       $data argument is cleared and an empty hash reference is encoded and
153       returned.  If no $expires is given, then if the "default_duration"
154       attribute is set, it will be used to calculate an expiration time.
155
156       The method returns a string that securely encodes the session data.
157       All binary components are protected via the "transport_encoder"
158       attribute.
159
160       An exception is thrown on any errors.
161
162   decode
163         my $data = $store->decode( $string );
164
165       The $string argument must be the output of "encode".
166
167       If the message integrity check fails or if expiration exists and is in
168       the past, the method returns undef or an empty list (depending on
169       context).
170
171       An exception is thrown on any errors.
172

LIMITATIONS

174   Secret key
175       You must protect the secret key, of course.  Rekeying periodically
176       would improve security.  Rekeying also invalidates all existing
177       sessions unless the "old_secrets" attribute contains old encryption
178       keys still used for decryption.  In a multi-node application, all nodes
179       must share the same secret key.
180
181   Session size
182       If storing the encoded session in a cookie, keep in mind that cookies
183       must fit within 4k, so don't store too much data.  This module uses
184       Sereal for serialization and enables the "snappy" compression option.
185       Sereal plus Snappy appears to be one of the fastest and most compact
186       serialization options for Perl, according to the Sereal benchmarks
187       <https://github.com/Sereal/Sereal/wiki/Sereal-Comparison-Graphs> page.
188
189       However, nothing prevents the encoded output from exceeding 4k.
190       Applications must check for this condition and handle it appropriately
191       with an error or by splitting the value across multiple cookies.
192
193   Objects not stored by default
194       The default Sereal options do not allow storing objects because object
195       deserialization can have undesirable side effects, including
196       potentially fatal errors if a class is not available at deserialization
197       time or if internal class structures changed from when the session data
198       was serialized to when it was deserialized.  Applications should take
199       steps to deflate/inflate objects before storing them in session data.
200
201       Alternatively, applications can change "sereal_encoder_options" and
202       "sereal_decoder_options" to allow object serialization or other object
203       transformations and accept the risks of doing so.
204

SECURITY

206       Storing encrypted session data within a browser cookie avoids latency
207       and overhead of backend session storage, but has several additional
208       security considerations.
209
210   Transport security
211       If using cookies to store session data, an attacker could intercept
212       cookies and replay them to impersonate a valid user regardless of
213       encryption.  SSL encryption of the transport channel is strongly
214       recommended.
215
216   Cookie replay
217       Because all session state is maintained in the session cookie, an
218       attacker or malicious user could replay an old cookie to return to a
219       previous state.  Cookie-based sessions should not be used for recording
220       incremental steps in a transaction or to record "negative rights".
221
222       Because cookie expiration happens on the client-side, an attacker or
223       malicious user could replay a cookie after its scheduled expiration
224       date.  It is strongly recommended to set "cookie_duration" or
225       "default_duration" to limit the window of opportunity for such replay
226       attacks.
227
228   Session authentication
229       A compromised secret key could be used to construct valid messages
230       appearing to be from any user.  Applications should take extra steps in
231       their use of session data to ensure that sessions are authenticated to
232       the user.
233
234       One simple approach could be to store a hash of the user's hashed
235       password in the session on login and to verify it on each request.
236
237         # on login
238         my $hashed_pw = bcrypt( $password, $salt );
239         if ( $hashed_pw eq $hashed_pw_from_db ) {
240           session user => $user;
241           session auth => bcrypt( $hashed_pw, $salt ) );
242         }
243
244         # on each request
245         if ( bcrypt( $hashed_pw_from_db, $salt ) ne session("auth") ) {
246           context->destroy_session;
247         }
248
249       The downside of this is that if there is a read-only attack against the
250       database (SQL injection or leaked backup dump) and the secret key is
251       compromised, then an attacker can forge a cookie to impersonate any
252       user.
253
254       A more secure approach suggested by Stephen Murdoch in Hardened
255       Stateless Session Cookies
256       <http://www.cl.cam.ac.uk/~sjm217/papers/protocols08cookies.pdf> is to
257       store an iterated hash of the hashed password in the database and use
258       the hashed password itself within the session.
259
260         # on login
261         my $hashed_pw = bcrypt( $password, $salt );
262         if ( bcrypt( $hashed_pw, $salt ) eq $double_hashed_pw_from_db ) {
263           session user => $user;
264           session auth => $hashed_pw;
265         }
266
267         # on each request
268         if ( $double_hashed_pw_from_db ne bcrypt( session("auth"), $salt ) ) {
269           context->destroy_session;
270         }
271
272       This latter approach means that even a compromise of the secret key and
273       the database contents can't be used to impersonate a user because doing
274       so would requiring reversing a one-way hash to determine the correct
275       authenticator to put into the forged cookie.
276
277       Both methods require an additional database read per request. This
278       diminishes some of the scalability benefits of storing session data in
279       a cookie, but the read could be cached and there is still no database
280       write needed to store session data.
281

SEE ALSO

283       Papers on secure cookies and cookie session storage:
284
285       •   Liu, Alex X., et al., A Secure Cookie Protocol
286           <http://www.cse.msu.edu/~alexliu/publications/Cookie/Cookie_COMNET.pdf>
287
288       •   Murdoch, Stephen J., Hardened Stateless Session Cookies
289           <http://www.cl.cam.ac.uk/~sjm217/papers/protocols08cookies.pdf>
290
291       •   Fu, Kevin, et al., Dos and Don'ts of Client Authentication on the
292           Web <http://pdos.csail.mit.edu/papers/webauth:sec10.pdf>
293
294       CPAN modules implementing cookie session storage:
295
296       •   Catalyst::Plugin::CookiedSession -- encryption only
297
298       •   Dancer::Session::Cookie -- Dancer 1, encryption only
299
300       •   Dancer::SessionFactory::Cookie -- Dancer 2, forthcoming, based on
301           this module
302
303       •   HTTP::CryptoCookie -- encryption only
304
305       •   Mojolicious::Sessions -- MAC only
306
307       •   Plack::Middleware::Session::Cookie -- MAC only
308
309       •   Plack::Middleware::Session::SerializedCookie -- really just a
310           framework and you provide the guts with callbacks
311
312       Related CPAN modules that offer frameworks for serializing and
313       encrypting data, but without features relevant for sessions like
314       expiration and unique keying.
315
316       •   Crypt::Util
317
318       •   Data::Serializer
319

AUTHOR

321       David Golden <dagolden@cpan.org>
322

CONTRIBUTORS

324       •   Petr Písař <ppisar@redhat.com>
325
326       •   Tom Hukins <tom@eborcom.com>
327
329       This software is Copyright (c) 2013 by David Golden.
330
331       This is free software, licensed under:
332
333         The Apache License, Version 2.0, January 2004
334
335
336
337perl v5.38.0                      2023-07-21       Session::Storage::Secure(3)
Impressum