Session-Storage-Secure-0.007/000755 000765 000024 00000000000 12152265347 016232 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/Changes000644 000765 000024 00000002257 12152265347 017533 0ustar00davidstaff000000 000000 Revision history for Session-Storage-Secure 0.007 2013-05-31 23:30:44 America/New_York [FIXED] - Replaced HMAC equality check with a constant-time comparison to foil timing attacks 0.006 2013-02-06 22:56:45 America/New_York [FIXED] - Made MooX::Types::MooseLike prereq explicit to try to address prereqs failures by some testers 0.005 2013-02-01 13:55:34 America/New_York [FIXED] - Added some defensive code to try to avoid test failures on Perl 5.8 0.004 2013-01-25 15:10:34 America/New_York [CHANGES] - Seeding is now done by Crypt::URandom, which uses the best non-blocking source of random data on a given platform, including Win32 0.003 2013-01-17 08:47:45 America/New_York [BUG FIXES] - ISAAC is now seeded from /dev/urandom instead of /dev/random to avoid blocking. urandom is sufficient for seeding a CPRNG that itself is generating salt to permute the actual secret key. 0.002 2013-01-15 23:06:47 America/New_York [BUG FIXES] - Specify MIME::Base64 3.12 as minimum for encode/decode_base64url 0.001 2013-01-10 22:07:12 America/New_York - First release Session-Storage-Secure-0.007/CONTRIBUTING000644 000765 000024 00000003254 12152265347 020070 0ustar00davidstaff000000 000000 CONTRIBUTING Thank you for considering contributing to this distribution. This file contains instructions that will help you work with the source code. The distribution is managed with Dist::Zilla. This means than many of the usual files you might expect are not in the repository, but are generated at release time (e.g. Makefile.PL). However, you can run tests directly using the 'prove' tool: $ prove -l $ prove -lv t/some_test_file.t For most distributions, 'prove' is entirely sufficent for you to test any patches you have. You may need to satisfy some dependencies. See the included META.json file for a list. If you install App::mymeta_requires from CPAN, it's easy to satisfy any that you are missing by piping the output to your favorite CPAN client: $ mymeta-requires | cpanm $ cpan `mymeta-requires` Likewise, much of the documentation Pod is generated at release time. Depending on the distribution, some documentation may be written in a Pod dialect called WikiDoc. (See Pod::WikiDoc on CPAN.) If you would like to submit a documentation edit, please limit yourself to the documentation you see. If you see typos or documentation issues in the generated docs, please email or open a bug ticket instead of patching. Dist::Zilla is a very powerful authoring tool, but requires a number of author-specific plugins. If you would like to use it for contributing, install it from CPAN, then run one of the following commands, depending on your CPAN client: $ cpan `dzil authordeps` $ dzil authordeps | cpanm Once installed, here are some dzil commands you might try: $ dzil build $ dzil test $ dzil xtest You can learn more about Dist::Zilla at http://dzil.org/ Session-Storage-Secure-0.007/dist.ini000644 000765 000024 00000001142 12152265347 017674 0ustar00davidstaff000000 000000 name = Session-Storage-Secure author = David Golden license = Apache_2_0 copyright_holder = David Golden copyright_year = 2013 [@DAGOLDEN] :version = 0.032 AutoMetaResources.bugtracker.rt = 0 AutoMetaResources.bugtracker.github = user:dagolden stopwords = AES stopwords = Don'ts stopwords = Fu stopwords = HMAC stopwords = Liu stopwords = MAC's stopwords = Rekeying stopwords = Sereal stopwords = al stopwords = authenticator stopwords = ciphertext stopwords = cryptographically stopwords = decrypting stopwords = et stopwords = login stopwords = scalability stopwords = unencrypted Session-Storage-Secure-0.007/lib/000755 000765 000024 00000000000 12152265347 017000 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/LICENSE000644 000765 000024 00000026354 12152265347 017251 0ustar00davidstaff000000 000000 This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Session-Storage-Secure-0.007/Makefile.PL000644 000765 000024 00000004020 12152265347 020200 0ustar00davidstaff000000 000000 use strict; use warnings; use 5.008001; use ExtUtils::MakeMaker 6.30; my %WriteMakefileArgs = ( "ABSTRACT" => "Encrypted, expiring, compressed, serialized session data with integrity", "AUTHOR" => "David Golden ", "BUILD_REQUIRES" => {}, "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.30" }, "DISTNAME" => "Session-Storage-Secure", "EXE_FILES" => [], "LICENSE" => "apache", "NAME" => "Session::Storage::Secure", "PREREQ_PM" => { "Carp" => 0, "Crypt::CBC" => 0, "Crypt::Rijndael" => 0, "Crypt::URandom" => 0, "Digest::SHA" => 0, "MIME::Base64" => "3.12", "Math::Random::ISAAC::XS" => 0, "Moo" => 0, "MooX::Types::MooseLike::Base" => "0.16", "Sereal::Decoder" => 0, "Sereal::Encoder" => 0, "String::Compare::ConstantTime" => 0, "namespace::clean" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "ExtUtils::MakeMaker" => 0, "File::Find" => 0, "File::Spec::Functions" => 0, "File::Temp" => 0, "List::Util" => 0, "Test::Deep" => 0, "Test::Fatal" => 0, "Test::More" => "0.96", "Test::Tolerant" => 0 }, "VERSION" => "0.007", "test" => { "TESTS" => "t/*.t" } ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { my $tr = delete $WriteMakefileArgs{TEST_REQUIRES}; my $br = $WriteMakefileArgs{BUILD_REQUIRES}; for my $mod ( keys %$tr ) { if ( exists $br->{$mod} ) { $br->{$mod} = $tr->{$mod} if $tr->{$mod} > $br->{$mod}; } else { $br->{$mod} = $tr->{$mod}; } } } unless ( eval { ExtUtils::MakeMaker->VERSION(6.56) } ) { my $br = delete $WriteMakefileArgs{BUILD_REQUIRES}; my $pp = $WriteMakefileArgs{PREREQ_PM}; for my $mod ( keys %$br ) { if ( exists $pp->{$mod} ) { $pp->{$mod} = $br->{$mod} if $br->{$mod} > $pp->{$mod}; } else { $pp->{$mod} = $br->{$mod}; } } } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Session-Storage-Secure-0.007/MANIFEST000644 000765 000024 00000000574 12152265347 017371 0ustar00davidstaff000000 000000 CONTRIBUTING Changes LICENSE MANIFEST META.json META.yml Makefile.PL README dist.ini lib/Session/Storage/Secure.pm perlcritic.rc t/00-compile.t t/00-report-prereqs.t t/basic.t t/errors.t xt/author/critic.t xt/author/pod-spell.t xt/release/distmeta.t xt/release/minimum-version.t xt/release/pod-coverage.t xt/release/pod-syntax.t xt/release/portability.t xt/release/test-version.t Session-Storage-Secure-0.007/META.json000644 000765 000024 00000005070 12152265347 017655 0ustar00davidstaff000000 000000 { "abstract" : "Encrypted, expiring, compressed, serialized session data with integrity", "author" : [ "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 4.300034, CPAN::Meta::Converter version 2.131490", "license" : [ "apache_2_0" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Session-Storage-Secure", "no_index" : { "directory" : [ "t", "xt", "examples", "corpus" ], "package" : [ "DB" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.30" } }, "develop" : { "requires" : { "Pod::Coverage::TrustPod" : "0", "Test::CPAN::Meta" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08" } }, "runtime" : { "requires" : { "Carp" : "0", "Crypt::CBC" : "0", "Crypt::Rijndael" : "0", "Crypt::URandom" : "0", "Digest::SHA" : "0", "MIME::Base64" : "3.12", "Math::Random::ISAAC::XS" : "0", "Moo" : "0", "MooX::Types::MooseLike::Base" : "0.16", "Sereal::Decoder" : "0", "Sereal::Encoder" : "0", "String::Compare::ConstantTime" : "0", "namespace::clean" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "ExtUtils::MakeMaker" : "0", "File::Find" : "0", "File::Spec::Functions" : "0", "File::Temp" : "0", "List::Util" : "0", "Test::Deep" : "0", "Test::Fatal" : "0", "Test::More" : "0.96", "Test::Tolerant" : "0" } } }, "provides" : { "Session::Storage::Secure" : { "file" : "lib/Session/Storage/Secure.pm", "version" : "0.007" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/dagolden/session-storage-secure/issues" }, "homepage" : "https://metacpan.org/release/Session-Storage-Secure", "repository" : { "type" : "git", "url" : "git://github.com/dagolden/session-storage-secure.git", "web" : "https://github.com/dagolden/session-storage-secure" } }, "version" : "0.007" } Session-Storage-Secure-0.007/META.yml000644 000765 000024 00000002512 12152265347 017503 0ustar00davidstaff000000 000000 --- abstract: 'Encrypted, expiring, compressed, serialized session data with integrity' author: - 'David Golden ' build_requires: ExtUtils::MakeMaker: 0 File::Find: 0 File::Spec::Functions: 0 File::Temp: 0 List::Util: 0 Test::Deep: 0 Test::Fatal: 0 Test::More: 0.96 Test::Tolerant: 0 configure_requires: ExtUtils::MakeMaker: 6.30 dynamic_config: 0 generated_by: 'Dist::Zilla version 4.300034, CPAN::Meta::Converter version 2.131490' license: apache meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: Session-Storage-Secure no_index: directory: - t - xt - examples - corpus package: - DB provides: Session::Storage::Secure: file: lib/Session/Storage/Secure.pm version: 0.007 requires: Carp: 0 Crypt::CBC: 0 Crypt::Rijndael: 0 Crypt::URandom: 0 Digest::SHA: 0 MIME::Base64: 3.12 Math::Random::ISAAC::XS: 0 Moo: 0 MooX::Types::MooseLike::Base: 0.16 Sereal::Decoder: 0 Sereal::Encoder: 0 String::Compare::ConstantTime: 0 namespace::clean: 0 perl: 5.008001 strict: 0 warnings: 0 resources: bugtracker: https://github.com/dagolden/session-storage-secure/issues homepage: https://metacpan.org/release/Session-Storage-Secure repository: git://github.com/dagolden/session-storage-secure.git version: 0.007 Session-Storage-Secure-0.007/perlcritic.rc000644 000765 000024 00000001032 12152265347 020714 0ustar00davidstaff000000 000000 severity = 5 verbose = 8 [Variables::ProhibitPunctuationVars] allow = $@ $! [TestingAndDebugging::ProhibitNoStrict] allow = refs # Turn these off [-BuiltinFunctions::ProhibitStringyEval] [-ControlStructures::ProhibitPostfixControls] [-ControlStructures::ProhibitUnlessBlocks] [-Documentation::RequirePodSections] [-InputOutput::ProhibitInteractiveTest] [-References::ProhibitDoubleSigils] [-RegularExpressions::RequireExtendedFormatting] [-InputOutput::ProhibitTwoArgOpen] # Turn this on [Lax::ProhibitStringyEval::ExceptForRequire] Session-Storage-Secure-0.007/README000644 000765 000024 00000026157 12152265347 017125 0ustar00davidstaff000000 000000 NAME Session::Storage::Secure - Encrypted, expiring, compressed, serialized session data with integrity VERSION version 0.007 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 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 Crypt::URandom. 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 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 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 * Murdoch, Stephen J., Hardened Stateless Session Cookies * Fu, Kevin, et al., Dos and Don'ts of Client Authentication on the Web 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 . 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. git clone git://github.com/dagolden/session-storage-secure.git AUTHOR David Golden 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 Session-Storage-Secure-0.007/t/000755 000765 000024 00000000000 12152265347 016475 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/xt/000755 000765 000024 00000000000 12152265347 016665 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/xt/author/000755 000765 000024 00000000000 12152265347 020167 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/xt/release/000755 000765 000024 00000000000 12152265347 020305 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/xt/release/distmeta.t000644 000765 000024 00000000217 12152265347 022304 0ustar00davidstaff000000 000000 #!perl use Test::More; eval "use Test::CPAN::Meta"; plan skip_all => "Test::CPAN::Meta required for testing META.yml" if $@; meta_yaml_ok(); Session-Storage-Secure-0.007/xt/release/minimum-version.t000644 000765 000024 00000000266 12152265347 023634 0ustar00davidstaff000000 000000 #!perl use Test::More; eval "use Test::MinimumVersion"; plan skip_all => "Test::MinimumVersion required for testing minimum versions" if $@; all_minimum_version_ok( qq{5.010} ); Session-Storage-Secure-0.007/xt/release/pod-coverage.t000644 000765 000024 00000000527 12152265347 023051 0ustar00davidstaff000000 000000 #!perl use Test::More; eval "use Test::Pod::Coverage 1.08"; plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage" if $@; eval "use Pod::Coverage::TrustPod"; plan skip_all => "Pod::Coverage::TrustPod required for testing POD coverage" if $@; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); Session-Storage-Secure-0.007/xt/release/pod-syntax.t000644 000765 000024 00000000212 12152265347 022573 0ustar00davidstaff000000 000000 #!perl use Test::More; eval "use Test::Pod 1.41"; plan skip_all => "Test::Pod 1.41 required for testing POD" if $@; all_pod_files_ok(); Session-Storage-Secure-0.007/xt/release/portability.t000644 000765 000024 00000000332 12152265347 023032 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::More; eval 'use Test::Portability::Files'; plan skip_all => 'Test::Portability::Files required for testing portability' if $@; options(test_one_dot => 0); run_tests(); Session-Storage-Secure-0.007/xt/release/test-version.t000644 000765 000024 00000000643 12152265347 023137 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::Version 0.002004 BEGIN { eval "use Test::Version; 1;" or die $@; } my @imports = ( 'version_all_ok' ); my $params = { is_strict => 0, has_version => 1, }; push @imports, $params if version->parse( $Test::Version::VERSION ) >= version->parse('1.002'); Test::Version->import(@imports); version_all_ok; done_testing; Session-Storage-Secure-0.007/xt/author/critic.t000644 000765 000024 00000000435 12152265347 021633 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::More; use English qw(-no_match_vars); eval "use Test::Perl::Critic"; plan skip_all => 'Test::Perl::Critic required to criticise code' if $@; Test::Perl::Critic->import( -profile => "perlcritic.rc" ) if -e "perlcritic.rc"; all_critic_ok(); Session-Storage-Secure-0.007/xt/author/pod-spell.t000644 000765 000024 00000000673 12152265347 022261 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::PodSpelling 2.006000 eval "use Test::Spelling 0.12; use Pod::Wordlist::hanekomu; 1" or die $@; add_stopwords(); all_pod_files_spelling_ok( qw( bin lib ) ); __DATA__ AES Don'ts Fu HMAC Liu MAC's Rekeying Sereal al authenticator ciphertext cryptographically decrypting et login scalability unencrypted David Golden dagolden lib Session Storage Secure Session-Storage-Secure-0.007/t/00-compile.t000644 000765 000024 00000003100 12152265347 020521 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::More; use File::Find; use File::Temp qw{ tempdir }; my @modules; find( sub { return if $File::Find::name !~ /\.pm\z/; my $found = $File::Find::name; $found =~ s{^lib/}{}; $found =~ s{[/\\]}{::}g; $found =~ s/\.pm$//; # nothing to skip push @modules, $found; }, 'lib', ); sub _find_scripts { my $dir = shift @_; my @found_scripts = (); find( sub { return unless -f; my $found = $File::Find::name; # nothing to skip open my $FH, '<', $_ or do { note( "Unable to open $found in ( $! ), skipping" ); return; }; my $shebang = <$FH>; return unless $shebang =~ /^#!.*?\bperl\b\s*$/; push @found_scripts, $found; }, $dir, ); return @found_scripts; } my @scripts; do { push @scripts, _find_scripts($_) if -d $_ } for qw{ bin script scripts }; my $plan = scalar(@modules) + scalar(@scripts); $plan ? (plan tests => $plan) : (plan skip_all => "no tests to run"); { # fake home for cpan-testers local $ENV{HOME} = tempdir( CLEANUP => 1 ); like( qx{ $^X -Ilib -e "require $_; print '$_ ok'" }, qr/^\s*$_ ok/s, "$_ loaded ok" ) for sort @modules; SKIP: { eval "use Test::Script 1.05; 1;"; skip "Test::Script needed to test script compilation", scalar(@scripts) if $@; foreach my $file ( @scripts ) { my $script = $file; $script =~ s!.*/!!; script_compiles( $file, "$script script compiles" ); } } } Session-Storage-Secure-0.007/t/00-report-prereqs.t000644 000765 000024 00000003445 12152265347 022077 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec::Functions; use List::Util qw/max/; my @modules = qw( Carp Crypt::CBC Crypt::Rijndael Crypt::URandom Digest::SHA ExtUtils::MakeMaker File::Find File::Spec::Functions File::Temp List::Util MIME::Base64 Math::Random::ISAAC::XS Moo MooX::Types::MooseLike::Base Sereal::Decoder Sereal::Encoder String::Compare::ConstantTime Test::Deep Test::Fatal Test::More Test::Tolerant namespace::clean perl strict warnings ); # replace modules with dynamic results from MYMETA.json if we can # (hide CPAN::Meta from prereq scanner) my $cpan_meta = "CPAN::Meta"; if ( -f "MYMETA.json" && eval "require $cpan_meta" ) { ## no critic if ( my $meta = eval { CPAN::Meta->load_file("MYMETA.json") } ) { my $prereqs = $meta->prereqs; delete $prereqs->{develop}; my %uniq = map {$_ => 1} map { keys %$_ } map { values %$_ } values %$prereqs; $uniq{$_} = 1 for @modules; # don't lose any static ones @modules = sort keys %uniq; } } my @reports = [qw/Version Module/]; for my $mod ( @modules ) { next if $mod eq 'perl'; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e catfile($_, $file) } @INC; if ( $prefix ) { my $ver = MM->parse_version( catfile($prefix, $file) ); $ver = "undef" unless defined $ver; # Newer MM should do this anyway push @reports, [$ver, $mod]; } else { push @reports, ["missing", $mod]; } } if ( @reports ) { my $vl = max map { length $_->[0] } @reports; my $ml = max map { length $_->[1] } @reports; splice @reports, 1, 0, ["-" x $vl, "-" x $ml]; diag "Prerequisite Report:\n", map {sprintf(" %*s %*s\n",$vl,$_->[0],-$ml,$_->[1])} @reports; } pass; # vim: ts=2 sts=2 sw=2 et: Session-Storage-Secure-0.007/t/basic.t000644 000765 000024 00000011600 12152265347 017741 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; use Test::More 0.96; use Test::Deep qw/!blessed/; use Test::Tolerant; use MIME::Base64 qw/encode_base64url/; use Session::Storage::Secure; my $data = { foo => 'bar', baz => 'bam', }; my $secret = "serenade viscount secretary frail"; sub _gen_store { my ($config) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; my $store = Session::Storage::Secure->new( secret_key => $secret, %{ $config || {} }, ); ok( $store, "created a storage object" ); return $store; } sub _replace { my ( $string, $index, $value ) = @_; my @parts = split qr/~/, $string; $parts[$index] = $value; return join "~", @parts; } subtest "defaults" => sub { my $store = _gen_store; my $encoded = $store->encode($data); like( $encoded, qr/^\d+~~/, "no expiration set" ); my $decoded = $store->decode($encoded); cmp_deeply( $decoded, $data, "roundtrip" ); }; subtest "no data" => sub { my $store = _gen_store; my $encoded = $store->encode(); like( $encoded, qr/^\d+~~/, "no expiration set" ); my $decoded = $store->decode($encoded); cmp_deeply( $decoded, {}, "undefined data treated as empty hashref" ); }; subtest "future expiration" => sub { my $store = _gen_store; my $expires = time + 3600; my $encoded = $store->encode( $data, $expires ); my ($got) = $encoded =~ m/~(\d+)~/; is( $got, $expires, "expiration timestamp correct" ); my $decoded = $store->decode($encoded); cmp_deeply( $decoded, $data, "roundtrip" ); }; subtest "past expiration" => sub { my $store = _gen_store; my $expires = time - 3600; my $encoded = $store->encode( $data, $expires ); my ($got) = $encoded =~ m/~(\d+)~/; is( $got, $expires, "expiration timestamp correct" ); my $decoded = $store->decode($encoded); is( $decoded, undef, "expired data decodes to undef" ); }; subtest "future default duration" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = $store->encode($data); my ($got) = $encoded =~ m/~(\d+)~/; is_tol( $got - time, [qw/3550 to 3605/], "expiration in correct range" ); my $decoded = $store->decode($encoded); cmp_deeply( $decoded, $data, "roundtrip" ); }; subtest "past default duration" => sub { my $store = _gen_store( { default_duration => -3600 } ); my $encoded = $store->encode($data); my ($got) = $encoded =~ m/~(\d+)~/; is_tol( $got - time, [qw/-3605 to -3550/], "expiration in correct range" ); my $decoded = $store->decode($encoded); is( $decoded, undef, "expired data decodes to undef" ); }; subtest "changed secret key" => sub { my $store = _gen_store; my $encoded = $store->encode($data); my $store2 = _gen_store( { secret_key => "unpopular deface inflamed belay" } ); my $decoded = $store2->decode($encoded); is( $decoded, undef, "changed key decodes to undef" ); }; subtest "modified salt" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = _replace( $store->encode($data), 0, int( rand() * 2**31 ) ); my $decoded = $store->decode($encoded); is( $decoded, undef, "changed salt decodes to undef" ); }; subtest "modified expiration" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = _replace( $store->encode($data), 1, time + 86400 ); my $decoded = $store->decode($encoded); is( $decoded, undef, "changed expiration decodes to undef" ); }; subtest "modified ciphertext" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = _replace( $store->encode($data), 2, encode_base64url( pack( "l*", rand, rand, rand, rand ) ) ); my $decoded = $store->decode($encoded); is( $decoded, undef, "changed ciphertext decodes to undef" ); }; subtest "modified mac" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = _replace( $store->encode($data), 3, encode_base64url( pack( "l*", rand, rand, rand, rand ) ) ); my $decoded = $store->decode($encoded); is( $decoded, undef, "changed mac decodes to undef" ); }; subtest "truncated mac" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = _replace( $store->encode($data), 3, "" ); my $decoded = $store->decode($encoded); is( $decoded, undef, "truncated mac decodes to undef" ); }; subtest "garbage encoded" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $encoded = encode_base64url( pack( "l*", rand, rand, rand, rand ) ); my $decoded = $store->decode($encoded); is( $decoded, undef, "garbage decodes to undef" ); }; subtest "empty encoded" => sub { my $store = _gen_store( { default_duration => 3600 } ); my $decoded = $store->decode(''); is( $decoded, undef, "empty string decodes to undef" ); }; done_testing; # # This file is part of Session-Storage-Secure # # This software is Copyright (c) 2013 by David Golden. # # This is free software, licensed under: # # The Apache License, Version 2.0, January 2004 # Session-Storage-Secure-0.007/t/errors.t000644 000765 000024 00000002001 12152265347 020167 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; use Test::More 0.96; use Test::Fatal; use Session::Storage::Secure; my $data = { foo => 'bar', baz => 'bam', }; my $secret = "serenade viscount secretary frail"; sub _gen_store { my ($config) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; my $store = Session::Storage::Secure->new( secret_key => $secret, %{ $config || {} }, ); ok( $store, "created a storage object" ); return $store; } sub _replace { my ( $string, $index, $value ) = @_; my @parts = split qr/~/, $string; $parts[$index] = $value; return join "~", @parts; } subtest "bad data" => sub { my $store = _gen_store; like( exception { $store->encode( { foo => bless {} } ) }, qr/Encoding error/, "Invalid data throws encoding error", ); }; done_testing; # # This file is part of Session-Storage-Secure # # This software is Copyright (c) 2013 by David Golden. # # This is free software, licensed under: # # The Apache License, Version 2.0, January 2004 # Session-Storage-Secure-0.007/lib/Session/000755 000765 000024 00000000000 12152265347 020423 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/lib/Session/Storage/000755 000765 000024 00000000000 12152265347 022027 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.007/lib/Session/Storage/Secure.pm000644 000765 000024 00000035353 12152265347 023624 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; package Session::Storage::Secure; # ABSTRACT: Encrypted, expiring, compressed, serialized session data with integrity our $VERSION = '0.007'; # VERSION use Carp (qw/croak/); use Crypt::CBC (); use Crypt::Rijndael (); use Crypt::URandom (qw/urandom/); use Digest::SHA (qw/hmac_sha256/); use Math::Random::ISAAC::XS (); use MIME::Base64 3.12 (qw/encode_base64url decode_base64url/); use Sereal::Encoder (); use Sereal::Decoder (); use String::Compare::ConstantTime qw/equals/; use namespace::clean; use Moo; use MooX::Types::MooseLike::Base 0.16 qw(:all); #--------------------------------------------------------------------------# # Attributes #--------------------------------------------------------------------------# has secret_key => ( is => 'ro', isa => Str, required => 1, ); has default_duration => ( is => 'ro', isa => Int, predicate => 1, ); has _encoder => ( is => 'lazy', isa => InstanceOf ['Sereal::Encoder'], handles => { '_freeze' => 'encode' }, ); sub _build__encoder { my ($self) = @_; return Sereal::Encoder->new( { snappy => 1, croak_on_bless => 1, } ); } has _decoder => ( is => 'lazy', isa => InstanceOf ['Sereal::Decoder'], handles => { '_thaw' => 'decode' }, ); sub _build__decoder { my ($self) = @_; return Sereal::Decoder->new( { refuse_objects => 1, validate_utf8 => 1, } ); } has _rng => ( is => 'lazy', isa => InstanceOf ['Math::Random::ISAAC::XS'], handles => { '_irand' => 'irand' }, ); sub _build__rng { my ($self) = @_; return Math::Random::ISAAC::XS->new( map { unpack( "N", urandom(4) ) } 1 .. 256 ); } sub encode { my ( $self, $data, $expires ) = @_; $data = {} unless defined $data; # If expiration is set, we want to check it and possibly clear data; # if not set, we might add an expiration based on default_duration if ( defined $expires ) { $data = {} if $expires < time; } else { $expires = $self->has_default_duration ? time + $self->default_duration : ""; } # Random salt used to derive unique encryption/MAC key for each cookie my $salt = $self->_irand; my $key = hmac_sha256( $salt, $self->secret_key ); my $cbc = Crypt::CBC->new( -key => $key, -cipher => 'Rijndael' ); my ( $ciphertext, $mac ); eval { $ciphertext = encode_base64url( $cbc->encrypt( $self->_freeze($data) ) ); $mac = encode_base64url( hmac_sha256( "$expires~$ciphertext", $key ) ); }; croak "Encoding error: $@" if $@; return join( "~", $salt, $expires, $ciphertext, $mac ); } sub decode { my ( $self, $string ) = @_; return unless length $string; # Having a string implies at least salt; expires is optional; rest required my ( $salt, $expires, $ciphertext, $mac ) = split qr/~/, $string; return unless defined($ciphertext) && length($ciphertext); return unless defined($mac) && length($mac); # Check MAC integrity and expiration my $key = hmac_sha256( $salt, $self->secret_key ); my $check_mac = eval { encode_base64url( hmac_sha256( "$expires~$ciphertext", $key ) ) }; return unless defined($check_mac) && length($check_mac) && equals( $check_mac, $mac ); # constant time comparision return if length($expires) && $expires < time; # Decrypt and deserialize the data my $cbc = Crypt::CBC->new( -key => $key, -cipher => 'Rijndael' ); my $data; eval { $self->_thaw( $cbc->decrypt( decode_base64url($ciphertext) ), $data ) }; croak "Decoding error: $@" if $@; return $data; } 1; # vim: ts=4 sts=4 sw=4 et: __END__ =pod =encoding utf-8 =head1 NAME Session::Storage::Secure - Encrypted, expiring, compressed, serialized session data with integrity =head1 VERSION version 0.007 =head1 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 ); =head1 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: =over 4 =item * Data serialization and compression using L =item * Data encryption using AES with a unique derived key per encoded session =item * Enforced expiration timestamp (optional) =item * Integrity protected with a message authentication code (MAC) =back The storage protocol used in this module is based heavily on L 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 C. This weakens protection against replay attacks if an attacker can break the SSL session key and intercept messages. Using C and C 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 C 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 L, seeded from L. The HMAC algorithm is C from L. Encryption is done by L using L (AES). The ciphertext and MAC's in the cookie are Base64 encoded by L. During session retrieval, if the MAC does not authenticate or if the expiration is set and in the past, the session will be discarded. =head1 ATTRIBUTES =head2 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. =head2 default_duration Number of seconds for which the session may be considered valid. If an expiration is not provided to C, 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. =head1 METHODS =head2 encode my $string = $store->encode( $data, $expires ); The C<$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 C<$expires> argument should be the session expiration time expressed as epoch seconds. If the C<$expires> time is in the past, the C<$data> argument is cleared and an empty hash reference is encoded and returned. If no C<$expires> is given, then if the C 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. =head2 decode my $data = $store->decode( $string ); The C<$string> argument must be the output of C. 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. =for Pod::Coverage method_names_here =head1 LIMITATIONS =head2 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. =head2 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 L for serialization and enables the C compression option. Sereal plus Snappy appears to be one of the fastest and most compact serialization options for Perl, according to the L 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. =head2 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. =head1 SECURITY Storing encrypted session data within a browser cookie avoids latency and overhead of backend session storage, but has several additional security considerations. =head2 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. =head2 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 C or C to limit the window of opportunity for such replay attacks. =head2 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 L 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. =head1 SEE ALSO Papers on secure cookies and cookie session storage: =over 4 =item * Liu, Alex X., et al., L =item * Murdoch, Stephen J., L =item * Fu, Kevin, et al., L =back CPAN modules implementing cookie session storage: =over 4 =item * L -- encryption only =item * L -- Dancer 1, encryption only =item * L -- Dancer 2, forthcoming, based on this module =item * L -- encryption only =item * L -- MAC only =item * L -- MAC only =item * L -- really just a framework and you provide the guts with callbacks =back Related CPAN modules that offer frameworks for serializing and encrypting data, but without features relevant for sessions like expiration and unique keying. =over 4 =item * L =item * L =back =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone git://github.com/dagolden/session-storage-secure.git =head1 AUTHOR David Golden =head1 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 =cut