3 namespace Shaarli\Security
;
5 use Shaarli\Config\ConfigManager
;
8 * Manages the server-side session
12 public const KEY_LINKS_PER_PAGE
= 'LINKS_PER_PAGE';
13 public const KEY_VISIBILITY
= 'visibility';
14 public const KEY_UNTAGGED_ONLY
= 'untaggedonly';
16 public const KEY_SUCCESS_MESSAGES
= 'successes';
17 public const KEY_WARNING_MESSAGES
= 'warnings';
18 public const KEY_ERROR_MESSAGES
= 'errors';
20 /** @var int Session expiration timeout, in seconds */
21 public static $SHORT_TIMEOUT = 3600; // 1 hour
23 /** @var int Session expiration timeout, in seconds */
24 public static $LONG_TIMEOUT = 31536000; // 1 year
26 /** @var array Local reference to the global $_SESSION array */
27 protected $session = [];
29 /** @var ConfigManager Configuration Manager instance **/
30 protected $conf = null;
32 /** @var bool Whether the user should stay signed in (LONG_TIMEOUT) */
33 protected $staySignedIn = false;
41 * @param array $session The $_SESSION array (reference)
42 * @param ConfigManager $conf ConfigManager instance
43 * @param string $savePath Session save path returned by builtin function session_save_path()
45 public function __construct(&$session, $conf, string $savePath)
47 $this->session
= &$session;
49 $this->savePath
= $savePath;
53 * Initialize XSRF token and links per page session variables.
55 public function initialize(): void
57 if (!isset($this->session
['tokens'])) {
58 $this->session
['tokens'] = [];
61 if (!isset($this->session
['LINKS_PER_PAGE'])) {
62 $this->session
['LINKS_PER_PAGE'] = $this->conf
->get('general.links_per_page', 20);
67 * Define whether the user should stay signed in across browser sessions
69 * @param bool $staySignedIn Keep the user signed in
71 public function setStaySignedIn($staySignedIn)
73 $this->staySignedIn
= $staySignedIn;
77 * Generates a session token
79 * @return string token
81 public function generateToken()
83 $token = sha1(uniqid('', true) . '_' . mt_rand() . $this->conf
->get('credentials.salt'));
84 $this->session
['tokens'][$token] = 1;
89 * Checks the validity of a session token, and destroys it afterwards
91 * @param string $token The token to check
93 * @return bool true if the token is valid, else false
95 public function checkToken($token)
97 if (! isset($this->session
['tokens'][$token])) {
98 // the token is wrong, or has already been used
102 // destroy the token to prevent future use
103 unset($this->session
['tokens'][$token]);
108 * Validate session ID to prevent Full Path Disclosure.
111 * The session ID's format depends on the hash algorithm set in PHP settings
113 * @param string $sessionId Session ID
115 * @return true if valid, false otherwise.
117 * @see http://php.net/manual/en/function.hash-algos.php
118 * @see http://php.net/manual/en/session.configuration.php
120 public static function checkId($sessionId)
122 if (empty($sessionId)) {
130 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
138 * Store user login information after a successful login
140 * @param string $clientIpId Client IP address identifier
142 public function storeLoginInfo($clientIpId)
144 $this->session
['ip'] = $clientIpId;
145 $this->session
['username'] = $this->conf
->get('credentials.login');
146 $this->extendTimeValidityBy(self
::$SHORT_TIMEOUT);
150 * Extend session validity
152 public function extendSession()
154 if ($this->staySignedIn
) {
155 return $this->extendTimeValidityBy(self
::$LONG_TIMEOUT);
157 return $this->extendTimeValidityBy(self
::$SHORT_TIMEOUT);
161 * Extend expiration time
163 * @param int $duration Expiration time extension (seconds)
165 * @return int New session expiration time
167 protected function extendTimeValidityBy($duration)
169 $expirationTime = time() +
$duration;
170 $this->session
['expires_on'] = $expirationTime;
171 return $expirationTime;
175 * Logout a user by unsetting all login information
178 * - https://secure.php.net/manual/en/function.setcookie.php
180 public function logout()
182 if (isset($this->session
)) {
183 unset($this->session
['ip']);
184 unset($this->session
['expires_on']);
185 unset($this->session
['username']);
186 unset($this->session
['visibility']);
191 * Check whether the session has expired
193 * @param string $clientIpId Client IP address identifier
195 * @return bool true if the session has expired, false otherwise
197 public function hasSessionExpired()
199 if (empty($this->session
['expires_on'])) {
202 if (time() >= $this->session
['expires_on']) {
209 * Check whether the client IP address has changed
211 * @param string $clientIpId Client IP address identifier
213 * @return bool true if the IP has changed, false if it has not, or
214 * if session protection has been disabled
216 public function hasClientIpChanged($clientIpId)
218 if ($this->conf
->get('security.session_protection_disabled') === true) {
221 if (isset($this->session
['ip']) && $this->session
['ip'] === $clientIpId) {
227 /** @return array Local reference to the global $_SESSION array */
228 public function getSession(): array
230 return $this->session
;
234 * @param mixed $default value which will be returned if the $key is undefined
236 * @return mixed Content stored in session
238 public function getSessionParameter(string $key, $default = null)
240 return $this->session
[$key] ?? $default;
244 * Store a variable in user session.
246 * @param string $key Session key
247 * @param mixed $value Session value to store
251 public function setSessionParameter(string $key, $value): self
253 $this->session
[$key] = $value;
259 * Store a variable in user session.
261 * @param string $key Session key
265 public function deleteSessionParameter(string $key): self
267 unset($this->session
[$key]);
272 public function getSavePath(): string
274 return $this->savePath
;
278 * Next public functions wrapping native PHP session API.
281 public function destroy(): bool
285 return session_destroy();
288 public function start(): bool
290 if (session_status() === PHP_SESSION_ACTIVE
) {
294 return session_start();
298 * Be careful, return type of session_set_cookie_params() changed between PHP 7.1 and 7.2.
300 public function cookieParameters(int $lifeTime, string $path, string $domain): void
302 session_set_cookie_params($lifeTime, $path, $domain);
305 public function regenerateId(bool $deleteOldSession = false): bool
307 return session_regenerate_id($deleteOldSession);