MediaWiki  1.27.2
Session.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
27 use User;
29 
48 final class Session implements \Countable, \Iterator, \ArrayAccess {
50  private static $encryptionAlgorithm = null;
51 
53  private $backend;
54 
56  private $index;
57 
59  private $logger;
60 
66  public function __construct( SessionBackend $backend, $index, LoggerInterface $logger ) {
67  $this->backend = $backend;
68  $this->index = $index;
69  $this->logger = $logger;
70  }
71 
72  public function __destruct() {
73  $this->backend->deregisterSession( $this->index );
74  }
75 
80  public function getId() {
81  return $this->backend->getId();
82  }
83 
89  public function getSessionId() {
90  return $this->backend->getSessionId();
91  }
92 
97  public function resetId() {
98  return $this->backend->resetId();
99  }
100 
105  public function getProvider() {
106  return $this->backend->getProvider();
107  }
108 
116  public function isPersistent() {
117  return $this->backend->isPersistent();
118  }
119 
126  public function persist() {
127  $this->backend->persist();
128  }
129 
133  public function unpersist() {
134  $this->backend->unpersist();
135  }
136 
142  public function shouldRememberUser() {
143  return $this->backend->shouldRememberUser();
144  }
145 
151  public function setRememberUser( $remember ) {
152  $this->backend->setRememberUser( $remember );
153  }
154 
159  public function getRequest() {
160  return $this->backend->getRequest( $this->index );
161  }
162 
167  public function getUser() {
168  return $this->backend->getUser();
169  }
170 
175  public function getAllowedUserRights() {
176  return $this->backend->getAllowedUserRights();
177  }
178 
183  public function canSetUser() {
184  return $this->backend->canSetUser();
185  }
186 
194  public function setUser( $user ) {
195  $this->backend->setUser( $user );
196  }
197 
202  public function suggestLoginUsername() {
203  return $this->backend->suggestLoginUsername( $this->index );
204  }
205 
210  public function shouldForceHTTPS() {
211  return $this->backend->shouldForceHTTPS();
212  }
213 
218  public function setForceHTTPS( $force ) {
219  $this->backend->setForceHTTPS( $force );
220  }
221 
226  public function getLoggedOutTimestamp() {
227  return $this->backend->getLoggedOutTimestamp();
228  }
229 
234  public function setLoggedOutTimestamp( $ts ) {
235  $this->backend->setLoggedOutTimestamp( $ts );
236  }
237 
243  public function getProviderMetadata() {
244  return $this->backend->getProviderMetadata();
245  }
246 
250  public function clear() {
251  $data = &$this->backend->getData();
252  if ( $data ) {
253  $data = [];
254  $this->backend->dirty();
255  }
256  if ( $this->backend->canSetUser() ) {
257  $this->backend->setUser( new User );
258  }
259  $this->backend->save();
260  }
261 
268  public function renew() {
269  $this->backend->renew();
270  }
271 
282  $request->setSessionId( $this->backend->getSessionId() );
283  return $this->backend->getSession( $request );
284  }
285 
292  public function get( $key, $default = null ) {
293  $data = &$this->backend->getData();
294  return array_key_exists( $key, $data ) ? $data[$key] : $default;
295  }
296 
303  public function exists( $key ) {
304  $data = &$this->backend->getData();
305  return array_key_exists( $key, $data );
306  }
307 
313  public function set( $key, $value ) {
314  $data = &$this->backend->getData();
315  if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
316  $data[$key] = $value;
317  $this->backend->dirty();
318  }
319  }
320 
325  public function remove( $key ) {
326  $data = &$this->backend->getData();
327  if ( array_key_exists( $key, $data ) ) {
328  unset( $data[$key] );
329  $this->backend->dirty();
330  }
331  }
332 
343  public function getToken( $salt = '', $key = 'default' ) {
344  $new = false;
345  $secrets = $this->get( 'wsTokenSecrets' );
346  if ( !is_array( $secrets ) ) {
347  $secrets = [];
348  }
349  if ( isset( $secrets[$key] ) && is_string( $secrets[$key] ) ) {
350  $secret = $secrets[$key];
351  } else {
352  $secret = \MWCryptRand::generateHex( 32 );
353  $secrets[$key] = $secret;
354  $this->set( 'wsTokenSecrets', $secrets );
355  $new = true;
356  }
357  if ( is_array( $salt ) ) {
358  $salt = implode( '|', $salt );
359  }
360  return new Token( $secret, (string)$salt, $new );
361  }
362 
370  public function resetToken( $key = 'default' ) {
371  $secrets = $this->get( 'wsTokenSecrets' );
372  if ( is_array( $secrets ) && isset( $secrets[$key] ) ) {
373  unset( $secrets[$key] );
374  $this->set( 'wsTokenSecrets', $secrets );
375  }
376  }
377 
381  public function resetAllTokens() {
382  $this->remove( 'wsTokenSecrets' );
383  }
384 
389  private function getSecretKeys() {
390  global $wgSessionSecret, $wgSecretKey;
391 
392  $wikiSecret = $wgSessionSecret ?: $wgSecretKey;
393  $userSecret = $this->get( 'wsSessionSecret', null );
394  if ( $userSecret === null ) {
395  $userSecret = \MWCryptRand::generateHex( 32 );
396  $this->set( 'wsSessionSecret', $userSecret );
397  }
398 
399  $keymats = hash_pbkdf2( 'sha256', $wikiSecret, $userSecret, 10001, 64, true );
400  return [
401  substr( $keymats, 0, 32 ),
402  substr( $keymats, 32, 32 ),
403  ];
404  }
405 
410  private static function getEncryptionAlgorithm() {
411  global $wgSessionInsecureSecrets;
412 
413  if ( self::$encryptionAlgorithm === null ) {
414  if ( function_exists( 'openssl_encrypt' ) ) {
415  $methods = openssl_get_cipher_methods();
416  if ( in_array( 'aes-256-ctr', $methods, true ) ) {
417  self::$encryptionAlgorithm = [ 'openssl', 'aes-256-ctr' ];
418  return self::$encryptionAlgorithm;
419  }
420  if ( in_array( 'aes-256-cbc', $methods, true ) ) {
421  self::$encryptionAlgorithm = [ 'openssl', 'aes-256-cbc' ];
422  return self::$encryptionAlgorithm;
423  }
424  }
425 
426  if ( function_exists( 'mcrypt_encrypt' )
427  && in_array( 'rijndael-128', mcrypt_list_algorithms(), true )
428  ) {
429  $modes = mcrypt_list_modes();
430  if ( in_array( 'ctr', $modes, true ) ) {
431  self::$encryptionAlgorithm = [ 'mcrypt', 'rijndael-128', 'ctr' ];
432  return self::$encryptionAlgorithm;
433  }
434  if ( in_array( 'cbc', $modes, true ) ) {
435  self::$encryptionAlgorithm = [ 'mcrypt', 'rijndael-128', 'cbc' ];
436  return self::$encryptionAlgorithm;
437  }
438  }
439 
440  if ( $wgSessionInsecureSecrets ) {
441  // @todo: import a pure-PHP library for AES instead of this
442  self::$encryptionAlgorithm = [ 'insecure' ];
443  return self::$encryptionAlgorithm;
444  }
445 
446  throw new \BadMethodCallException(
447  'Encryption is not available. You really should install the PHP OpenSSL extension, ' .
448  'or failing that the mcrypt extension. But if you really can\'t and you\'re willing ' .
449  'to accept insecure storage of sensitive session data, set ' .
450  '$wgSessionInsecureSecrets = true in LocalSettings.php to make this exception go away.'
451  );
452  }
453 
454  return self::$encryptionAlgorithm;
455  }
456 
465  public function setSecret( $key, $value ) {
466  list( $encKey, $hmacKey ) = $this->getSecretKeys();
468 
469  // The code for encryption (with OpenSSL) and sealing is taken from
470  // Chris Steipp's OATHAuthUtils class in Extension::OATHAuth.
471 
472  // Encrypt
473  // @todo: import a pure-PHP library for AES instead of doing $wgSessionInsecureSecrets
474  $iv = \MWCryptRand::generate( 16, true );
475  $algorithm = self::getEncryptionAlgorithm();
476  switch ( $algorithm[0] ) {
477  case 'openssl':
478  $ciphertext = openssl_encrypt( $serialized, $algorithm[1], $encKey, OPENSSL_RAW_DATA, $iv );
479  if ( $ciphertext === false ) {
480  throw new \UnexpectedValueException( 'Encryption failed: ' . openssl_error_string() );
481  }
482  break;
483  case 'mcrypt':
484  // PKCS7 padding
485  $blocksize = mcrypt_get_block_size( $algorithm[1], $algorithm[2] );
486  $pad = $blocksize - ( strlen( $serialized ) % $blocksize );
487  $serialized .= str_repeat( chr( $pad ), $pad );
488 
489  $ciphertext = mcrypt_encrypt( $algorithm[1], $encKey, $serialized, $algorithm[2], $iv );
490  if ( $ciphertext === false ) {
491  throw new \UnexpectedValueException( 'Encryption failed' );
492  }
493  break;
494  case 'insecure':
495  $ex = new \Exception( 'No encryption is available, storing data as plain text' );
496  $this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
497  $ciphertext = $serialized;
498  break;
499  default:
500  throw new \LogicException( 'invalid algorithm' );
501  }
502 
503  // Seal
504  $sealed = base64_encode( $iv ) . '.' . base64_encode( $ciphertext );
505  $hmac = hash_hmac( 'sha256', $sealed, $hmacKey, true );
506  $encrypted = base64_encode( $hmac ) . '.' . $sealed;
507 
508  // Store
509  $this->set( $key, $encrypted );
510  }
511 
518  public function getSecret( $key, $default = null ) {
519  // Fetch
520  $encrypted = $this->get( $key, null );
521  if ( $encrypted === null ) {
522  return $default;
523  }
524 
525  // The code for unsealing, checking, and decrypting (with OpenSSL) is
526  // taken from Chris Steipp's OATHAuthUtils class in
527  // Extension::OATHAuth.
528 
529  // Unseal and check
530  $pieces = explode( '.', $encrypted );
531  if ( count( $pieces ) !== 3 ) {
532  $ex = new \Exception( 'Invalid sealed-secret format' );
533  $this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
534  return $default;
535  }
536  list( $hmac, $iv, $ciphertext ) = $pieces;
537  list( $encKey, $hmacKey ) = $this->getSecretKeys();
538  $integCalc = hash_hmac( 'sha256', $iv . '.' . $ciphertext, $hmacKey, true );
539  if ( !hash_equals( $integCalc, base64_decode( $hmac ) ) ) {
540  $ex = new \Exception( 'Sealed secret has been tampered with, aborting.' );
541  $this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
542  return $default;
543  }
544 
545  // Decrypt
546  $algorithm = self::getEncryptionAlgorithm();
547  switch ( $algorithm[0] ) {
548  case 'openssl':
549  $serialized = openssl_decrypt( base64_decode( $ciphertext ), $algorithm[1], $encKey,
550  OPENSSL_RAW_DATA, base64_decode( $iv ) );
551  if ( $serialized === false ) {
552  $ex = new \Exception( 'Decyption failed: ' . openssl_error_string() );
553  $this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
554  return $default;
555  }
556  break;
557  case 'mcrypt':
558  $serialized = mcrypt_decrypt( $algorithm[1], $encKey, base64_decode( $ciphertext ),
559  $algorithm[2], base64_decode( $iv ) );
560  if ( $serialized === false ) {
561  $ex = new \Exception( 'Decyption failed' );
562  $this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
563  return $default;
564  }
565 
566  // Remove PKCS7 padding
567  $pad = ord( substr( $serialized, -1 ) );
568  $serialized = substr( $serialized, 0, -$pad );
569  break;
570  case 'insecure':
571  $ex = new \Exception(
572  'No encryption is available, retrieving data that was stored as plain text'
573  );
574  $this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
575  $serialized = base64_decode( $ciphertext );
576  break;
577  default:
578  throw new \LogicException( 'invalid algorithm' );
579  }
580 
582  if ( $value === false && $serialized !== serialize( false ) ) {
583  $value = $default;
584  }
585  return $value;
586  }
587 
595  public function delaySave() {
596  return $this->backend->delaySave();
597  }
598 
602  public function save() {
603  $this->backend->save();
604  }
605 
611  public function count() {
612  $data = &$this->backend->getData();
613  return count( $data );
614  }
615 
616  public function current() {
617  $data = &$this->backend->getData();
618  return current( $data );
619  }
620 
621  public function key() {
622  $data = &$this->backend->getData();
623  return key( $data );
624  }
625 
626  public function next() {
627  $data = &$this->backend->getData();
628  next( $data );
629  }
630 
631  public function rewind() {
632  $data = &$this->backend->getData();
633  reset( $data );
634  }
635 
636  public function valid() {
637  $data = &$this->backend->getData();
638  return key( $data ) !== null;
639  }
640 
645  public function offsetExists( $offset ) {
646  $data = &$this->backend->getData();
647  return isset( $data[$offset] );
648  }
649 
657  public function &offsetGet( $offset ) {
658  $data = &$this->backend->getData();
659  if ( !array_key_exists( $offset, $data ) ) {
660  $ex = new \Exception( "Undefined index (auto-adds to session with a null value): $offset" );
661  $this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
662  }
663  return $data[$offset];
664  }
665 
666  public function offsetSet( $offset, $value ) {
667  $this->set( $offset, $value );
668  }
669 
670  public function offsetUnset( $offset ) {
671  $this->remove( $offset );
672  }
673 
676 }
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
This is the actual workhorse for Session.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
setForceHTTPS($force)
Set whether HTTPS should be forced.
Definition: Session.php:218
setUser($user)
Set a new user for this session.
Definition: Session.php:194
canSetUser()
Indicate whether the session user info can be changed.
Definition: Session.php:183
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getLoggedOutTimestamp()
Fetch the "logged out" timestamp.
Definition: Session.php:226
resetAllTokens()
Remove all CSRF tokens from the session.
Definition: Session.php:381
$value
set($key, $value)
Set a value in the session.
Definition: Session.php:313
exists($key)
Test if a value exists in the session.
Definition: Session.php:303
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
setLoggedOutTimestamp($ts)
Set the "logged out" timestamp.
Definition: Session.php:234
getRequest()
Returns the request associated with this session.
Definition: Session.php:159
getAllowedUserRights()
Fetch the rights allowed the user when this session is active.
Definition: Session.php:175
renew()
Renew the session.
Definition: Session.php:268
__construct(SessionBackend $backend, $index, LoggerInterface $logger)
Definition: Session.php:66
getSessionId()
Returns the SessionId object.
Definition: Session.php:89
Value object representing a CSRF token.
Definition: Token.php:32
static getEncryptionAlgorithm()
Decide what type of encryption to use, based on system capabilities.
Definition: Session.php:410
unserialize($serialized)
Definition: ApiMessage.php:102
delaySave()
Delay automatic saving while multiple updates are being made.
Definition: Session.php:595
shouldForceHTTPS()
Whether HTTPS should be forced.
Definition: Session.php:210
static null string[] $encryptionAlgorithm
Encryption algorithm to use.
Definition: Session.php:50
sessionWithRequest(WebRequest $request)
Fetch a copy of this session attached to an alternative WebRequest.
Definition: Session.php:281
getProviderMetadata()
Fetch provider metadata.
Definition: Session.php:243
getProvider()
Fetch the SessionProvider for this session.
Definition: Session.php:105
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.
Definition: Session.php:142
Manages data for an an authenticated session.
Definition: Session.php:48
LoggerInterface $logger
Definition: Session.php:59
getSecret($key, $default=null)
Fetch a value from the session that was set with self::setSecret()
Definition: Session.php:518
getId()
Returns the session ID.
Definition: Session.php:80
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
setSessionId(SessionId $sessionId)
Set the session for this request.
Definition: WebRequest.php:711
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
getSecretKeys()
Fetch the secret keys for self::setSecret() and self::getSecret().
Definition: Session.php:389
isPersistent()
Indicate whether this session is persisted across requests.
Definition: Session.php:116
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2418
resetId()
Changes the session ID.
Definition: Session.php:97
int $index
Session index.
Definition: Session.php:56
resetToken($key= 'default')
Remove a CSRF token from the session.
Definition: Session.php:370
offsetSet($offset, $value)
Definition: Session.php:666
getToken($salt= '', $key= 'default')
Fetch a CSRF token from the session.
Definition: Session.php:343
static generateHex($chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format...
setRememberUser($remember)
Set whether the user should be remembered independently of the session ID.
Definition: Session.php:151
suggestLoginUsername()
Get a suggested username for the login form.
Definition: Session.php:202
save()
Save the session.
Definition: Session.php:602
clear()
Delete all session data and clear the user (if possible)
Definition: Session.php:250
SessionBackend $backend
Session backend.
Definition: Session.php:53
setSecret($key, $value)
Set a value in the session, encrypted.
Definition: Session.php:465
getUser()
Returns the authenticated user for this session.
Definition: Session.php:167
serialize()
Definition: ApiMessage.php:94
static generate($bytes, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in raw binary form...
foreach($res as $row) $serialized
unpersist()
Make this session not be persisted across requests.
Definition: Session.php:133
persist()
Make this session persisted across requests.
Definition: Session.php:126