2 namespace Shaarli\Security
;
4 use Shaarli\Config\ConfigManager
;
7 * Manages the server-side session
11 public const KEY_LINKS_PER_PAGE
= 'LINKS_PER_PAGE';
12 public const KEY_VISIBILITY
= 'visibility';
13 public const KEY_UNTAGGED_ONLY
= 'untaggedonly';
15 public const KEY_SUCCESS_MESSAGES
= 'successes';
16 public const KEY_WARNING_MESSAGES
= 'warnings';
17 public const KEY_ERROR_MESSAGES
= 'errors';
19 /** @var int Session expiration timeout, in seconds */
20 public static $SHORT_TIMEOUT = 3600; // 1 hour
22 /** @var int Session expiration timeout, in seconds */
23 public static $LONG_TIMEOUT = 31536000; // 1 year
25 /** @var array Local reference to the global $_SESSION array */
26 protected $session = [];
28 /** @var ConfigManager Configuration Manager instance **/
29 protected $conf = null;
31 /** @var bool Whether the user should stay signed in (LONG_TIMEOUT) */
32 protected $staySignedIn = false;
40 * @param array $session The $_SESSION array (reference)
41 * @param ConfigManager $conf ConfigManager instance
42 * @param string $savePath Session save path returned by builtin function session_save_path()
44 public function __construct(&$session, $conf, string $savePath)
46 $this->session
= &$session;
48 $this->savePath
= $savePath;
52 * Initialize XSRF token and links per page session variables.
54 public function initialize(): void
56 if (!isset($this->session
['tokens'])) {
57 $this->session
['tokens'] = [];
60 if (!isset($this->session
['LINKS_PER_PAGE'])) {
61 $this->session
['LINKS_PER_PAGE'] = $this->conf
->get('general.links_per_page', 20);
66 * Define whether the user should stay signed in across browser sessions
68 * @param bool $staySignedIn Keep the user signed in
70 public function setStaySignedIn($staySignedIn)
72 $this->staySignedIn
= $staySignedIn;
76 * Generates a session token
78 * @return string token
80 public function generateToken()
82 $token = sha1(uniqid('', true) .'_'. mt_rand() . $this->conf
->get('credentials.salt'));
83 $this->session
['tokens'][$token] = 1;
88 * Checks the validity of a session token, and destroys it afterwards
90 * @param string $token The token to check
92 * @return bool true if the token is valid, else false
94 public function checkToken($token)
96 if (! isset($this->session
['tokens'][$token])) {
97 // the token is wrong, or has already been used
101 // destroy the token to prevent future use
102 unset($this->session
['tokens'][$token]);
107 * Validate session ID to prevent Full Path Disclosure.
110 * The session ID's format depends on the hash algorithm set in PHP settings
112 * @param string $sessionId Session ID
114 * @return true if valid, false otherwise.
116 * @see http://php.net/manual/en/function.hash-algos.php
117 * @see http://php.net/manual/en/session.configuration.php
119 public static function checkId($sessionId)
121 if (empty($sessionId)) {
129 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
137 * Store user login information after a successful login
139 * @param string $clientIpId Client IP address identifier
141 public function storeLoginInfo($clientIpId)
143 $this->session
['ip'] = $clientIpId;
144 $this->session
['username'] = $this->conf
->get('credentials.login');
145 $this->extendTimeValidityBy(self
::$SHORT_TIMEOUT);
149 * Extend session validity
151 public function extendSession()
153 if ($this->staySignedIn
) {
154 return $this->extendTimeValidityBy(self
::$LONG_TIMEOUT);
156 return $this->extendTimeValidityBy(self
::$SHORT_TIMEOUT);
160 * Extend expiration time
162 * @param int $duration Expiration time extension (seconds)
164 * @return int New session expiration time
166 protected function extendTimeValidityBy($duration)
168 $expirationTime = time() +
$duration;
169 $this->session
['expires_on'] = $expirationTime;
170 return $expirationTime;
174 * Logout a user by unsetting all login information
177 * - https://secure.php.net/manual/en/function.setcookie.php
179 public function logout()
181 if (isset($this->session
)) {
182 unset($this->session
['ip']);
183 unset($this->session
['expires_on']);
184 unset($this->session
['username']);
185 unset($this->session
['visibility']);
190 * Check whether the session has expired
192 * @param string $clientIpId Client IP address identifier
194 * @return bool true if the session has expired, false otherwise
196 public function hasSessionExpired()
198 if (empty($this->session
['expires_on'])) {
201 if (time() >= $this->session
['expires_on']) {
208 * Check whether the client IP address has changed
210 * @param string $clientIpId Client IP address identifier
212 * @return bool true if the IP has changed, false if it has not, or
213 * if session protection has been disabled
215 public function hasClientIpChanged($clientIpId)
217 if ($this->conf
->get('security.session_protection_disabled') === true) {
220 if (isset($this->session
['ip']) && $this->session
['ip'] === $clientIpId) {
226 /** @return array Local reference to the global $_SESSION array */
227 public function getSession(): array
229 return $this->session
;
233 * @param mixed $default value which will be returned if the $key is undefined
235 * @return mixed Content stored in session
237 public function getSessionParameter(string $key, $default = null)
239 return $this->session
[$key] ?? $default;
243 * Store a variable in user session.
245 * @param string $key Session key
246 * @param mixed $value Session value to store
250 public function setSessionParameter(string $key, $value): self
252 $this->session
[$key] = $value;
258 * Store a variable in user session.
260 * @param string $key Session key
264 public function deleteSessionParameter(string $key): self
266 unset($this->session
[$key]);
271 public function getSavePath(): string
273 return $this->savePath
;
277 * Next public functions wrapping native PHP session API.
280 public function destroy(): bool
284 return session_destroy();
287 public function start(): bool
289 if (session_status() === PHP_SESSION_ACTIVE
) {
293 return session_start();
296 public function cookieParameters(int $lifeTime, string $path, string $domain): bool
298 return session_set_cookie_params($lifeTime, $path, $domain);
301 public function regenerateId(bool $deleteOldSession = false): bool
303 return session_regenerate_id($deleteOldSession);