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 0.011
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

METHODS

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

LIMITATIONS

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

SECURITY

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

SEE ALSO

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

SUPPORT

315   Bugs / Feature Requests
316       Please report any bugs or feature requests through the issue tracker at
317       <https://github.com/dagolden/Session-Storage-Secure/issues>.  You will
318       be notified automatically of any progress on your issue.
319
320   Source Code
321       This is open source software.  The code repository is available for
322       public review and contribution under the terms of the license.
323
324       <https://github.com/dagolden/Session-Storage-Secure>
325
326         git clone https://github.com/dagolden/Session-Storage-Secure.git
327

AUTHOR

329       David Golden <dagolden@cpan.org>
330

CONTRIBUTOR

332       Tom Hukins <tom@eborcom.com>
333
335       This software is Copyright (c) 2013 by David Golden.
336
337       This is free software, licensed under:
338
339         The Apache License, Version 2.0, January 2004
340
341
342
343perl v5.30.0                      2019-07-26       Session::Storage::Secure(3)
Impressum