Session-Storage-Secure-0.010/000755 000765 000024 00000000000 12331477120 016215 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/Changes000644 000765 000024 00000003745 12331477120 017521 0ustar00davidstaff000000 000000 Revision history for Session-Storage-Secure 0.010 2014-05-04 13:52:13-04:00 America/New_York [ADDED] - Added support for customizing options to Sereal encoder and decoder, i.e. to allow object serialization for those willing to accept the risks of doing so. (Thanks to Breno de Oliveira for inspiration to do this.) 0.009 2014-04-17 17:15:25-04:00 America/New_York [FIXED] - Fixed bug that would cause custom encoding tests to fail intermittently 0.008 2014-04-17 16:29:50-04:00 America/New_York [ADDED] - Added support for keeping an array of old keys for decryption (Tom Hukins) - Added support for replacing MIME::Base64 encoding with user-specified transport encoding/decoding, possibly with a custom separator [INTERNAL] - Update repository support and meta files 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.010/CONTRIBUTING000644 000765 000024 00000006512 12331477120 020053 0ustar00davidstaff000000 000000 ## HOW TO CONTRIBUTE 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). Generally, **you do not need Dist::Zilla to contribute patches**. You do need Dist::Zilla to create a tarball and/or install from the repository. See below for guidance. ### Getting dependencies See the included `cpanfile` file for a list of dependencies. If you have App::cpanminus 1.6 or later installed, you can use `cpanm` to satisfy dependencies like this: $ cpanm --installdeps . Otherwise, you can install Module::CPANfile 1.0002 or later and then satisfy dependencies with the regular `cpan` client and `cpanfile-dump`: $ cpan `cpanfile-dump` ### Running tests You can run tests directly using the `prove` tool: $ prove -l $ prove -lv t/some_test_file.t For most of my distributions, `prove` is entirely sufficient for you to test any patches you have. I use `prove` for 99% of my testing during development. ### Code style and tidying Please try to match any existing coding style. If there is a `.perltidyrc` file, please install Perl::Tidy and use perltidy before submitting patches. If there is a `tidyall.ini` file, you can also install Code::TidyAll and run `tidyall` on a file or `tidyall -a` to tidy all files. ### Patching documentation Much of the documentation Pod is generated at release time. Depending on the distribution, some of my 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. ### Installing from the repository If you want to install directly from the repository, you need to have Dist::Zilla installed (see below). If this is a burden to you, I welcome patches against a CPAN tarball instead of the repository. ### Installing and using Dist::Zilla Dist::Zilla is a very powerful authoring tool, optimized for maintaining a large number of distributions with a high degree of automation, but it has a large dependency chain, a bit of a learning curve and requires a number of author-specific plugins. To install it from CPAN, I recommend one of the following approaches for the quickest installation: # using CPAN.pm, but bypassing non-functional pod tests $ cpan TAP::Harness::Restricted $ PERL_MM_USE_DEFAULT=1 HARNESS_CLASS=TAP::Harness::Restricted cpan Dist::Zilla # using cpanm, bypassing *all* tests $ cpanm -n Dist::Zilla In either case, it's probably going to take about 10 minutes. Go for a walk, go get a cup of your favorite beverage, take a bathroom break, or whatever. When you get back, Dist::Zilla should be ready for you. Then you need to install any plugins specific to this distribution: $ cpan `dzil authordeps` $ dzil authordeps | cpanm Once installed, here are some dzil commands you might try: $ dzil build $ dzil test $ dzil xtest To install from the repository, use: $ dzil install You can learn more about Dist::Zilla at http://dzil.org/ Session-Storage-Secure-0.010/cpanfile000644 000765 000024 00000002707 12331477120 017727 0ustar00davidstaff000000 000000 requires "Carp" => "0"; requires "Crypt::CBC" => "0"; requires "Crypt::Rijndael" => "0"; requires "Crypt::URandom" => "0"; requires "Digest::SHA" => "0"; requires "MIME::Base64" => "3.12"; requires "Math::Random::ISAAC::XS" => "0"; requires "Moo" => "0"; requires "MooX::Types::MooseLike::Base" => "0.16"; requires "Sereal::Decoder" => "0"; requires "Sereal::Encoder" => "0"; requires "String::Compare::ConstantTime" => "0"; requires "namespace::clean" => "0"; requires "perl" => "5.008001"; requires "strict" => "0"; requires "warnings" => "0"; on 'test' => sub { requires "ExtUtils::MakeMaker" => "0"; requires "File::Spec::Functions" => "0"; requires "List::Util" => "0"; requires "Test::Deep" => "0"; requires "Test::Fatal" => "0"; requires "Test::More" => "0.96"; requires "Test::Tolerant" => "0"; requires "version" => "0"; }; on 'test' => sub { recommends "CPAN::Meta" => "0"; recommends "CPAN::Meta::Requirements" => "2.120900"; }; on 'configure' => sub { requires "ExtUtils::MakeMaker" => "6.17"; }; on 'develop' => sub { requires "Dist::Zilla" => "5.015"; requires "Dist::Zilla::PluginBundle::DAGOLDEN" => "0.060"; requires "File::Spec" => "0"; requires "File::Temp" => "0"; requires "IO::Handle" => "0"; requires "IPC::Open3" => "0"; requires "Pod::Coverage::TrustPod" => "0"; requires "Test::CPAN::Meta" => "0"; requires "Test::More" => "0"; requires "Test::Pod" => "1.41"; requires "Test::Pod::Coverage" => "1.08"; }; Session-Storage-Secure-0.010/dist.ini000644 000765 000024 00000001012 12331477120 017653 0ustar00davidstaff000000 000000 name = Session-Storage-Secure author = David Golden license = Apache_2_0 copyright_holder = David Golden copyright_year = 2013 [@DAGOLDEN] :version = 0.060 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.010/lib/000755 000765 000024 00000000000 12331477120 016763 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/LICENSE000644 000765 000024 00000026354 12331477120 017234 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.010/Makefile.PL000644 000765 000024 00000004305 12331477120 020171 0ustar00davidstaff000000 000000 # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.015. use strict; use warnings; use 5.008001; use ExtUtils::MakeMaker 6.17; my %WriteMakefileArgs = ( "ABSTRACT" => "Encrypted, expiring, compressed, serialized session data with integrity", "AUTHOR" => "David Golden ", "BUILD_REQUIRES" => {}, "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.17" }, "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::Spec::Functions" => 0, "List::Util" => 0, "Test::Deep" => 0, "Test::Fatal" => 0, "Test::More" => "0.96", "Test::Tolerant" => 0, "version" => 0 }, "VERSION" => "0.010", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Carp" => 0, "Crypt::CBC" => 0, "Crypt::Rijndael" => 0, "Crypt::URandom" => 0, "Digest::SHA" => 0, "ExtUtils::MakeMaker" => 0, "File::Spec::Functions" => 0, "List::Util" => 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, "Test::Deep" => 0, "Test::Fatal" => 0, "Test::More" => "0.96", "Test::Tolerant" => 0, "namespace::clean" => 0, "strict" => 0, "version" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Session-Storage-Secure-0.010/MANIFEST000644 000765 000024 00000000767 12331477120 017360 0ustar00davidstaff000000 000000 # This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.015. CONTRIBUTING Changes LICENSE MANIFEST META.json META.yml Makefile.PL README cpanfile dist.ini lib/Session/Storage/Secure.pm perlcritic.rc t/00-report-prereqs.t t/basic.t t/encoding.t t/errors.t tidyall.ini xt/author/00-compile.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.010/META.json000644 000765 000024 00000005766 12331477120 017654 0ustar00davidstaff000000 000000 { "abstract" : "Encrypted, expiring, compressed, serialized session data with integrity", "author" : [ "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.015, CPAN::Meta::Converter version 2.141170", "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.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5.015", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.060", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Test::CPAN::Meta" : "0", "Test::More" : "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" : { "recommends" : { "CPAN::Meta" : "0", "CPAN::Meta::Requirements" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec::Functions" : "0", "List::Util" : "0", "Test::Deep" : "0", "Test::Fatal" : "0", "Test::More" : "0.96", "Test::Tolerant" : "0", "version" : "0" } } }, "provides" : { "Session::Storage::Secure" : { "file" : "lib/Session/Storage/Secure.pm", "version" : "0.010" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/dagolden/Session-Storage-Secure/issues" }, "homepage" : "https://github.com/dagolden/Session-Storage-Secure", "repository" : { "type" : "git", "url" : "https://github.com/dagolden/Session-Storage-Secure.git", "web" : "https://github.com/dagolden/Session-Storage-Secure" } }, "version" : "0.010", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Tom Hukins " ] } Session-Storage-Secure-0.010/META.yml000644 000765 000024 00000002673 12331477120 017476 0ustar00davidstaff000000 000000 --- abstract: 'Encrypted, expiring, compressed, serialized session data with integrity' author: - 'David Golden ' build_requires: ExtUtils::MakeMaker: '0' File::Spec::Functions: '0' List::Util: '0' Test::Deep: '0' Test::Fatal: '0' Test::More: '0.96' Test::Tolerant: '0' version: '0' configure_requires: ExtUtils::MakeMaker: '6.17' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.015, CPAN::Meta::Converter version 2.141170' 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.010' 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://github.com/dagolden/Session-Storage-Secure repository: https://github.com/dagolden/Session-Storage-Secure.git version: '0.010' x_authority: cpan:DAGOLDEN x_contributors: - 'Tom Hukins ' Session-Storage-Secure-0.010/perlcritic.rc000644 000765 000024 00000001166 12331477120 020707 0ustar00davidstaff000000 000000 severity = 5 verbose = 8 [Variables::ProhibitPunctuationVars] allow = $@ $! [TestingAndDebugging::ProhibitNoStrict] allow = refs [Variables::ProhibitEvilVariables] variables = $DB::single # Turn these off [-BuiltinFunctions::ProhibitStringyEval] [-ControlStructures::ProhibitPostfixControls] [-ControlStructures::ProhibitUnlessBlocks] [-Documentation::RequirePodSections] [-InputOutput::ProhibitInteractiveTest] [-References::ProhibitDoubleSigils] [-RegularExpressions::RequireExtendedFormatting] [-InputOutput::ProhibitTwoArgOpen] [-Modules::ProhibitEvilModules] # Turn this on [Lax::ProhibitStringyEval::ExceptForRequire] Session-Storage-Secure-0.010/README000644 000765 000024 00000031443 12331477120 017102 0ustar00davidstaff000000 000000 NAME Session::Storage::Secure - Encrypted, expiring, compressed, serialized session data with integrity VERSION version 0.010 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 (with the unfortunate side effect of revealing user names and prohibiting 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 an extra step 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 by default. 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 session expiration is not capped. old_secrets An optional array reference of strings containing old secret keys no longer used for encryption but still supported for decrypting session data. separator A character used to separate fields. It defaults to "~". sereal_encoder_options A hash reference with constructor arguments for Sereal::Encoder. Defaults to "{ snappy => 1, croak_on_bless => 1 }". sereal_decoder_options A hash reference with constructor arguments for Sereal::Decoder. Defaults to "{ refuse_objects => 1, validate_utf8 => 1 }". transport_encoder A code reference to convert binary data elements (the encrypted data and the MAC) into a transport-safe form. Defaults to MIME::Base64::encode_base64url. The output must not include the "separator" attribute used to delimit fields. transport_decoder A code reference to extract binary data (the encrypted data and the MAC) from a transport-safe form. It must be the complement to "encode". Defaults to MIME::Base64::decode_base64url. METHODS encode my $string = $store->encode( $data, $expires ); The $data argument should be a reference to a data structure. By default, it must not contain objects. (See "Objects not stored by default" for rationale and alternatives.) 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 protected via the "transport_encoder" attribute. 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 unless the "old_secrets" attribute contains old encryption keys still used for decryption. 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 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. Alternatively, applications can change "sereal_encoder_options" and "sereal_decoder_options" to allow object serialization or other object transformations and accept the risks of doing so. 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 https://github.com/dagolden/Session-Storage-Secure.git AUTHOR David Golden CONTRIBUTOR Tom Hukins 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.010/t/000755 000765 000024 00000000000 12331477120 016460 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/tidyall.ini000644 000765 000024 00000000240 12331477120 020354 0ustar00davidstaff000000 000000 ; Install Code::TidyAll ; run "tidyall -a" to tidy all files ; run "tidyall -g" to tidy only files modified from git [PerlTidy] select = {lib,t}/**/*.{pl,pm,t} Session-Storage-Secure-0.010/xt/000755 000765 000024 00000000000 12331477120 016650 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/xt/author/000755 000765 000024 00000000000 12331477120 020152 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/xt/release/000755 000765 000024 00000000000 12331477120 020270 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/xt/release/distmeta.t000644 000765 000024 00000000172 12331477120 022267 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::MetaTests. use Test::CPAN::Meta; meta_yaml_ok(); Session-Storage-Secure-0.010/xt/release/minimum-version.t000644 000765 000024 00000000266 12331477120 023617 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.010/xt/release/pod-coverage.t000644 000765 000024 00000000334 12331477120 023030 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::PodCoverageTests. use Test::Pod::Coverage 1.08; use Pod::Coverage::TrustPod; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); Session-Storage-Secure-0.010/xt/release/pod-syntax.t000644 000765 000024 00000000220 12331477120 022555 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Session-Storage-Secure-0.010/xt/release/portability.t000644 000765 000024 00000000332 12331477120 023015 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.010/xt/release/test-version.t000644 000765 000024 00000000643 12331477120 023122 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.010/xt/author/00-compile.t000644 000765 000024 00000002050 12331477120 022201 0ustar00davidstaff000000 000000 use 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.040 use Test::More tests => 1 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'Session/Storage/Secure.pm' ); # fake home for cpan-testers use File::Temp; local $ENV{HOME} = File::Temp::tempdir( CLEANUP => 1 ); my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') if $ENV{AUTHOR_TESTING}; Session-Storage-Secure-0.010/xt/author/critic.t000644 000765 000024 00000000435 12331477120 021616 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.010/xt/author/pod-spell.t000644 000765 000024 00000000654 12331477120 022243 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::PodSpelling 2.006007 use Test::Spelling 0.12; use Pod::Wordlist; 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 Tom Hukins tom lib Session Storage Secure Session-Storage-Secure-0.010/t/00-report-prereqs.t000644 000765 000024 00000015376 12331477120 022070 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.013 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec::Functions; use List::Util qw/max/; use version; # hide optional CPAN::Meta modules from prereq scanner # and check if they are available my $cpan_meta = "CPAN::Meta"; my $cpan_meta_req = "CPAN::Meta::Requirements"; my $HAS_CPAN_META = eval "require $cpan_meta"; ## no critic my $HAS_CPAN_META_REQ = eval "require $cpan_meta_req; $cpan_meta_req->VERSION('2.120900')"; # Verify requirements? my $DO_VERIFY_PREREQS = 1; sub _merge_requires { my ($collector, $prereqs) = @_; for my $phase ( qw/configure build test runtime develop/ ) { next unless exists $prereqs->{$phase}; if ( my $req = $prereqs->{$phase}{'requires'} ) { my $cmr = CPAN::Meta::Requirements->from_string_hash( $req ); $collector->add_requirements( $cmr ); } } } my %include = map {; $_ => 1 } qw( ); my %exclude = map {; $_ => 1 } qw( ); # Add static prereqs to the included modules list my $static_prereqs = do { my $x = { 'configure' => { 'requires' => { 'ExtUtils::MakeMaker' => '6.17' } }, 'develop' => { 'requires' => { 'Dist::Zilla' => '5.015', 'Dist::Zilla::PluginBundle::DAGOLDEN' => '0.060', 'File::Spec' => '0', 'File::Temp' => '0', 'IO::Handle' => '0', 'IPC::Open3' => '0', 'Pod::Coverage::TrustPod' => '0', 'Test::CPAN::Meta' => '0', 'Test::More' => '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' => { 'recommends' => { 'CPAN::Meta' => '0', 'CPAN::Meta::Requirements' => '2.120900' }, 'requires' => { 'ExtUtils::MakeMaker' => '0', 'File::Spec::Functions' => '0', 'List::Util' => '0', 'Test::Deep' => '0', 'Test::Fatal' => '0', 'Test::More' => '0.96', 'Test::Tolerant' => '0', 'version' => '0' } } }; $x; }; delete $static_prereqs->{develop} if not $ENV{AUTHOR_TESTING}; $include{$_} = 1 for map { keys %$_ } map { values %$_ } values %$static_prereqs; # Merge requirements for major phases (if we can) my $all_requires; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META_REQ ) { $all_requires = $cpan_meta_req->new; _merge_requires($all_requires, $static_prereqs); } # Add dynamic prereqs to the included modules list (if we can) my ($source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; if ( $source && $HAS_CPAN_META ) { if ( my $meta = eval { CPAN::Meta->load_file($source) } ) { my $dynamic_prereqs = $meta->prereqs; delete $dynamic_prereqs->{develop} if not $ENV{AUTHOR_TESTING}; $include{$_} = 1 for map { keys %$_ } map { values %$_ } values %$dynamic_prereqs; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META_REQ ) { _merge_requires($all_requires, $dynamic_prereqs); } } } else { $source = 'static metadata'; } my @modules = sort grep { ! $exclude{$_} } keys %include; my @reports = [qw/Version Module/]; my @dep_errors; my $req_hash = defined($all_requires) ? $all_requires->as_string_hash : {}; 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]; if ( $DO_VERIFY_PREREQS && $all_requires ) { my $req = $req_hash->{$mod}; if ( defined $req && length $req ) { if ( ! defined eval { version->parse($ver) } ) { push @dep_errors, "$mod version '$ver' cannot be parsed (version '$req' required)"; } elsif ( ! $all_requires->accepts_module( $mod => $ver ) ) { push @dep_errors, "$mod version '$ver' is not in required range '$req'"; } } } } else { push @reports, ["missing", $mod]; if ( $DO_VERIFY_PREREQS && $all_requires ) { my $req = $req_hash->{$mod}; if ( defined $req && length $req ) { push @dep_errors, "$mod is not installed (version '$req' required)"; } } } } 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 "\nVersions for all modules listed in $source (including optional ones):\n", map {sprintf(" %*s %*s\n",$vl,$_->[0],-$ml,$_->[1])} @reports; } if ( @dep_errors ) { diag join("\n", "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n", "The following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass; # vim: ts=4 sts=4 sw=4 et: Session-Storage-Secure-0.010/t/basic.t000644 000765 000024 00000014114 12331477120 017727 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 decode_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" ); my $store2 = _gen_store( { secret_key => "second secret", old_secrets => [$secret], } ); my $decoded2 = $store2->decode($encoded); cmp_deeply( $decoded2, $data, "roundtrip with old secret" ); my $store3 = _gen_store( { secret_key => "second secret", old_secrets => [ "another secret", $secret ], } ); my $decoded3 = $store3->decode($encoded); cmp_deeply( $decoded3, $data, "roundtrip with old secret" ); my $store4 = _gen_store( { secret_key => "second secret", old_secrets => [ $secret, "another secret" ], } ); my $decoded4 = $store4->decode($encoded); cmp_deeply( $decoded4, $data, "roundtrip with old secret" ); }; 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" ); my $store3 = _gen_store( { secret_key => "second secret key", old_secrets => [ "something else", "another secret" ], } ); is( $store3->decode($encoded), undef, "No matching keys 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.010/t/encoding.t000644 000765 000024 00000005062 12331477120 020436 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 decode_base64url/; use Session::Storage::Secure; my $data = { foo => 'bar', baz => 'bam', }; my $secret = "serenade viscount secretary frail"; my $custom_enc = sub { return "~" . reverse encode_base64url( $_[0] ); }; my $custom_dec = sub { my $string = shift; substr( $string, 0, 1, '' ); return decode_base64url( scalar reverse $string ); }; 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; } subtest "custom separator" => sub { my $store = _gen_store( { separator => ":", } ); my $encoded = $store->encode($data); my $decoded = eval { $store->decode($encoded) }; is( $@, '', "no error decoding custom separator" ); cmp_deeply( $decoded, $data, "custom separator works" ); }; subtest "custom transfer encoding" => sub { my $store = _gen_store( { transport_encoder => $custom_enc, transport_decoder => sub { return "" }, # intentionally broken separator => ':', } ); my $encoded = $store->encode($data); my $decoded = eval { $store->decode($encoded) }; is( $decoded, undef, "non-symmtric custom codec throws error" ); $store = _gen_store( { transport_encoder => $custom_enc, transport_decoder => $custom_dec, separator => ':', } ); $decoded = eval { $store->decode($encoded) }; is( $@, '', "no error decoding custom codec" ); cmp_deeply( $decoded, $data, "custom codec works" ); }; subtest "custom sereal options" => sub { my $store = _gen_store( { sereal_encoder_options => {}, # i.e. allow objects sereal_decoder_options => {}, } ); my $object = bless { %$data }, "Fake::Class"; my $encoded = $store->encode({ object => $object}); my $decoded = eval { $store->decode($encoded) }; isa_ok( $decoded->{object}, "Fake::Class", "decoded session element" ); is_deeply( $decoded->{object}, $object, "object decoded correctly" ); }; 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.010/t/errors.t000644 000765 000024 00000002067 12331477120 020166 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.010/lib/Session/000755 000765 000024 00000000000 12331477120 020406 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/lib/Session/Storage/000755 000765 000024 00000000000 12331477120 022012 5ustar00davidstaff000000 000000 Session-Storage-Secure-0.010/lib/Session/Storage/Secure.pm000644 000765 000024 00000050750 12331477120 023605 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.010'; # 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 (); 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 #--------------------------------------------------------------------------# #pod =attr secret_key (required) #pod #pod This is used to secure the session data. The encryption and message #pod authentication key is derived from this using a one-way function. Changing it #pod will invalidate all sessions. #pod #pod =cut has secret_key => ( is => 'ro', isa => Str, required => 1, ); #pod =attr default_duration #pod #pod Number of seconds for which the session may be considered valid. If an #pod expiration is not provided to C, this is used instead to expire the #pod session after a period of time. It is unset by default, meaning that session #pod expiration is not capped. #pod #pod =cut has default_duration => ( is => 'ro', isa => Int, predicate => 1, ); #pod =attr old_secrets #pod #pod An optional array reference of strings containing old secret keys no longer #pod used for encryption but still supported for decrypting session data. #pod #pod =cut has old_secrets => ( is => 'ro', isa => ArrayRef [Str], ); #pod =attr separator #pod #pod A character used to separate fields. It defaults to C<~>. #pod #pod =cut has separator => ( is => 'ro', isa => Str, default => '~', ); #pod =attr sereal_encoder_options #pod #pod A hash reference with constructor arguments for L. Defaults #pod to C<< { snappy => 1, croak_on_bless => 1 } >>. #pod #pod =cut has sereal_encoder_options => ( is => 'ro', isa => HashRef, default => sub { { snappy => 1, croak_on_bless => 1 } }, ); #pod =attr sereal_decoder_options #pod #pod A hash reference with constructor arguments for L. Defaults #pod to C<< { refuse_objects => 1, validate_utf8 => 1 } >>. #pod #pod =cut has sereal_decoder_options => ( is => 'ro', isa => HashRef, default => sub { { refuse_objects => 1, validate_utf8 => 1 } }, ); #pod =attr transport_encoder #pod #pod A code reference to convert binary data elements (the encrypted data and the #pod MAC) into a transport-safe form. Defaults to #pod L. The output must not include #pod the C attribute used to delimit fields. #pod #pod =cut has transport_encoder => ( is => 'ro', isa => CodeRef, default => sub { \&MIME::Base64::encode_base64url }, ); #pod =attr transport_decoder #pod #pod A code reference to extract binary data (the encrypted data and the #pod MAC) from a transport-safe form. It must be the complement to C. #pod Defaults to L. #pod #pod =cut has transport_decoder => ( is => 'ro', isa => CodeRef, default => sub { \&MIME::Base64::decode_base64url }, ); has _encoder => ( is => 'lazy', isa => InstanceOf ['Sereal::Encoder'], handles => { '_freeze' => 'encode' }, ); sub _build__encoder { my ($self) = @_; return Sereal::Encoder->new( $self->sereal_encoder_options ); } has _decoder => ( is => 'lazy', isa => InstanceOf ['Sereal::Decoder'], handles => { '_thaw' => 'decode' }, ); sub _build__decoder { my ($self) = @_; return Sereal::Decoder->new( $self->sereal_decoder_options ); } 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 ); } #pod =method encode #pod #pod my $string = $store->encode( $data, $expires ); #pod #pod The C<$data> argument should be a reference to a data structure. By default, #pod it must not contain objects. (See L for #pod rationale and alternatives.) If it is undefined, an empty hash reference will #pod be encoded instead. #pod #pod The optional C<$expires> argument should be the session expiration time #pod expressed as epoch seconds. If the C<$expires> time is in the past, the #pod C<$data> argument is cleared and an empty hash reference is encoded and returned. #pod If no C<$expires> is given, then if the C attribute is set, it #pod will be used to calculate an expiration time. #pod #pod The method returns a string that securely encodes the session data. All binary #pod components are protected via the L attribute. #pod #pod An exception is thrown on any errors. #pod #pod =cut sub encode { my ( $self, $data, $expires ) = @_; $data = {} unless defined $data; my $sep = $self->separator; # 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 = $self->transport_encoder->( $cbc->encrypt( $self->_freeze($data) ) ); $mac = $self->transport_encoder->( hmac_sha256( "$expires$sep$ciphertext", $key ) ); }; croak "Encoding error: $@" if $@; return join( $sep, $salt, $expires, $ciphertext, $mac ); } #pod =method decode #pod #pod my $data = $store->decode( $string ); #pod #pod The C<$string> argument must be the output of C. #pod #pod If the message integrity check fails or if expiration exists and is in #pod the past, the method returns undef or an empty list (depending on context). #pod #pod An exception is thrown on any errors. #pod #pod =cut sub decode { my ( $self, $string ) = @_; return unless length $string; # Having a string implies at least salt; expires is optional; rest required my $sep = $self->separator; my ( $salt, $expires, $ciphertext, $mac ) = split qr/\Q$sep\E/, $string; return unless defined($ciphertext) && length($ciphertext); return unless defined($mac) && length($mac); # Try to decode against all known secret keys my @secrets = ( $self->secret_key, @{ $self->old_secrets || [] } ); my $key; CHECK: foreach my $secret (@secrets) { $key = hmac_sha256( $salt, $secret ); my $check_mac = eval { $self->transport_encoder->( hmac_sha256( "$expires$sep$ciphertext", $key ) ); }; last CHECK if ( defined($check_mac) && length($check_mac) && equals( $check_mac, $mac ) # constant time comparison ); undef $key; } # Check MAC integrity return unless defined($key); # Check expiration 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( $self->transport_decoder->($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.010 =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 (with the unfortunate side effect of revealing user names and prohibiting 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 an extra step 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 by default. 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 session expiration is not capped. =head2 old_secrets An optional array reference of strings containing old secret keys no longer used for encryption but still supported for decrypting session data. =head2 separator A character used to separate fields. It defaults to C<~>. =head2 sereal_encoder_options A hash reference with constructor arguments for L. Defaults to C<< { snappy => 1, croak_on_bless => 1 } >>. =head2 sereal_decoder_options A hash reference with constructor arguments for L. Defaults to C<< { refuse_objects => 1, validate_utf8 => 1 } >>. =head2 transport_encoder A code reference to convert binary data elements (the encrypted data and the MAC) into a transport-safe form. Defaults to L. The output must not include the C attribute used to delimit fields. =head2 transport_decoder A code reference to extract binary data (the encrypted data and the MAC) from a transport-safe form. It must be the complement to C. Defaults to L. =head1 METHODS =head2 encode my $string = $store->encode( $data, $expires ); The C<$data> argument should be a reference to a data structure. By default, it must not contain objects. (See L for rationale and alternatives.) 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 protected via the L attribute. 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 has_default_duration =head1 LIMITATIONS =head2 Secret key You must protect the secret key, of course. Rekeying periodically would improve security. Rekeying also invalidates all existing sessions unless the C attribute contains old encryption keys still used for decryption. 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 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. Alternatively, applications can change L and L to allow object serialization or other object transformations and accept the risks of doing so. =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 https://github.com/dagolden/Session-Storage-Secure.git =head1 AUTHOR David Golden =head1 CONTRIBUTOR Tom Hukins =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