Session-Storage-Secure-1.000/000755 000766 000024 00000000000 14026353116 016217 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/LICENSE000644 000766 000024 00000026354 14026353116 017236 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-1.000/cpanfile000644 000766 000024 00000004004 14026353116 017721 0ustar00davidstaff000000 000000 # This file is generated by Dist::Zilla::Plugin::CPANFile v6.017 # Do not edit this file directly. To change prereqs, edit the `dist.ini` file. requires "Carp" => "0"; requires "Crypt::CBC" => "3.01"; 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" => "4.005"; requires "Sereal::Encoder" => "4.005"; 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" => "0"; requires "Test::Deep" => "0"; requires "Test::Fatal" => "0"; requires "Test::More" => "0.96"; requires "Test::Tolerant" => "0"; requires "perl" => "5.008001"; }; on 'test' => sub { recommends "CPAN::Meta" => "2.120900"; }; on 'configure' => sub { requires "ExtUtils::MakeMaker" => "6.17"; requires "perl" => "5.008001"; }; on 'configure' => sub { suggests "JSON::PP" => "2.27300"; }; on 'develop' => sub { requires "Dist::Zilla" => "5"; requires "Dist::Zilla::Plugin::MinimumPerl" => "0"; requires "Dist::Zilla::Plugin::ReleaseStatus::FromVersion" => "0"; requires "Dist::Zilla::PluginBundle::DAGOLDEN" => "0.072"; requires "File::Spec" => "0"; requires "File::Temp" => "0"; requires "IO::Handle" => "0"; requires "IPC::Open3" => "0"; requires "Pod::Coverage::TrustPod" => "0"; requires "Pod::Wordlist" => "0"; requires "Software::License::Apache_2_0" => "0"; requires "Test::CPAN::Meta" => "0"; requires "Test::MinimumVersion" => "0"; requires "Test::More" => "0"; requires "Test::Perl::Critic" => "0"; requires "Test::Pod" => "1.41"; requires "Test::Pod::Coverage" => "1.08"; requires "Test::Portability::Files" => "0"; requires "Test::Spelling" => "0.12"; requires "Test::Version" => "1"; }; Session-Storage-Secure-1.000/Changes000644 000766 000024 00000005737 14026353116 017526 0ustar00davidstaff000000 000000 Revision history for Session-Storage-Secure 1.000 2021-03-23 07:51:36-04:00 America/New_York [!!! Compatibility Notice !!!] - This version introduces protocol version 2. By default, newly generated output will be encoded using version 2. Old data created with old versions of this module will still be readable, whether using the same secret or the old_secrets array. - Protocol version 2 key features include: salt length increased to 256 bits and binary encoded; no longer uses a deprecated Crypt::CBC key derivation function; protocol version appended to the generated output. [FIXED] - Protocol version 1 suppresses 'opensslv1' key-derivation function deprecation warnings from Crypt::CBC. [PREREQS] - Requires Crypt::CBC 3.01 0.903 2021-03-22 22:40:21-04:00 America/New_York (TRIAL RELEASE) 0.901 2021-03-22 11:37:09-04:00 America/New_York (TRIAL RELEASE) 0.011 2018-04-22 22:12:40+02:00 Europe/Oslo [CHANGED] - Bumped prereq on Sereal::Decoder to 4.005 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-1.000/MANIFEST000644 000766 000024 00000001060 14026353116 017345 0ustar00davidstaff000000 000000 # This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.017. CONTRIBUTING.mkdn Changes LICENSE MANIFEST META.json META.yml Makefile.PL README cpanfile dist.ini lib/Session/Storage/Secure.pm perlcritic.rc t/00-report-prereqs.dd t/00-report-prereqs.t t/basic.t t/basic_v1.t t/encoding.t t/errors.t t/protocol_versions.t tidyall.ini xt/author/00-compile.t xt/author/critic.t xt/author/distmeta.t xt/author/minimum-version.t xt/author/pod-coverage.t xt/author/pod-spell.t xt/author/pod-syntax.t xt/author/portability.t xt/author/test-version.t Session-Storage-Secure-1.000/perlcritic.rc000644 000766 000024 00000001166 14026353116 020711 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-1.000/CONTRIBUTING.mkdn000644 000766 000024 00000006604 14026353116 021007 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 that many of the usual files you might expect are not in the repository, but are generated at release time, as is much of the documentation. Some generated files are kept in the repository as a convenience (e.g. Makefile.PL or cpanfile). Generally, **you do not need Dist::Zilla to contribute patches**. You do need Dist::Zilla to create a tarball. See below for guidance. ### Getting dependencies If you have App::cpanminus 1.6 or later installed, you can use `cpanm` to satisfy dependencies like this: $ cpanm --installdeps . Otherwise, look for either a `Makefile.PL` or `cpanfile` file for a list of dependencies to satisfy. ### 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. Some is generated boilerplate; other documentation is built from pseudo-POD directives in the source like C<=method> or C<=func>. 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. ### Where to send patches and pull requests If you found this distribution on Github, sending a pull-request is the best way to contribute. If a pull-request isn't possible, a bug ticket with a patch file is the next best option. As a last resort, an email to the author(s) is acceptable. ## Installing and using Dist::Zilla Dist::Zilla is not required for contributing, but if you'd like to learn more, this section will get you up to speed. 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 You can learn more about Dist::Zilla at http://dzil.org/ Session-Storage-Secure-1.000/t/000755 000766 000024 00000000000 14026353116 016462 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/xt/000755 000766 000024 00000000000 14026353116 016652 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/README000644 000766 000024 00000031041 14026353116 017076 0ustar00davidstaff000000 000000 NAME Session::Storage::Secure - Encrypted, expiring, compressed, serialized session data with integrity VERSION version 1.000 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. protocol_version An integer representing the protocol used by "Session::Storage::Secure". Protocol 1 was the initial version, which used a now-deprecated mode of Crypt::CBC. Protocol 2 is the current default. 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 AUTHOR David Golden CONTRIBUTORS * Petr Písař * 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-1.000/META.yml000644 000766 000024 00000003125 14026353116 017471 0ustar00davidstaff000000 000000 --- abstract: 'Encrypted, expiring, compressed, serialized session data with integrity' author: - 'David Golden ' build_requires: ExtUtils::MakeMaker: '0' File::Spec: '0' Test::Deep: '0' Test::Fatal: '0' Test::More: '0.96' Test::Tolerant: '0' perl: '5.008001' configure_requires: ExtUtils::MakeMaker: '6.17' perl: '5.008001' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.017, CPAN::Meta::Converter version 2.150010' 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: - corpus - examples - t - xt package: - DB provides: Session::Storage::Secure: file: lib/Session/Storage/Secure.pm version: '1.000' requires: Carp: '0' Crypt::CBC: '3.01' 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: '4.005' Sereal::Encoder: '4.005' 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: '1.000' x_authority: cpan:DAGOLDEN x_contributors: - 'Petr Písař ' - 'Tom Hukins ' x_generated_by_perl: v5.32.0 x_serialization_backend: 'YAML::Tiny version 1.73' x_spdx_expression: Apache-2.0 Session-Storage-Secure-1.000/tidyall.ini000644 000766 000024 00000000240 14026353116 020356 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-1.000/lib/000755 000766 000024 00000000000 14026353116 016765 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/Makefile.PL000644 000766 000024 00000004156 14026353116 020177 0ustar00davidstaff000000 000000 # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.017. 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 ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.17" }, "DISTNAME" => "Session-Storage-Secure", "LICENSE" => "apache", "MIN_PERL_VERSION" => "5.008001", "NAME" => "Session::Storage::Secure", "PREREQ_PM" => { "Carp" => 0, "Crypt::CBC" => "3.01", "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" => "4.005", "Sereal::Encoder" => "4.005", "String::Compare::ConstantTime" => 0, "namespace::clean" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "Test::Deep" => 0, "Test::Fatal" => 0, "Test::More" => "0.96", "Test::Tolerant" => 0 }, "VERSION" => "1.000", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Carp" => 0, "Crypt::CBC" => "3.01", "Crypt::Rijndael" => 0, "Crypt::URandom" => 0, "Digest::SHA" => 0, "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "MIME::Base64" => "3.12", "Math::Random::ISAAC::XS" => 0, "Moo" => 0, "MooX::Types::MooseLike::Base" => "0.16", "Sereal::Decoder" => "4.005", "Sereal::Encoder" => "4.005", "String::Compare::ConstantTime" => 0, "Test::Deep" => 0, "Test::Fatal" => 0, "Test::More" => "0.96", "Test::Tolerant" => 0, "namespace::clean" => 0, "strict" => 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-1.000/META.json000644 000766 000024 00000007150 14026353116 017643 0ustar00davidstaff000000 000000 { "abstract" : "Encrypted, expiring, compressed, serialized session data with integrity", "author" : [ "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.017, CPAN::Meta::Converter version 2.150010", "license" : [ "apache_2_0" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Session-Storage-Secure", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17", "perl" : "5.008001" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::MinimumPerl" : "0", "Dist::Zilla::Plugin::ReleaseStatus::FromVersion" : "0", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.072", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Software::License::Apache_2_0" : "0", "Test::CPAN::Meta" : "0", "Test::MinimumVersion" : "0", "Test::More" : "0", "Test::Perl::Critic" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1" } }, "runtime" : { "requires" : { "Carp" : "0", "Crypt::CBC" : "3.01", "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" : "4.005", "Sereal::Encoder" : "4.005", "String::Compare::ConstantTime" : "0", "namespace::clean" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::Deep" : "0", "Test::Fatal" : "0", "Test::More" : "0.96", "Test::Tolerant" : "0", "perl" : "5.008001" } } }, "provides" : { "Session::Storage::Secure" : { "file" : "lib/Session/Storage/Secure.pm", "version" : "1.000" } }, "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" : "1.000", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Petr P\u00edsa\u0159 ", "Tom Hukins " ], "x_generated_by_perl" : "v5.32.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.24", "x_spdx_expression" : "Apache-2.0" } Session-Storage-Secure-1.000/dist.ini000644 000766 000024 00000001123 14026353116 017660 0ustar00davidstaff000000 000000 name = Session-Storage-Secure author = David Golden license = Apache_2_0 copyright_holder = David Golden copyright_year = 2013 [@DAGOLDEN] :version = 0.072 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 [ReleaseStatus::FromVersion] testing = third_decimal_odd [MinimumPerl] Session-Storage-Secure-1.000/lib/Session/000755 000766 000024 00000000000 14026353116 020410 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/lib/Session/Storage/000755 000766 000024 00000000000 14026353116 022014 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/lib/Session/Storage/Secure.pm000644 000766 000024 00000053754 14026353116 023616 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; package Session::Storage::Secure; # ABSTRACT: Encrypted, expiring, compressed, serialized session data with integrity our $VERSION = '1.000'; use Carp (qw/croak/); use Crypt::CBC 3.01 (); 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 4.005 (); use Sereal::Decoder 4.005 (); 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 }, ); #pod =attr protocol_version #pod #pod An integer representing the protocol used by C. #pod Protocol 1 was the initial version, which used a now-deprecated mode of #pod L. Protocol 2 is the current default. #pod #pod =cut has protocol_version => ( is => 'ro', isa => Num, default => 2, ); 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 ); } sub BUILD { my ($self) = @_; $self->_check_version_for( encoding => $self->protocol_version ); } sub _check_version_for { my ( $self, $action, $pv ) = @_; if ( $pv < 1 || $pv > 2 ) { croak "Invalid protocol version for $action: $pv"; } } sub _get_cbc { my ( $self, $pv, $key, $salt ) = @_; my $cbc_opts = { -key => $key, -cipher => 'Rijndael', }; if ( $pv == 1 ) { $cbc_opts->{-pbkdf} = 'opensslv1'; $cbc_opts->{-nodeprecate} = 1; } else { $cbc_opts->{-pbkdf} = 'none'; $cbc_opts->{-keysize} = 32; $cbc_opts->{-header} = 'none'; my $cipher = Crypt::Rijndael->new($key); $cbc_opts->{-iv} = substr( $cipher->encrypt($salt), 0, 16 ); } return Crypt::CBC->new(%$cbc_opts); } #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; if ( $self->protocol_version == 1 ) { # numeric salt $salt = $self->_irand; } else { # binary salt $salt = pack( "N*", map { $self->_irand } 1 .. 8 ); } my $key = hmac_sha256( $salt, $self->secret_key ); my $cbc = $self->_get_cbc( $self->protocol_version, $key, $salt ); 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 $@; my $output; if ( $self->protocol_version == 1 ) { $output = join( $sep, $salt, $expires, $ciphertext, $mac ); } else { $salt = $self->transport_encoder->($salt); $output = join( $sep, $salt, $expires, $ciphertext, $mac, $self->protocol_version ); } return $output; } #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, $version ) = split qr/\Q$sep\E/, $string; return unless defined($ciphertext) && length($ciphertext); return unless defined($mac) && length($mac); $version = 1 unless defined $version; $self->_check_version_for( decoding => $version ); if ( $version == 1 ) { # $salt is a decimal } else { # Decode salt to binary $salt = $self->transport_decoder->($salt); } # 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 = $self->_get_cbc( $version, $key, $salt ); 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 1.000 =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. =head2 protocol_version An integer representing the protocol used by C. Protocol 1 was the initial version, which used a now-deprecated mode of L. Protocol 2 is the current default. =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 BUILD =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 =head1 AUTHOR David Golden =head1 CONTRIBUTORS =for stopwords Petr Písař Tom Hukins =over 4 =item * Petr Písař =item * Tom Hukins =back =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 Session-Storage-Secure-1.000/xt/author/000755 000766 000024 00000000000 14026353116 020154 5ustar00davidstaff000000 000000 Session-Storage-Secure-1.000/xt/author/critic.t000644 000766 000024 00000000201 14026353116 021607 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; use Test::Perl::Critic (-profile => "perlcritic.rc") x!! -e "perlcritic.rc"; all_critic_ok(); Session-Storage-Secure-1.000/xt/author/minimum-version.t000644 000766 000024 00000000152 14026353116 023475 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; use Test::MinimumVersion; all_minimum_version_ok( qq{5.010} ); Session-Storage-Secure-1.000/xt/author/test-version.t000644 000766 000024 00000000637 14026353116 023011 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::Version 1.09 use Test::Version; my @imports = qw( version_all_ok ); my $params = { is_strict => 0, has_version => 1, multiple => 0, }; 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-1.000/xt/author/00-compile.t000644 000766 000024 00000002673 14026353116 022216 0ustar00davidstaff000000 000000 use 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.058 use Test::More; plan tests => 2; my @module_files = ( 'Session/Storage/Secure.pm' ); # fake home for cpan-testers use File::Temp; local $ENV{HOME} = File::Temp::tempdir( CLEANUP => 1 ); my @switches = ( -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; diag('Running: ', join(', ', map { my $str = $_; $str =~ s/'/\\'/g; q{'} . $str . q{'} } $^X, @switches, '-e', "require q[$lib]")) if $ENV{PERL_COMPILE_TEST_DEBUG}; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, @switches, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); shift @_warnings if @_warnings and $_warnings[0] =~ /^Using .*\bblib/ and not eval { +require blib; blib->VERSION('1.01') }; if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') or diag 'got warnings: ', ( Test::More->can('explain') ? Test::More::explain(\@warnings) : join("\n", '', @warnings) ); Session-Storage-Secure-1.000/xt/author/pod-syntax.t000644 000766 000024 00000000252 14026353116 022446 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Session-Storage-Secure-1.000/xt/author/portability.t000644 000766 000024 00000000322 14026353116 022700 0ustar00davidstaff000000 000000 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-1.000/xt/author/distmeta.t000644 000766 000024 00000000172 14026353116 022153 0ustar00davidstaff000000 000000 #!perl # This file was automatically generated by Dist::Zilla::Plugin::MetaTests. use Test::CPAN::Meta; meta_yaml_ok(); Session-Storage-Secure-1.000/xt/author/pod-spell.t000644 000766 000024 00000000677 14026353116 022252 0ustar00davidstaff000000 000000 use strict; use warnings; use Test::More; # generated by Dist::Zilla::Plugin::Test::PodSpelling 2.007005 use Test::Spelling 0.12; use Pod::Wordlist; add_stopwords(); all_pod_files_spelling_ok( qw( bin lib ) ); __DATA__ AES David Don'ts Fu Golden HMAC Hukins Liu MAC's Petr Písař Rekeying Secure Sereal Session Storage Tom al authenticator ciphertext cryptographically dagolden decrypting et lib login ppisar scalability tom unencrypted Session-Storage-Secure-1.000/xt/author/pod-coverage.t000644 000766 000024 00000000334 14026353116 022714 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-1.000/t/protocol_versions.t000644 000766 000024 00000003472 14026353116 022446 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; use Test::More 0.96; use Test::Fatal; use Test::Deep qw/!blessed/; use Session::Storage::Secure; my $data = { foo => 'bar', baz => 'bam', }; my $secret = "serenade viscount secretary frail"; my $old_secret = "tornados hypocrisy overhang exegesis"; 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 "pv2 object reads pv1 session" => sub { my $pv1_store = _gen_store( { protocol_version => 1 } ); my $pv2_store = _gen_store; my $pv1_session = $pv1_store->encode($data); my $decoded = $pv2_store->decode($pv1_session); cmp_deeply( $decoded, $data, "roundtrip" ); }; subtest "pv1 object reads pv2 session" => sub { my $pv1_store = _gen_store( { protocol_version => 1 } ); my $pv2_store = _gen_store; my $pv2_session = $pv2_store->encode($data); my $decoded = $pv1_store->decode($pv2_session); cmp_deeply( $decoded, $data, "roundtrip" ); }; subtest "pv2 object reads pv1 old secrets" => sub { my $pv1_store = _gen_store( { secret_key => $old_secret, protocol_version => 1 } ); my $pv2_store = _gen_store( { old_secrets => [ $old_secret ] } ); my $pv1_session = $pv1_store->encode($data); my $decoded = $pv2_store->decode($pv1_session); cmp_deeply( $decoded, $data, "roundtrip" ); }; 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-1.000/t/encoding.t000644 000766 000024 00000005062 14026353116 020440 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-1.000/t/errors.t000644 000766 000024 00000002726 14026353116 020172 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", ); }; subtest "bad protocol version" => sub { for my $pv ( -1, 0, 3 ) { like( exception { Session::Storage::Secure->new( secret_key => $secret, protocol_version => $pv, ) }, qr/Invalid protocol version for encoding/, "Invalid protocol_version $pv throws 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-1.000/t/basic_v1.t000644 000766 000024 00000000613 14026353116 020336 0ustar00davidstaff000000 000000 use 5.008001; use strict; use warnings; use Test::More 0.96; $ENV{Session_Storage_Secure_Version} = 1; note "Running basic tests with protocol version 1"; do './t/basic.t' or die $@ || $!; # # 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-1.000/t/basic.t000644 000766 000024 00000014336 14026353116 017737 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 $protocol_version = $ENV{Session_Storage_Secure_Version}; sub _gen_store { my ($config) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; my $store = Session::Storage::Secure->new( secret_key => $secret, %{ $config || {} }, ( $protocol_version ? ( protocol_version => $protocol_version ) : () ), ); 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/^[^~]+~~/, "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/^[^~]+~~/, "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-1.000/t/00-report-prereqs.t000644 000766 000024 00000013452 14026353116 022063 0ustar00davidstaff000000 000000 #!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.028 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec; # from $version::LAX my $lax_version_re = qr/(?: undef | (?: (?:[0-9]+) (?: \. | (?:\.[0-9]+) (?:_[0-9]+)? )? | (?:\.[0-9]+) (?:_[0-9]+)? ) | (?: v (?:[0-9]+) (?: (?:\.[0-9]+)+ (?:_[0-9]+)? )? | (?:[0-9]+)? (?:\.[0-9]+){2,} (?:_[0-9]+)? ) )/x; # hide optional CPAN::Meta modules from prereq scanner # and check if they are available my $cpan_meta = "CPAN::Meta"; my $cpan_meta_pre = "CPAN::Meta::Prereqs"; my $HAS_CPAN_META = eval "require $cpan_meta; $cpan_meta->VERSION('2.120900')" && eval "require $cpan_meta_pre"; ## no critic # Verify requirements? my $DO_VERIFY_PREREQS = 1; sub _max { my $max = shift; $max = ( $_ > $max ) ? $_ : $max for @_; return $max; } sub _merge_prereqs { my ($collector, $prereqs) = @_; # CPAN::Meta::Prereqs object if (ref $collector eq $cpan_meta_pre) { return $collector->with_merged_prereqs( CPAN::Meta::Prereqs->new( $prereqs ) ); } # Raw hashrefs for my $phase ( keys %$prereqs ) { for my $type ( keys %{ $prereqs->{$phase} } ) { for my $module ( keys %{ $prereqs->{$phase}{$type} } ) { $collector->{$phase}{$type}{$module} = $prereqs->{$phase}{$type}{$module}; } } } return $collector; } my @include = qw( ); my @exclude = qw( ); # Add static prereqs to the included modules list my $static_prereqs = do './t/00-report-prereqs.dd'; # Merge all prereqs (either with ::Prereqs or a hashref) my $full_prereqs = _merge_prereqs( ( $HAS_CPAN_META ? $cpan_meta_pre->new : {} ), $static_prereqs ); # Add dynamic prereqs to the included modules list (if we can) my ($source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; my $cpan_meta_error; if ( $source && $HAS_CPAN_META && (my $meta = eval { CPAN::Meta->load_file($source) } ) ) { $full_prereqs = _merge_prereqs($full_prereqs, $meta->prereqs); } else { $cpan_meta_error = $@; # capture error from CPAN::Meta->load_file($source) $source = 'static metadata'; } my @full_reports; my @dep_errors; my $req_hash = $HAS_CPAN_META ? $full_prereqs->as_string_hash : $full_prereqs; # Add static includes into a fake section for my $mod (@include) { $req_hash->{other}{modules}{$mod} = 0; } for my $phase ( qw(configure build test runtime develop other) ) { next unless $req_hash->{$phase}; next if ($phase eq 'develop' and not $ENV{AUTHOR_TESTING}); for my $type ( qw(requires recommends suggests conflicts modules) ) { next unless $req_hash->{$phase}{$type}; my $title = ucfirst($phase).' '.ucfirst($type); my @reports = [qw/Module Want Have/]; for my $mod ( sort keys %{ $req_hash->{$phase}{$type} } ) { next if $mod eq 'perl'; next if grep { $_ eq $mod } @exclude; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e File::Spec->catfile($_, $file) } @INC; my $want = $req_hash->{$phase}{$type}{$mod}; $want = "undef" unless defined $want; $want = "any" if !$want && $want == 0; my $req_string = $want eq 'any' ? 'any version required' : "version '$want' required"; if ($prefix) { my $have = MM->parse_version( File::Spec->catfile($prefix, $file) ); $have = "undef" unless defined $have; push @reports, [$mod, $want, $have]; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META && $type eq 'requires' ) { if ( $have !~ /\A$lax_version_re\z/ ) { push @dep_errors, "$mod version '$have' cannot be parsed ($req_string)"; } elsif ( ! $full_prereqs->requirements_for( $phase, $type )->accepts_module( $mod => $have ) ) { push @dep_errors, "$mod version '$have' is not in required range '$want'"; } } } else { push @reports, [$mod, $want, "missing"]; if ( $DO_VERIFY_PREREQS && $type eq 'requires' ) { push @dep_errors, "$mod is not installed ($req_string)"; } } } if ( @reports ) { push @full_reports, "=== $title ===\n\n"; my $ml = _max( map { length $_->[0] } @reports ); my $wl = _max( map { length $_->[1] } @reports ); my $hl = _max( map { length $_->[2] } @reports ); if ($type eq 'modules') { splice @reports, 1, 0, ["-" x $ml, "", "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s\n", -$ml, $_->[0], $hl, $_->[2]) } @reports; } else { splice @reports, 1, 0, ["-" x $ml, "-" x $wl, "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s %*s\n", -$ml, $_->[0], $wl, $_->[1], $hl, $_->[2]) } @reports; } push @full_reports, "\n"; } } } if ( @full_reports ) { diag "\nVersions for all modules listed in $source (including optional ones):\n\n", @full_reports; } if ( $cpan_meta_error || @dep_errors ) { diag "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n"; } if ( $cpan_meta_error ) { my ($orig_source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; diag "\nCPAN::Meta->load_file('$orig_source') failed with: $cpan_meta_error\n"; } if ( @dep_errors ) { diag join("\n", "\nThe following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass('Reported prereqs'); # vim: ts=4 sts=4 sw=4 et: Session-Storage-Secure-1.000/t/00-report-prereqs.dd000644 000766 000024 00000007212 14026353116 022204 0ustar00davidstaff000000 000000 do { my $x = { 'configure' => { 'requires' => { 'ExtUtils::MakeMaker' => '6.17', 'perl' => '5.008001' }, 'suggests' => { 'JSON::PP' => '2.27300' } }, 'develop' => { 'requires' => { 'Dist::Zilla' => '5', 'Dist::Zilla::Plugin::MinimumPerl' => '0', 'Dist::Zilla::Plugin::ReleaseStatus::FromVersion' => '0', 'Dist::Zilla::PluginBundle::DAGOLDEN' => '0.072', 'File::Spec' => '0', 'File::Temp' => '0', 'IO::Handle' => '0', 'IPC::Open3' => '0', 'Pod::Coverage::TrustPod' => '0', 'Pod::Wordlist' => '0', 'Software::License::Apache_2_0' => '0', 'Test::CPAN::Meta' => '0', 'Test::MinimumVersion' => '0', 'Test::More' => '0', 'Test::Perl::Critic' => '0', 'Test::Pod' => '1.41', 'Test::Pod::Coverage' => '1.08', 'Test::Portability::Files' => '0', 'Test::Spelling' => '0.12', 'Test::Version' => '1' } }, 'runtime' => { 'requires' => { 'Carp' => '0', 'Crypt::CBC' => '3.01', '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' => '4.005', 'Sereal::Encoder' => '4.005', 'String::Compare::ConstantTime' => '0', 'namespace::clean' => '0', 'perl' => '5.008001', 'strict' => '0', 'warnings' => '0' } }, 'test' => { 'recommends' => { 'CPAN::Meta' => '2.120900' }, 'requires' => { 'ExtUtils::MakeMaker' => '0', 'File::Spec' => '0', 'Test::Deep' => '0', 'Test::Fatal' => '0', 'Test::More' => '0.96', 'Test::Tolerant' => '0', 'perl' => '5.008001' } } }; $x; }