5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
26 use Psr\Log\LoggerInterface
;
31 * Manages data for an an authenticated session
33 * A Session represents the fact that the current HTTP request is part of a
34 * session. There are two broad types of Sessions, based on whether they
35 * return true or false from self::canSetUser():
36 * * When true (mutable), the Session identifies multiple requests as part of
37 * a session generically, with no tie to a particular user.
38 * * When false (immutable), the Session identifies multiple requests as part
39 * of a session by identifying and authenticating the request itself as
40 * belonging to a particular user.
42 * The Session object also serves as a replacement for PHP's $_SESSION,
43 * managing access to per-session data.
48 final class Session
implements \Countable
, \Iterator
, \ArrayAccess
{
49 /** @var null|string[] Encryption algorithm to use */
50 private static $encryptionAlgorithm = null;
52 /** @var SessionBackend Session backend */
55 /** @var int Session index */
58 /** @var LoggerInterface */
62 * @param SessionBackend $backend
64 * @param LoggerInterface $logger
66 public function __construct( SessionBackend
$backend, $index, LoggerInterface
$logger ) {
67 $this->backend
= $backend;
68 $this->index
= $index;
69 $this->logger
= $logger;
72 public function __destruct() {
73 $this->backend
->deregisterSession( $this->index
);
77 * Returns the session ID
80 public function getId() {
81 return $this->backend
->getId();
85 * Returns the SessionId object
86 * @private For internal use by WebRequest
89 public function getSessionId() {
90 return $this->backend
->getSessionId();
94 * Changes the session ID
95 * @return string New ID (might be the same as the old)
97 public function resetId() {
98 return $this->backend
->resetId();
102 * Fetch the SessionProvider for this session
103 * @return SessionProviderInterface
105 public function getProvider() {
106 return $this->backend
->getProvider();
110 * Indicate whether this session is persisted across requests
112 * For example, if cookies are set.
116 public function isPersistent() {
117 return $this->backend
->isPersistent();
121 * Make this session persisted across requests
123 * If the session is already persistent, equivalent to calling
126 public function persist() {
127 $this->backend
->persist();
131 * Make this session not be persisted across requests
133 * This will remove persistence information (e.g. delete cookies)
134 * from the associated WebRequest(s), and delete session data in the
135 * backend. The session data will still be available via get() until
136 * the end of the request.
138 public function unpersist() {
139 $this->backend
->unpersist();
143 * Indicate whether the user should be remembered independently of the
147 public function shouldRememberUser() {
148 return $this->backend
->shouldRememberUser();
152 * Set whether the user should be remembered independently of the session
154 * @param bool $remember
156 public function setRememberUser( $remember ) {
157 $this->backend
->setRememberUser( $remember );
161 * Returns the request associated with this session
164 public function getRequest() {
165 return $this->backend
->getRequest( $this->index
);
169 * Returns the authenticated user for this session
172 public function getUser() {
173 return $this->backend
->getUser();
177 * Fetch the rights allowed the user when this session is active.
178 * @return null|string[] Allowed user rights, or null to allow all.
180 public function getAllowedUserRights() {
181 return $this->backend
->getAllowedUserRights();
185 * Indicate whether the session user info can be changed
188 public function canSetUser() {
189 return $this->backend
->canSetUser();
193 * Set a new user for this session
194 * @note This should only be called when the user has been authenticated
195 * @param User $user User to set on the session.
196 * This may become a "UserValue" in the future, or User may be refactored
199 public function setUser( $user ) {
200 $this->backend
->setUser( $user );
204 * Get a suggested username for the login form
205 * @return string|null
207 public function suggestLoginUsername() {
208 return $this->backend
->suggestLoginUsername( $this->index
);
212 * Whether HTTPS should be forced
215 public function shouldForceHTTPS() {
216 return $this->backend
->shouldForceHTTPS();
220 * Set whether HTTPS should be forced
223 public function setForceHTTPS( $force ) {
224 $this->backend
->setForceHTTPS( $force );
228 * Fetch the "logged out" timestamp
231 public function getLoggedOutTimestamp() {
232 return $this->backend
->getLoggedOutTimestamp();
236 * Set the "logged out" timestamp
239 public function setLoggedOutTimestamp( $ts ) {
240 $this->backend
->setLoggedOutTimestamp( $ts );
244 * Fetch provider metadata
245 * @protected For use by SessionProvider subclasses only
248 public function getProviderMetadata() {
249 return $this->backend
->getProviderMetadata();
253 * Delete all session data and clear the user (if possible)
255 public function clear() {
256 $data = &$this->backend
->getData();
259 $this->backend
->dirty();
261 if ( $this->backend
->canSetUser() ) {
262 $this->backend
->setUser( new User
);
264 $this->backend
->save();
270 * Resets the TTL in the backend store if the session is near expiring, and
271 * re-persists the session to any active WebRequests if persistent.
273 public function renew() {
274 $this->backend
->renew();
278 * Fetch a copy of this session attached to an alternative WebRequest
280 * Actions on the copy will affect this session too, and vice versa.
282 * @param WebRequest $request Any existing session associated with this
283 * WebRequest object will be overwritten.
286 public function sessionWithRequest( WebRequest
$request ) {
287 $request->setSessionId( $this->backend
->getSessionId() );
288 return $this->backend
->getSession( $request );
292 * Fetch a value from the session
293 * @param string|int $key
294 * @param mixed|null $default Returned if $this->exists( $key ) would be false
297 public function get( $key, $default = null ) {
298 $data = &$this->backend
->getData();
299 return array_key_exists( $key, $data ) ?
$data[$key] : $default;
303 * Test if a value exists in the session
304 * @note Unlike isset(), null values are considered to exist.
305 * @param string|int $key
308 public function exists( $key ) {
309 $data = &$this->backend
->getData();
310 return array_key_exists( $key, $data );
314 * Set a value in the session
315 * @param string|int $key
316 * @param mixed $value
318 public function set( $key, $value ) {
319 $data = &$this->backend
->getData();
320 if ( !array_key_exists( $key, $data ) ||
$data[$key] !== $value ) {
321 $data[$key] = $value;
322 $this->backend
->dirty();
327 * Remove a value from the session
328 * @param string|int $key
330 public function remove( $key ) {
331 $data = &$this->backend
->getData();
332 if ( array_key_exists( $key, $data ) ) {
333 unset( $data[$key] );
334 $this->backend
->dirty();
339 * Fetch a CSRF token from the session
341 * Note that this does not persist the session, which you'll probably want
342 * to do if you want the token to actually be useful.
344 * @param string|string[] $salt Token salt
345 * @param string $key Token key
348 public function getToken( $salt = '', $key = 'default' ) {
350 $secrets = $this->get( 'wsTokenSecrets' );
351 if ( !is_array( $secrets ) ) {
354 if ( isset( $secrets[$key] ) && is_string( $secrets[$key] ) ) {
355 $secret = $secrets[$key];
357 $secret = \MWCryptRand
::generateHex( 32 );
358 $secrets[$key] = $secret;
359 $this->set( 'wsTokenSecrets', $secrets );
362 if ( is_array( $salt ) ) {
363 $salt = implode( '|', $salt );
365 return new Token( $secret, (string)$salt, $new );
369 * Remove a CSRF token from the session
371 * The next call to self::getToken() with $key will generate a new secret.
373 * @param string $key Token key
375 public function resetToken( $key = 'default' ) {
376 $secrets = $this->get( 'wsTokenSecrets' );
377 if ( is_array( $secrets ) && isset( $secrets[$key] ) ) {
378 unset( $secrets[$key] );
379 $this->set( 'wsTokenSecrets', $secrets );
384 * Remove all CSRF tokens from the session
386 public function resetAllTokens() {
387 $this->remove( 'wsTokenSecrets' );
391 * Fetch the secret keys for self::setSecret() and self::getSecret().
392 * @return string[] Encryption key, HMAC key
394 private function getSecretKeys() {
395 global $wgSessionSecret, $wgSecretKey, $wgSessionPbkdf2Iterations;
397 $wikiSecret = $wgSessionSecret ?
: $wgSecretKey;
398 $userSecret = $this->get( 'wsSessionSecret', null );
399 if ( $userSecret === null ) {
400 $userSecret = \MWCryptRand
::generateHex( 32 );
401 $this->set( 'wsSessionSecret', $userSecret );
403 $iterations = $this->get( 'wsSessionPbkdf2Iterations', null );
404 if ( $iterations === null ) {
405 $iterations = $wgSessionPbkdf2Iterations;
406 $this->set( 'wsSessionPbkdf2Iterations', $iterations );
409 $keymats = hash_pbkdf2( 'sha256', $wikiSecret, $userSecret, $iterations, 64, true );
411 substr( $keymats, 0, 32 ),
412 substr( $keymats, 32, 32 ),
417 * Decide what type of encryption to use, based on system capabilities.
420 private static function getEncryptionAlgorithm() {
421 global $wgSessionInsecureSecrets;
423 if ( self
::$encryptionAlgorithm === null ) {
424 if ( function_exists( 'openssl_encrypt' ) ) {
425 $methods = openssl_get_cipher_methods();
426 if ( in_array( 'aes-256-ctr', $methods, true ) ) {
427 self
::$encryptionAlgorithm = [ 'openssl', 'aes-256-ctr' ];
428 return self
::$encryptionAlgorithm;
430 if ( in_array( 'aes-256-cbc', $methods, true ) ) {
431 self
::$encryptionAlgorithm = [ 'openssl', 'aes-256-cbc' ];
432 return self
::$encryptionAlgorithm;
436 if ( $wgSessionInsecureSecrets ) {
437 // @todo: import a pure-PHP library for AES instead of this
438 self
::$encryptionAlgorithm = [ 'insecure' ];
439 return self
::$encryptionAlgorithm;
442 throw new \
BadMethodCallException(
443 'Encryption is not available. You really should install the PHP OpenSSL extension. ' .
444 'But if you really can\'t and you\'re willing ' .
445 'to accept insecure storage of sensitive session data, set ' .
446 '$wgSessionInsecureSecrets = true in LocalSettings.php to make this exception go away.'
450 return self
::$encryptionAlgorithm;
454 * Set a value in the session, encrypted
456 * This relies on the secrecy of $wgSecretKey (by default), or $wgSessionSecret.
458 * @param string|int $key
459 * @param mixed $value
461 public function setSecret( $key, $value ) {
462 list( $encKey, $hmacKey ) = $this->getSecretKeys();
463 $serialized = serialize( $value );
465 // The code for encryption (with OpenSSL) and sealing is taken from
466 // Chris Steipp's OATHAuthUtils class in Extension::OATHAuth.
469 // @todo: import a pure-PHP library for AES instead of doing $wgSessionInsecureSecrets
470 $iv = random_bytes( 16 );
471 $algorithm = self
::getEncryptionAlgorithm();
472 switch ( $algorithm[0] ) {
474 $ciphertext = openssl_encrypt( $serialized, $algorithm[1], $encKey, OPENSSL_RAW_DATA
, $iv );
475 if ( $ciphertext === false ) {
476 throw new \
UnexpectedValueException( 'Encryption failed: ' . openssl_error_string() );
480 $ex = new \
Exception( 'No encryption is available, storing data as plain text' );
481 $this->logger
->warning( $ex->getMessage(), [ 'exception' => $ex ] );
482 $ciphertext = $serialized;
485 throw new \
LogicException( 'invalid algorithm' );
489 $sealed = base64_encode( $iv ) . '.' . base64_encode( $ciphertext );
490 $hmac = hash_hmac( 'sha256', $sealed, $hmacKey, true );
491 $encrypted = base64_encode( $hmac ) . '.' . $sealed;
494 $this->set( $key, $encrypted );
498 * Fetch a value from the session that was set with self::setSecret()
499 * @param string|int $key
500 * @param mixed|null $default Returned if $this->exists( $key ) would be false or decryption fails
503 public function getSecret( $key, $default = null ) {
505 $encrypted = $this->get( $key, null );
506 if ( $encrypted === null ) {
510 // The code for unsealing, checking, and decrypting (with OpenSSL) is
511 // taken from Chris Steipp's OATHAuthUtils class in
512 // Extension::OATHAuth.
515 $pieces = explode( '.', $encrypted, 4 );
516 if ( count( $pieces ) !== 3 ) {
517 $ex = new \
Exception( 'Invalid sealed-secret format' );
518 $this->logger
->warning( $ex->getMessage(), [ 'exception' => $ex ] );
521 list( $hmac, $iv, $ciphertext ) = $pieces;
522 list( $encKey, $hmacKey ) = $this->getSecretKeys();
523 $integCalc = hash_hmac( 'sha256', $iv . '.' . $ciphertext, $hmacKey, true );
524 if ( !hash_equals( $integCalc, base64_decode( $hmac ) ) ) {
525 $ex = new \
Exception( 'Sealed secret has been tampered with, aborting.' );
526 $this->logger
->warning( $ex->getMessage(), [ 'exception' => $ex ] );
531 $algorithm = self
::getEncryptionAlgorithm();
532 switch ( $algorithm[0] ) {
534 $serialized = openssl_decrypt( base64_decode( $ciphertext ), $algorithm[1], $encKey,
535 OPENSSL_RAW_DATA
, base64_decode( $iv ) );
536 if ( $serialized === false ) {
537 $ex = new \
Exception( 'Decyption failed: ' . openssl_error_string() );
538 $this->logger
->debug( $ex->getMessage(), [ 'exception' => $ex ] );
543 $ex = new \
Exception(
544 'No encryption is available, retrieving data that was stored as plain text'
546 $this->logger
->warning( $ex->getMessage(), [ 'exception' => $ex ] );
547 $serialized = base64_decode( $ciphertext );
550 throw new \
LogicException( 'invalid algorithm' );
553 $value = unserialize( $serialized );
554 if ( $value === false && $serialized !== serialize( false ) ) {
561 * Delay automatic saving while multiple updates are being made
563 * Calls to save() or clear() will not be delayed.
565 * @return \Wikimedia\ScopedCallback When this goes out of scope, a save will be triggered
567 public function delaySave() {
568 return $this->backend
->delaySave();
574 * This will update the backend data and might re-persist the session
577 public function save() {
578 $this->backend
->save();
582 * @name Interface methods
587 public function count() {
588 $data = &$this->backend
->getData();
589 return count( $data );
593 public function current() {
594 $data = &$this->backend
->getData();
595 return current( $data );
599 public function key() {
600 $data = &$this->backend
->getData();
605 public function next() {
606 $data = &$this->backend
->getData();
611 public function rewind() {
612 $data = &$this->backend
->getData();
617 public function valid() {
618 $data = &$this->backend
->getData();
619 return key( $data ) !== null;
623 * @note Despite the name, this seems to be intended to implement isset()
624 * rather than array_key_exists(). So do that.
627 public function offsetExists( $offset ) {
628 $data = &$this->backend
->getData();
629 return isset( $data[$offset] );
633 * @note This supports indirect modifications but can't mark the session
634 * dirty when those happen. SessionBackend::save() checks the hash of the
635 * data to detect such changes.
636 * @note Accessing a nonexistent key via this mechanism causes that key to
637 * be created with a null value, and does not raise a PHP warning.
640 public function &offsetGet( $offset ) {
641 $data = &$this->backend
->getData();
642 if ( !array_key_exists( $offset, $data ) ) {
643 $ex = new \
Exception( "Undefined index (auto-adds to session with a null value): $offset" );
644 $this->logger
->debug( $ex->getMessage(), [ 'exception' => $ex ] );
646 return $data[$offset];
650 public function offsetSet( $offset, $value ) {
651 $this->set( $offset, $value );
655 public function offsetUnset( $offset ) {
656 $this->remove( $offset );