Giter VIP home page Giter VIP logo

php-secure-session's Introduction

PHP-Secure-Session

Build Status Coverage Status

About

This project adds encryption to internal PHP save handlers. It uses OpenSSL extension to provide encryption with AES-256 and authentication using HMAC-SHA-256.

The SecureHandler class extends the default SessionHandler of PHP and it adds only an encryption layer on the internal save handler. The session management logic remains the same, that means you can use SecureSession with all the PHP session handlers like 'file', 'sqlite', 'memcache' or 'memcached' which are provided by PHP extensions.

Installation

You can install this library using composer with the following command:

composer require ezimuel/php-secure-session

After that the PHP-Secure-Session handler will be automatically executed in your project when consuming the vendor/autoload.php file.

Usage

You don't have to do nothing to consume this library, the SecureHandler is automatically registered with session_set_save_handler() during the composer autoload.

How it works

The session data are encrypted using a random key stored in a cookie variable starting with the prefix KEY_.

This random key is generated using the random_bytes() function of PHP 7. For PHP 5 versions we used the paragonie/random_compat project that is a polyfill for random_bytes().

We also generated a random authentication key stored in the same cookie variable. The value stored in the KEY_ cookie is the Base64 representation of the encryption key concatenated with the authentication key.

Demo

You can test the PHP-Secure-Session using the test/demo/index.php example. You can run the demo using the internal web server of PHP with the following command:

php -S 0.0.0.0:8000 -t test/demo

If you open the browser to localhost:8000 you will see the demo in action.


Copyright 2011-2018 by Enrico Zimuel

Released under the MIT License

php-secure-session's People

Contributors

alanseiden avatar ezimuel avatar hardyjohnson avatar romainneutron avatar samdark avatar viralcode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-secure-session's Issues

Error line 120

list ($this->_key, $this->_auth) = explode (':',$_COOKIE[$this->_keyName]);

A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: Securesession.php
Line Number: 120

Seems that the $_COOKIE doesn't have a ':' in it therefore explode is returning only $this->_keyName, there is no second item (offset 1).

This class is very nice and I would really like to utilize it, any help with resolving this would be greatly appreciated.

Thanks!

I think I just figured it out... I cleared my cache, I think it was having problems because a previous session was created but not by this script, so it was not getting set properly... I am no longer having the offset issue.

Session wrapper loses data when serving concurrent requests.

The default PHP session handler aquires a lock before reading data, and releases this lock after data has been written back. This class doesn't do anything like this, so concurrent requests (two or more) will be able to all read the data, all modify them in different places, and then write them back one after the other - and the request writing last overwrites any changes from previous writes.

UTF-8 serialize error for save in MongoDB

I use a custom handler to save sessions in MongoDB.

I tried to adapt its handler to see if it came to an expected result: encrypt and save the database however, received a "Got invalid UTF-8 value serializing".

You have correction suggestions?

I know that support for saving in MongoDB is not part of his project but would like to serialize "UTF-8"?

I do not know the correct way to do this, I created a gist with the prototype.

here found gist

Already grateful for any help.

PHP 7.2+ Compatibility

PHP 7.2 Removes MCrypt support in favor of OpenSSL. This breaks this solution, are there any plans on 7.2+ compatibility?

MCrypt Fallback

Although apparently this is incredibly rare, some servers may not have the MCrypt module installed/enabled.
It happened to me using CodeAnywhere.com Dev and SandBox. And also on Linux Mint, which apparently it's a known quirk. Weird thing was, on my website's server worked perfectly (I later found ou what happened).

I implemented on my own project a sort of fallback that warns the user that SecureSession will not be loaded, allowing the php code to run (mine gave me a blank page untill I found out the problem was with the module). So if the module is loaded, it's business as usual. If not, the code runs, but the user is warned that SecureSession.php not running, and can take appropriate action, without losing the website's functionality.

Do you think it's worth to workaround?

Code fails on session_regenerate_id

This code does not support the use of session_regenerate_id which is used to mitigate session fixation and hijacking attacks.

The only solution I have found is to set an internal field to capture the incoming session ID on read() call and then test against the session ID prior to write(). If the session IDs don't match you know session_regenerate_id has been called. Once you know that you can set a new KEY_ cookie so that the hmac test on the next read will not fail.

Session lost on an oher page

Hi !
I don't know if it's the best place to write it but I still lost my session when I'm using the SecureSession class.

For example :
with this code :
$_SESSION['foo'] = 'foo';
Click Here

When I wrote echo $_SESSION['foo'] in the foo.php page, all is good.

But when I'm using the SecureSessionClass when I wrote var_dump($_SESSION['foo']) or do the same exercice with an other session key I have always and unfortunately NULL...

It's look like the session content can't be read...
I have alrady chown an chmod my /tmp file and all the created session without any success...

Can you give me some light ?
Just for information, I'm working on Linux.
Regards,
Kyrd

php.ini settings

Securing PHP sessions takes more than encrypting the data, the generation of the session ID itself is important as well as other factors which could be set during script execution via ini_set. It might be a good idea to set things like session.use_only_cookies, session.cookie_httponly, sesion.entropy_file and session.entropy_length, as well as session.hash_function and session.hash_bits_per_character to ensure that when someone is using this code they would in fact be using best practice settings. There may be other settings such as session.cookie_secure as well which should be set via hardcode or configuration.

What are your thoughts about adding a configuration function which is called during construct @ezimuel?

SessionHandler compatibility in PHP 8

PHP 8 (not sure which minor exactly) introduced types to the SessionHandler/SessionHandlerInterface which is incompatible with the current implementation of this library.

Deprecated: Return type of PHPSecureSession\SecureHandler::open($save_path, $session_name) should either be compatible with SessionHandler::open(string $path, string $name): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in vendor/ezimuel/php-secure-session/src/SecureHandler.php on line 49
PHP Deprecated:  Return type of PHPSecureSession\SecureHandler::read($id) should either be compatible with SessionHandler::read(string $id): string|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in ezimuel/php-secure-session/src/SecureHandler.php on line 60

There is a fork here where @DatabayAG already applied the necessary changes, but it doesn't look like they created a PR.

register_secure_session.php breaks application

After installing this lib as an experimental dependency for my application it breaks it. This is due to the chdir & require vendor/autoload.php. Removing both lines fixes the problem.

Please use specific exception

Hi,

Currently the code here:

throw new \RuntimeException('Authentication failed');

Is throwing a \RuntimeException. It would allow more precise catching of exceptions if it threw an exception that had a specific meaning.

namespace PHPSecureSession;
class AuthenticationFailedException extends \RuntimeException {
}

as that would allow people to know they are only catching that type of exception, rather than RuntimeExceptions that could be coming from elsewhere in their code.

Demo

Can you please provide a full working demo?

  • public page with a login form that set the session
  • privates pages that check if the session is set else redirects to the public page to log in
  • log out page

Error in session_start

Hello @ezimuel

I am using your library. I followed all of the steps in the README.md but I have some problems and I don't know what is the problem, Can you help me about this?

PHP Warning: session_start(): Failed to decode session object. Session has been destroyed

NOTICE: PHP message: PHP Fatal error:  Uncaught PHPSecureSession\Exception\AuthenticationFailedException: Authentication failed in /var/www/html/vendor/ezimuel/php-secure-session/src/SecureHandler.php:125
Stack trace:
#0 /var/www/html/vendor/ezimuel/php-secure-session/src/SecureHandler.php(63): PHPSecureSession\SecureHandler->decrypt('tiempo_sesion|i...', 'gv\x9C\xAA\xBF\xE6\r|\xB3\xF9VG\xDE\x8B ...')
#1 [internal function]: PHPSecureSession\SecureHandler->read('jaOogRV2lSyUpl1...')
#2 /var/www/html/Core/index.php(15): session_start()
#3 {main}
  thrown in /var/www/html/vendor/ezimuel/php-secure-session/src/SecureHandler.php on line 125

Thank you so much!

Warning on autoload.php

I installed the library with the command:
"composer require ezimuel / php-secure-session"

Then I include the "vendor / autoload.php" file in my .php file

I'm included autoload.php and returns:

You need to execute composer install!

In the directory of the file "composer.json", I executed the requested command, but nothing was increased or updated. The error persisted. I'm using Ampps in Windows environment with OpenSSL configured and SSL configured for localhost.

Help me, thanks.

You need more documentation

hello, you have a good repository, but you need add more data about it, for example how do you write and read in your session vars. because i was triying it in a mvc multitenant app. thanks

Encrypted data doesn't change when reload

I have cloned the repo. I'm using the demo provided and every time I reload the page I see the same encrypted data, it doesn't change. Any idea?

Thanks.

Update 1: I just realized the reason: if (empty($_SESSION['time'])). First time you run the demo.php, the $_SESSION['time'] will be filled. So the content will not be updated anymore because the if statement.

strpos warning

Glanced through your code: strpos() I am pretty sure needs at least 2 arguments. What was your intention for the function? Were you trying to check against if the key name already exists or is a sub string of the last key?

If you can fix this that would be awesome. Excellent.

I read your Crypto power point and it was very informative and right to the point.

Thanks,

Aaron

Warning : failed to open stream

This is probably just me. I'm getting this warning messages when I run the demo.php

Warning: file_get_contents(/tmp/PHPSESSID_q508fpe98uu5v8rp1u5rr9sgq1): failed to open stream: No such file or directory in C:\path\to\Connect\demo.php on line 24

Warning: file_put_contents(/tmp/PHPSESSID_q508fpe98uu5v8rp1u5rr9sgq1): failed to open stream: No such file or directory in C:\path\to\SecureSession.php on line 183

I put the demo.php and SecureSession.php in the same folder and did update the location in demo.php

Would I need to create a "tmp" folder too? or is it something else I'm overlooking?

Cookie handling on first session start

Hi,

if I start the session for the first time from a fresh browser, the cookie for the key in getKey($name) does not exist and is not saved in my browser, since cookies are only written on page reload. If for whatever reason, I do a session_write_close() and the try to restart the session again, I get the implemented runtime exception. This makes sense: in the process of starting the session, an open command is executed. As the key cookie has not been set yet, SecureHandler creates a new key, which then leads to conflicts when decrypting already written data, since the new key and the previous one are different. In order to resolve this issue, I propose to change the function getKey to

 protected function getKey($name)
    {
        if (empty($_COOKIE[$name])) {
            $key = random_bytes(64); // 32 for encryption and 32 for authentication
            $cookieParam = session_get_cookie_params();
            setcookie(
                $name,
                base64_encode($key),
                // if session cookie lifetime > 0 then add to current time
                // otherwise leave it as zero, honoring zero's special meaning
                // expire at browser close.
                ($cookieParam['lifetime'] > 0) ? time() + $cookieParam['lifetime'] : 0,
                $cookieParam['path'],
                $cookieParam['domain'],
                $cookieParam['secure'],
                $cookieParam['httponly']
            );
            $_COOKIE[$name] = base64_encode($key);
        } else {
            $key = base64_decode($_COOKIE[$name]);
        }
        return $key;
    }

i.e. setting the superglobal, $_COOKIE[$name], if created for the first time.

I changed this in my fork. I can create a pull request, if you agree.

Another question: Is it wise to store the decryption key in the cookies? I see that storing it in the session variables does not make any sense, but couldn't it be stored somewhere else?

Thank you for your help!
Ben

change default folder

hi

why change default folder where store session files?

for security reason? If yes, which security reason?

thanks

How to know if it is working or not ?

I have added PHP-Secure-Session as dependency in my project and i didn't notice any change in the session key. So how to know if it is working or not?

Code will not detect already started session.

This will allow unsecure data to be written via the default or other session handler.

I would suggest adding an exception if session has already been started in the constructor.

Session gets destroy sometime

I am using this library to secure session. Sometime users session gets destroy.
Trouble shooting her to find out the reason.

How this PHP_Secure_Session library works.
What is purpose of KEY_.. name?

Compatibility Zend Framework 1

Hi @ezimuel,

You have done a great job with PHP-Secure-Session, thanks for the community.

I plan to use-it with Zend Framework 1, but because the framework already manage the session with the class Zend_Session, I need to extends the class SecureSession with Zend_Session_SaveHandler_Interface.

=> Before I start doing it, I wanted to ask if anyone already did so work about it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.