summaryrefslogtreecommitdiff
path: root/www/wiki/includes/session/Session.php
blob: 024bf9a2b0eafe074d9f600e2dd0bce9adec6d60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<?php
/**
 * MediaWiki session
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Session
 */

namespace MediaWiki\Session;

use Psr\Log\LoggerInterface;
use User;
use WebRequest;

/**
 * Manages data for an an authenticated session
 *
 * A Session represents the fact that the current HTTP request is part of a
 * session. There are two broad types of Sessions, based on whether they
 * return true or false from self::canSetUser():
 * * When true (mutable), the Session identifies multiple requests as part of
 *   a session generically, with no tie to a particular user.
 * * When false (immutable), the Session identifies multiple requests as part
 *   of a session by identifying and authenticating the request itself as
 *   belonging to a particular user.
 *
 * The Session object also serves as a replacement for PHP's $_SESSION,
 * managing access to per-session data.
 *
 * @ingroup Session
 * @since 1.27
 */
final class Session implements \Countable, \Iterator, \ArrayAccess {
	/** @var null|string[] Encryption algorithm to use */
	private static $encryptionAlgorithm = null;

	/** @var SessionBackend Session backend */
	private $backend;

	/** @var int Session index */
	private $index;

	/** @var LoggerInterface */
	private $logger;

	/**
	 * @param SessionBackend $backend
	 * @param int $index
	 * @param LoggerInterface $logger
	 */
	public function __construct( SessionBackend $backend, $index, LoggerInterface $logger ) {
		$this->backend = $backend;
		$this->index = $index;
		$this->logger = $logger;
	}

	public function __destruct() {
		$this->backend->deregisterSession( $this->index );
	}

	/**
	 * Returns the session ID
	 * @return string
	 */
	public function getId() {
		return $this->backend->getId();
	}

	/**
	 * Returns the SessionId object
	 * @private For internal use by WebRequest
	 * @return SessionId
	 */
	public function getSessionId() {
		return $this->backend->getSessionId();
	}

	/**
	 * Changes the session ID
	 * @return string New ID (might be the same as the old)
	 */
	public function resetId() {
		return $this->backend->resetId();
	}

	/**
	 * Fetch the SessionProvider for this session
	 * @return SessionProviderInterface
	 */
	public function getProvider() {
		return $this->backend->getProvider();
	}

	/**
	 * Indicate whether this session is persisted across requests
	 *
	 * For example, if cookies are set.
	 *
	 * @return bool
	 */
	public function isPersistent() {
		return $this->backend->isPersistent();
	}

	/**
	 * Make this session persisted across requests
	 *
	 * If the session is already persistent, equivalent to calling
	 * $this->renew().
	 */
	public function persist() {
		$this->backend->persist();
	}

	/**
	 * Make this session not be persisted across requests
	 *
	 * This will remove persistence information (e.g. delete cookies)
	 * from the associated WebRequest(s), and delete session data in the
	 * backend. The session data will still be available via get() until
	 * the end of the request.
	 */
	public function unpersist() {
		$this->backend->unpersist();
	}

	/**
	 * Indicate whether the user should be remembered independently of the
	 * session ID.
	 * @return bool
	 */
	public function shouldRememberUser() {
		return $this->backend->shouldRememberUser();
	}

	/**
	 * Set whether the user should be remembered independently of the session
	 * ID.
	 * @param bool $remember
	 */
	public function setRememberUser( $remember ) {
		$this->backend->setRememberUser( $remember );
	}

	/**
	 * Returns the request associated with this session
	 * @return WebRequest
	 */
	public function getRequest() {
		return $this->backend->getRequest( $this->index );
	}

	/**
	 * Returns the authenticated user for this session
	 * @return User
	 */
	public function getUser() {
		return $this->backend->getUser();
	}

	/**
	 * Fetch the rights allowed the user when this session is active.
	 * @return null|string[] Allowed user rights, or null to allow all.
	 */
	public function getAllowedUserRights() {
		return $this->backend->getAllowedUserRights();
	}

	/**
	 * Indicate whether the session user info can be changed
	 * @return bool
	 */
	public function canSetUser() {
		return $this->backend->canSetUser();
	}

	/**
	 * Set a new user for this session
	 * @note This should only be called when the user has been authenticated
	 * @param User $user User to set on the session.
	 *   This may become a "UserValue" in the future, or User may be refactored
	 *   into such.
	 */
	public function setUser( $user ) {
		$this->backend->setUser( $user );
	}

	/**
	 * Get a suggested username for the login form
	 * @return string|null
	 */
	public function suggestLoginUsername() {
		return $this->backend->suggestLoginUsername( $this->index );
	}

	/**
	 * Whether HTTPS should be forced
	 * @return bool
	 */
	public function shouldForceHTTPS() {
		return $this->backend->shouldForceHTTPS();
	}

	/**
	 * Set whether HTTPS should be forced
	 * @param bool $force
	 */
	public function setForceHTTPS( $force ) {
		$this->backend->setForceHTTPS( $force );
	}

	/**
	 * Fetch the "logged out" timestamp
	 * @return int
	 */
	public function getLoggedOutTimestamp() {
		return $this->backend->getLoggedOutTimestamp();
	}

	/**
	 * Set the "logged out" timestamp
	 * @param int $ts
	 */
	public function setLoggedOutTimestamp( $ts ) {
		$this->backend->setLoggedOutTimestamp( $ts );
	}

	/**
	 * Fetch provider metadata
	 * @protected For use by SessionProvider subclasses only
	 * @return mixed
	 */
	public function getProviderMetadata() {
		return $this->backend->getProviderMetadata();
	}

	/**
	 * Delete all session data and clear the user (if possible)
	 */
	public function clear() {
		$data = &$this->backend->getData();
		if ( $data ) {
			$data = [];
			$this->backend->dirty();
		}
		if ( $this->backend->canSetUser() ) {
			$this->backend->setUser( new User );
		}
		$this->backend->save();
	}

	/**
	 * Renew the session
	 *
	 * Resets the TTL in the backend store if the session is near expiring, and
	 * re-persists the session to any active WebRequests if persistent.
	 */
	public function renew() {
		$this->backend->renew();
	}

	/**
	 * Fetch a copy of this session attached to an alternative WebRequest
	 *
	 * Actions on the copy will affect this session too, and vice versa.
	 *
	 * @param WebRequest $request Any existing session associated with this
	 *  WebRequest object will be overwritten.
	 * @return Session
	 */
	public function sessionWithRequest( WebRequest $request ) {
		$request->setSessionId( $this->backend->getSessionId() );
		return $this->backend->getSession( $request );
	}

	/**
	 * Fetch a value from the session
	 * @param string|int $key
	 * @param mixed $default Returned if $this->exists( $key ) would be false
	 * @return mixed
	 */
	public function get( $key, $default = null ) {
		$data = &$this->backend->getData();
		return array_key_exists( $key, $data ) ? $data[$key] : $default;
	}

	/**
	 * Test if a value exists in the session
	 * @note Unlike isset(), null values are considered to exist.
	 * @param string|int $key
	 * @return bool
	 */
	public function exists( $key ) {
		$data = &$this->backend->getData();
		return array_key_exists( $key, $data );
	}

	/**
	 * Set a value in the session
	 * @param string|int $key
	 * @param mixed $value
	 */
	public function set( $key, $value ) {
		$data = &$this->backend->getData();
		if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
			$data[$key] = $value;
			$this->backend->dirty();
		}
	}

	/**
	 * Remove a value from the session
	 * @param string|int $key
	 */
	public function remove( $key ) {
		$data = &$this->backend->getData();
		if ( array_key_exists( $key, $data ) ) {
			unset( $data[$key] );
			$this->backend->dirty();
		}
	}

	/**
	 * Fetch a CSRF token from the session
	 *
	 * Note that this does not persist the session, which you'll probably want
	 * to do if you want the token to actually be useful.
	 *
	 * @param string|string[] $salt Token salt
	 * @param string $key Token key
	 * @return Token
	 */
	public function getToken( $salt = '', $key = 'default' ) {
		$new = false;
		$secrets = $this->get( 'wsTokenSecrets' );
		if ( !is_array( $secrets ) ) {
			$secrets = [];
		}
		if ( isset( $secrets[$key] ) && is_string( $secrets[$key] ) ) {
			$secret = $secrets[$key];
		} else {
			$secret = \MWCryptRand::generateHex( 32 );
			$secrets[$key] = $secret;
			$this->set( 'wsTokenSecrets', $secrets );
			$new = true;
		}
		if ( is_array( $salt ) ) {
			$salt = implode( '|', $salt );
		}
		return new Token( $secret, (string)$salt, $new );
	}

	/**
	 * Remove a CSRF token from the session
	 *
	 * The next call to self::getToken() with $key will generate a new secret.
	 *
	 * @param string $key Token key
	 */
	public function resetToken( $key = 'default' ) {
		$secrets = $this->get( 'wsTokenSecrets' );
		if ( is_array( $secrets ) && isset( $secrets[$key] ) ) {
			unset( $secrets[$key] );
			$this->set( 'wsTokenSecrets', $secrets );
		}
	}

	/**
	 * Remove all CSRF tokens from the session
	 */
	public function resetAllTokens() {
		$this->remove( 'wsTokenSecrets' );
	}

	/**
	 * Fetch the secret keys for self::setSecret() and self::getSecret().
	 * @return string[] Encryption key, HMAC key
	 */
	private function getSecretKeys() {
		global $wgSessionSecret, $wgSecretKey, $wgSessionPbkdf2Iterations;

		$wikiSecret = $wgSessionSecret ?: $wgSecretKey;
		$userSecret = $this->get( 'wsSessionSecret', null );
		if ( $userSecret === null ) {
			$userSecret = \MWCryptRand::generateHex( 32 );
			$this->set( 'wsSessionSecret', $userSecret );
		}
		$iterations = $this->get( 'wsSessionPbkdf2Iterations', null );
		if ( $iterations === null ) {
			$iterations = $wgSessionPbkdf2Iterations;
			$this->set( 'wsSessionPbkdf2Iterations', $iterations );
		}

		$keymats = hash_pbkdf2( 'sha256', $wikiSecret, $userSecret, $iterations, 64, true );
		return [
			substr( $keymats, 0, 32 ),
			substr( $keymats, 32, 32 ),
		];
	}

	/**
	 * Decide what type of encryption to use, based on system capabilities.
	 * @return array
	 */
	private static function getEncryptionAlgorithm() {
		global $wgSessionInsecureSecrets;

		if ( self::$encryptionAlgorithm === null ) {
			if ( function_exists( 'openssl_encrypt' ) ) {
				$methods = openssl_get_cipher_methods();
				if ( in_array( 'aes-256-ctr', $methods, true ) ) {
					self::$encryptionAlgorithm = [ 'openssl', 'aes-256-ctr' ];
					return self::$encryptionAlgorithm;
				}
				if ( in_array( 'aes-256-cbc', $methods, true ) ) {
					self::$encryptionAlgorithm = [ 'openssl', 'aes-256-cbc' ];
					return self::$encryptionAlgorithm;
				}
			}

			if ( function_exists( 'mcrypt_encrypt' )
				&& in_array( 'rijndael-128', mcrypt_list_algorithms(), true )
			) {
				$modes = mcrypt_list_modes();
				if ( in_array( 'ctr', $modes, true ) ) {
					self::$encryptionAlgorithm = [ 'mcrypt', 'rijndael-128', 'ctr' ];
					return self::$encryptionAlgorithm;
				}
				if ( in_array( 'cbc', $modes, true ) ) {
					self::$encryptionAlgorithm = [ 'mcrypt', 'rijndael-128', 'cbc' ];
					return self::$encryptionAlgorithm;
				}
			}

			if ( $wgSessionInsecureSecrets ) {
				// @todo: import a pure-PHP library for AES instead of this
				self::$encryptionAlgorithm = [ 'insecure' ];
				return self::$encryptionAlgorithm;
			}

			throw new \BadMethodCallException(
				'Encryption is not available. You really should install the PHP OpenSSL extension, ' .
				'or failing that the mcrypt extension. But if you really can\'t and you\'re willing ' .
				'to accept insecure storage of sensitive session data, set ' .
				'$wgSessionInsecureSecrets = true in LocalSettings.php to make this exception go away.'
			);
		}

		return self::$encryptionAlgorithm;
	}

	/**
	 * Set a value in the session, encrypted
	 *
	 * This relies on the secrecy of $wgSecretKey (by default), or $wgSessionSecret.
	 *
	 * @param string|int $key
	 * @param mixed $value
	 */
	public function setSecret( $key, $value ) {
		list( $encKey, $hmacKey ) = $this->getSecretKeys();
		$serialized = serialize( $value );

		// The code for encryption (with OpenSSL) and sealing is taken from
		// Chris Steipp's OATHAuthUtils class in Extension::OATHAuth.

		// Encrypt
		// @todo: import a pure-PHP library for AES instead of doing $wgSessionInsecureSecrets
		$iv = \MWCryptRand::generate( 16, true );
		$algorithm = self::getEncryptionAlgorithm();
		switch ( $algorithm[0] ) {
			case 'openssl':
				$ciphertext = openssl_encrypt( $serialized, $algorithm[1], $encKey, OPENSSL_RAW_DATA, $iv );
				if ( $ciphertext === false ) {
					throw new \UnexpectedValueException( 'Encryption failed: ' . openssl_error_string() );
				}
				break;
			case 'mcrypt':
				// PKCS7 padding
				$blocksize = mcrypt_get_block_size( $algorithm[1], $algorithm[2] );
				$pad = $blocksize - ( strlen( $serialized ) % $blocksize );
				$serialized .= str_repeat( chr( $pad ), $pad );

				$ciphertext = mcrypt_encrypt( $algorithm[1], $encKey, $serialized, $algorithm[2], $iv );
				if ( $ciphertext === false ) {
					throw new \UnexpectedValueException( 'Encryption failed' );
				}
				break;
			case 'insecure':
				$ex = new \Exception( 'No encryption is available, storing data as plain text' );
				$this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
				$ciphertext = $serialized;
				break;
			default:
				throw new \LogicException( 'invalid algorithm' );
		}

		// Seal
		$sealed = base64_encode( $iv ) . '.' . base64_encode( $ciphertext );
		$hmac = hash_hmac( 'sha256', $sealed, $hmacKey, true );
		$encrypted = base64_encode( $hmac ) . '.' . $sealed;

		// Store
		$this->set( $key, $encrypted );
	}

	/**
	 * Fetch a value from the session that was set with self::setSecret()
	 * @param string|int $key
	 * @param mixed $default Returned if $this->exists( $key ) would be false or decryption fails
	 * @return mixed
	 */
	public function getSecret( $key, $default = null ) {
		// Fetch
		$encrypted = $this->get( $key, null );
		if ( $encrypted === null ) {
			return $default;
		}

		// The code for unsealing, checking, and decrypting (with OpenSSL) is
		// taken from Chris Steipp's OATHAuthUtils class in
		// Extension::OATHAuth.

		// Unseal and check
		$pieces = explode( '.', $encrypted );
		if ( count( $pieces ) !== 3 ) {
			$ex = new \Exception( 'Invalid sealed-secret format' );
			$this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
			return $default;
		}
		list( $hmac, $iv, $ciphertext ) = $pieces;
		list( $encKey, $hmacKey ) = $this->getSecretKeys();
		$integCalc = hash_hmac( 'sha256', $iv . '.' . $ciphertext, $hmacKey, true );
		if ( !hash_equals( $integCalc, base64_decode( $hmac ) ) ) {
			$ex = new \Exception( 'Sealed secret has been tampered with, aborting.' );
			$this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
			return $default;
		}

		// Decrypt
		$algorithm = self::getEncryptionAlgorithm();
		switch ( $algorithm[0] ) {
			case 'openssl':
				$serialized = openssl_decrypt( base64_decode( $ciphertext ), $algorithm[1], $encKey,
					OPENSSL_RAW_DATA, base64_decode( $iv ) );
				if ( $serialized === false ) {
					$ex = new \Exception( 'Decyption failed: ' . openssl_error_string() );
					$this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
					return $default;
				}
				break;
			case 'mcrypt':
				$serialized = mcrypt_decrypt( $algorithm[1], $encKey, base64_decode( $ciphertext ),
					$algorithm[2], base64_decode( $iv ) );
				if ( $serialized === false ) {
					$ex = new \Exception( 'Decyption failed' );
					$this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
					return $default;
				}

				// Remove PKCS7 padding
				$pad = ord( substr( $serialized, -1 ) );
				$serialized = substr( $serialized, 0, -$pad );
				break;
			case 'insecure':
				$ex = new \Exception(
					'No encryption is available, retrieving data that was stored as plain text'
				);
				$this->logger->warning( $ex->getMessage(), [ 'exception' => $ex ] );
				$serialized = base64_decode( $ciphertext );
				break;
			default:
				throw new \LogicException( 'invalid algorithm' );
		}

		$value = unserialize( $serialized );
		if ( $value === false && $serialized !== serialize( false ) ) {
			$value = $default;
		}
		return $value;
	}

	/**
	 * Delay automatic saving while multiple updates are being made
	 *
	 * Calls to save() or clear() will not be delayed.
	 *
	 * @return \Wikimedia\ScopedCallback When this goes out of scope, a save will be triggered
	 */
	public function delaySave() {
		return $this->backend->delaySave();
	}

	/**
	 * Save the session
	 *
	 * This will update the backend data and might re-persist the session
	 * if needed.
	 */
	public function save() {
		$this->backend->save();
	}

	/**
	 * @name Interface methods
	 * @{
	 */

	/** @inheritDoc */
	public function count() {
		$data = &$this->backend->getData();
		return count( $data );
	}

	/** @inheritDoc */
	public function current() {
		$data = &$this->backend->getData();
		return current( $data );
	}

	/** @inheritDoc */
	public function key() {
		$data = &$this->backend->getData();
		return key( $data );
	}

	/** @inheritDoc */
	public function next() {
		$data = &$this->backend->getData();
		next( $data );
	}

	/** @inheritDoc */
	public function rewind() {
		$data = &$this->backend->getData();
		reset( $data );
	}

	/** @inheritDoc */
	public function valid() {
		$data = &$this->backend->getData();
		return key( $data ) !== null;
	}

	/**
	 * @note Despite the name, this seems to be intended to implement isset()
	 *  rather than array_key_exists(). So do that.
	 * @inheritDoc
	 */
	public function offsetExists( $offset ) {
		$data = &$this->backend->getData();
		return isset( $data[$offset] );
	}

	/**
	 * @note This supports indirect modifications but can't mark the session
	 *  dirty when those happen. SessionBackend::save() checks the hash of the
	 *  data to detect such changes.
	 * @note Accessing a nonexistent key via this mechanism causes that key to
	 *  be created with a null value, and does not raise a PHP warning.
	 * @inheritDoc
	 */
	public function &offsetGet( $offset ) {
		$data = &$this->backend->getData();
		if ( !array_key_exists( $offset, $data ) ) {
			$ex = new \Exception( "Undefined index (auto-adds to session with a null value): $offset" );
			$this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
		}
		return $data[$offset];
	}

	/** @inheritDoc */
	public function offsetSet( $offset, $value ) {
		$this->set( $offset, $value );
	}

	/** @inheritDoc */
	public function offsetUnset( $offset ) {
		$this->remove( $offset );
	}

	/**@}*/

}