sbstel/sesshin

PHP 安全高级会话管理器

v1.2.0 2018-01-16 13:50 UTC

This package is not auto-updated.

Last update: 2024-09-11 11:23:48 UTC


README

面向对象、可扩展的高级会话处理组件,以安全性为核心,减轻诸如会话劫持、会话固定、会话暴露、会话中毒、会话预测等攻击。

php.pl contest 中获得第一名。

特性

  • 智能会话过期控制
  • 防止会话采用,即只有由组件生成的会话ID是可接受的(严格模式)
  • 只有在会话真正创建时才发送cookie
  • 基于时间或请求次数的会话ID轮换(防止会话劫持)
  • 可配置的
  • 与PHP原生机制不同,您不需要使用cron或资源消耗的100%垃圾收集概率来确保会话在指定时间后恰好被删除
  • 约定优于配置 - 可配置用户定义的存储、监听器(观察者)、熵回调和指纹生成器,但所有这些都有默认设置
  • 100%独立于不安全的原生PHP会话扩展

Build Status Scrutinizer Code Quality

用法

安装

composer require sobstel/sesshin

创建新会话

只有在调用 create() 时,才会创建会话cookie(对于原生PHP会话处理程序,无论是否需要,cookie始终存在)。

$session->create();

打开现有会话

如果会话之前未被创建,则不会打开会话,并返回 false

$session->open();

如果您想创建新的会话(如果它尚未存在),只需将 true 作为参数传递。它将透明地调用 create()

$session->open(true);

重新生成会话ID

// auto-regenerate after specified time (secs)
$session->setIdTtl(300);

// auto-regenerate after specified number of requests
$session->setIdRequestsLimit(10);

// manually
$session->regenerateId();

监听特殊事件

use Sesshin\Event\Event;

$eventEmitter = $session->geEmitter();

$eventEmitter->addListener('sesshin.no_data_or_expired', function(Event $event) {
  die('Session expired or session adoption attack!');
});
$eventEmitter->addListener('sesshin.expired', function(Event $event) {
  die(sprintf('Session %s expired!', $event->getSession()->getId()));
});
$eventEmitter->addListener('sesshin.invalid_fingerprint', function(Event $event) {
  die('Invalid fingerprint, possible attack!');
});

用户会话

use Sesshin\User\Session as UserSession;
use Sesshin\Store\FileStore;

$userSession = new UserSession(new FileStore('/path/to/dir'));

$userSession->create();
$userSession->login(123);

if ($userSession->isLogged()) {
  echo sprintf('User %s is logged', $userSession->getUserId());

  // Or if you have some kind of UserRepository class, which can be used to fetch user data
  $user = UserRepository::find($userSession->getUserId());
  echo sprintf('User %s is logged', $user->getUsername());
}

存储

Sesshin提供默认的FileStore。

use Sesshin\Session;
use Sesshin\Store\FileStore;

$session = new Session(new FileStore('/path/to/dir'));

注意!在共享托管中使用/tmp作为目录是不安全的。

您还可以使用doctrine/cache 中的众多提供者之一。

use Sesshin\Store\DoctrineCache;
use Doctrine\Common\Cache\MemcachedCache;

$memcached = new Memcached;
// here configure memcached (add servers etc)

$session = new Session(new DoctrineCache(new MemcachedCache($memcached)));

您还可以使用 Sesshin\Store\StoreInterface 实现您自己的存储。

更改熵算法

熵用于生成会话ID。

$session->getIdHandler()->setEntropyGenerator(new MyFancyEntropyGenerator());

MyFancyEntropyGenerator 必须实现 Sesshin\EntropyGenerator\EntropyGeneratorInterface

更改会话ID存储

默认情况下,会话ID存储在cookie中,但有时您可能需要基于某些令牌、查询字符串变量等强制会话ID。

$session->getIdHandler()->setIdStore(new MyFancyIdStore());

MyFancyIdStore 必须实现 Sesshin\Id\Store\StoreInterface