Enforce MW_NO_SESSION, add MW_NO_SESSION_HANDLER
[lhc/web/wiklou.git] / includes / session / SessionManager.php
1 <?php
2 /**
3 * MediaWiki\Session entry point
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Session
22 */
23
24 namespace MediaWiki\Session;
25
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\LogLevel;
28 use BagOStuff;
29 use CachedBagOStuff;
30 use Config;
31 use FauxRequest;
32 use User;
33 use WebRequest;
34
35 /**
36 * This serves as the entry point to the MediaWiki session handling system.
37 *
38 * @ingroup Session
39 * @since 1.27
40 */
41 final class SessionManager implements SessionManagerInterface {
42 /** @var SessionManager|null */
43 private static $instance = null;
44
45 /** @var Session|null */
46 private static $globalSession = null;
47
48 /** @var WebRequest|null */
49 private static $globalSessionRequest = null;
50
51 /** @var LoggerInterface */
52 private $logger;
53
54 /** @var Config */
55 private $config;
56
57 /** @var CachedBagOStuff|null */
58 private $store;
59
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
62
63 /** @var string[] */
64 private $varyCookies = null;
65
66 /** @var array */
67 private $varyHeaders = null;
68
69 /** @var SessionBackend[] */
70 private $allSessionBackends = [];
71
72 /** @var SessionId[] */
73 private $allSessionIds = [];
74
75 /** @var string[] */
76 private $preventUsers = [];
77
78 /**
79 * Get the global SessionManager
80 * @return SessionManagerInterface
81 * (really a SessionManager, but this is to make IDEs less confused)
82 */
83 public static function singleton() {
84 if ( self::$instance === null ) {
85 self::$instance = new self();
86 }
87 return self::$instance;
88 }
89
90 /**
91 * Get the "global" session
92 *
93 * If PHP's session_id() has been set, returns that session. Otherwise
94 * returns the session for RequestContext::getMain()->getRequest().
95 *
96 * @return Session
97 */
98 public static function getGlobalSession() {
99 if ( !PHPSessionHandler::isEnabled() ) {
100 $id = '';
101 } else {
102 $id = session_id();
103 }
104
105 $request = \RequestContext::getMain()->getRequest();
106 if (
107 !self::$globalSession // No global session is set up yet
108 || self::$globalSessionRequest !== $request // The global WebRequest changed
109 || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
110 ) {
111 self::$globalSessionRequest = $request;
112 if ( $id === '' ) {
113 // session_id() wasn't used, so fetch the Session from the WebRequest.
114 // We use $request->getSession() instead of $singleton->getSessionForRequest()
115 // because doing the latter would require a public
116 // "$request->getSessionId()" method that would confuse end
117 // users by returning SessionId|null where they'd expect it to
118 // be short for $request->getSession()->getId(), and would
119 // wind up being a duplicate of the code in
120 // $request->getSession() anyway.
121 self::$globalSession = $request->getSession();
122 } else {
123 // Someone used session_id(), so we need to follow suit.
124 // Note this overwrites whatever session might already be
125 // associated with $request with the one for $id.
126 self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
127 ?: $request->getSession();
128 }
129 }
130 return self::$globalSession;
131 }
132
133 /**
134 * @param array $options
135 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
136 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
137 * - store: BagOStuff to store session data in.
138 */
139 public function __construct( $options = [] ) {
140 if ( isset( $options['config'] ) ) {
141 $this->config = $options['config'];
142 if ( !$this->config instanceof Config ) {
143 throw new \InvalidArgumentException(
144 '$options[\'config\'] must be an instance of Config'
145 );
146 }
147 } else {
148 $this->config = \ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
149 }
150
151 if ( isset( $options['logger'] ) ) {
152 if ( !$options['logger'] instanceof LoggerInterface ) {
153 throw new \InvalidArgumentException(
154 '$options[\'logger\'] must be an instance of LoggerInterface'
155 );
156 }
157 $this->setLogger( $options['logger'] );
158 } else {
159 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
160 }
161
162 if ( isset( $options['store'] ) ) {
163 if ( !$options['store'] instanceof BagOStuff ) {
164 throw new \InvalidArgumentException(
165 '$options[\'store\'] must be an instance of BagOStuff'
166 );
167 }
168 $store = $options['store'];
169 } else {
170 $store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
171 $store->setLogger( $this->logger );
172 }
173 $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
174
175 register_shutdown_function( [ $this, 'shutdown' ] );
176 }
177
178 public function setLogger( LoggerInterface $logger ) {
179 $this->logger = $logger;
180 }
181
182 public function getSessionForRequest( WebRequest $request ) {
183 $info = $this->getSessionInfoForRequest( $request );
184
185 if ( !$info ) {
186 $session = $this->getEmptySession( $request );
187 } else {
188 $session = $this->getSessionFromInfo( $info, $request );
189 }
190 return $session;
191 }
192
193 public function getSessionById( $id, $create = false, WebRequest $request = null ) {
194 if ( !self::validateSessionId( $id ) ) {
195 throw new \InvalidArgumentException( 'Invalid session ID' );
196 }
197 if ( !$request ) {
198 $request = new FauxRequest;
199 }
200
201 $session = null;
202
203 // Test this here to provide a better log message for the common case
204 // of "no such ID"
205 $key = wfMemcKey( 'MWSession', $id );
206 if ( is_array( $this->store->get( $key ) ) ) {
207 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
208 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
209 $session = $this->getSessionFromInfo( $info, $request );
210 }
211 }
212
213 if ( $create && $session === null ) {
214 $ex = null;
215 try {
216 $session = $this->getEmptySessionInternal( $request, $id );
217 } catch ( \Exception $ex ) {
218 $this->logger->error( 'Failed to create empty session: {exception}',
219 [
220 'method' => __METHOD__,
221 'exception' => $ex,
222 ] );
223 $session = null;
224 }
225 }
226
227 return $session;
228 }
229
230 public function getEmptySession( WebRequest $request = null ) {
231 return $this->getEmptySessionInternal( $request );
232 }
233
234 /**
235 * @see SessionManagerInterface::getEmptySession
236 * @param WebRequest|null $request
237 * @param string|null $id ID to force on the new session
238 * @return Session
239 */
240 private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
241 if ( $id !== null ) {
242 if ( !self::validateSessionId( $id ) ) {
243 throw new \InvalidArgumentException( 'Invalid session ID' );
244 }
245
246 $key = wfMemcKey( 'MWSession', $id );
247 if ( is_array( $this->store->get( $key ) ) ) {
248 throw new \InvalidArgumentException( 'Session ID already exists' );
249 }
250 }
251 if ( !$request ) {
252 $request = new FauxRequest;
253 }
254
255 $infos = [];
256 foreach ( $this->getProviders() as $provider ) {
257 $info = $provider->newSessionInfo( $id );
258 if ( !$info ) {
259 continue;
260 }
261 if ( $info->getProvider() !== $provider ) {
262 throw new \UnexpectedValueException(
263 "$provider returned an empty session info for a different provider: $info"
264 );
265 }
266 if ( $id !== null && $info->getId() !== $id ) {
267 throw new \UnexpectedValueException(
268 "$provider returned empty session info with a wrong id: " .
269 $info->getId() . ' != ' . $id
270 );
271 }
272 if ( !$info->isIdSafe() ) {
273 throw new \UnexpectedValueException(
274 "$provider returned empty session info with id flagged unsafe"
275 );
276 }
277 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
278 if ( $compare > 0 ) {
279 continue;
280 }
281 if ( $compare === 0 ) {
282 $infos[] = $info;
283 } else {
284 $infos = [ $info ];
285 }
286 }
287
288 // Make sure there's exactly one
289 if ( count( $infos ) > 1 ) {
290 throw new \UnexpectedValueException(
291 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
292 );
293 } elseif ( count( $infos ) < 1 ) {
294 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
295 }
296
297 return $this->getSessionFromInfo( $infos[0], $request );
298 }
299
300 public function getVaryHeaders() {
301 if ( $this->varyHeaders === null ) {
302 $headers = [];
303 foreach ( $this->getProviders() as $provider ) {
304 foreach ( $provider->getVaryHeaders() as $header => $options ) {
305 if ( !isset( $headers[$header] ) ) {
306 $headers[$header] = [];
307 }
308 if ( is_array( $options ) ) {
309 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
310 }
311 }
312 }
313 $this->varyHeaders = $headers;
314 }
315 return $this->varyHeaders;
316 }
317
318 public function getVaryCookies() {
319 if ( $this->varyCookies === null ) {
320 $cookies = [];
321 foreach ( $this->getProviders() as $provider ) {
322 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
323 }
324 $this->varyCookies = array_values( array_unique( $cookies ) );
325 }
326 return $this->varyCookies;
327 }
328
329 /**
330 * Validate a session ID
331 * @param string $id
332 * @return bool
333 */
334 public static function validateSessionId( $id ) {
335 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
336 }
337
338 /**
339 * @name Internal methods
340 * @{
341 */
342
343 /**
344 * Auto-create the given user, if necessary
345 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
346 * @note This more properly belongs in AuthManager, but we need it now.
347 * When AuthManager comes, this will be deprecated and will pass-through
348 * to the corresponding AuthManager method.
349 * @param User $user User to auto-create
350 * @return bool Success
351 */
352 public static function autoCreateUser( User $user ) {
353 global $wgAuth;
354
355 $logger = self::singleton()->logger;
356
357 // Much of this code is based on that in CentralAuth
358
359 // Try the local user from the slave DB
360 $localId = User::idFromName( $user->getName() );
361 $flags = 0;
362
363 // Fetch the user ID from the master, so that we don't try to create the user
364 // when they already exist, due to replication lag
365 // @codeCoverageIgnoreStart
366 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
367 $localId = User::idFromName( $user->getName(), User::READ_LATEST );
368 $flags = User::READ_LATEST;
369 }
370 // @codeCoverageIgnoreEnd
371
372 if ( $localId ) {
373 // User exists after all.
374 $user->setId( $localId );
375 $user->loadFromId( $flags );
376 return false;
377 }
378
379 // Denied by AuthPlugin? But ignore AuthPlugin itself.
380 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
381 $logger->debug( __METHOD__ . ': denied by AuthPlugin' );
382 $user->setId( 0 );
383 $user->loadFromId();
384 return false;
385 }
386
387 // Wiki is read-only?
388 if ( wfReadOnly() ) {
389 $logger->debug( __METHOD__ . ': denied by wfReadOnly()' );
390 $user->setId( 0 );
391 $user->loadFromId();
392 return false;
393 }
394
395 $userName = $user->getName();
396
397 // Check the session, if we tried to create this user already there's
398 // no point in retrying.
399 $session = self::getGlobalSession();
400 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
401 if ( $reason ) {
402 $logger->debug( __METHOD__ . ": blacklisted in session ($reason)" );
403 $user->setId( 0 );
404 $user->loadFromId();
405 return false;
406 }
407
408 // Is the IP user able to create accounts?
409 $anon = new User;
410 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
411 || $anon->isBlockedFromCreateAccount()
412 ) {
413 // Blacklist the user to avoid repeated DB queries subsequently
414 $logger->debug( __METHOD__ . ': user is blocked from this wiki, blacklisting' );
415 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
416 $session->persist();
417 $user->setId( 0 );
418 $user->loadFromId();
419 return false;
420 }
421
422 // Check for validity of username
423 if ( !User::isCreatableName( $userName ) ) {
424 $logger->debug( __METHOD__ . ': Invalid username, blacklisting' );
425 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
426 $session->persist();
427 $user->setId( 0 );
428 $user->loadFromId();
429 return false;
430 }
431
432 // Give other extensions a chance to stop auto creation.
433 $user->loadDefaults( $userName );
434 $abortMessage = '';
435 if ( !\Hooks::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
436 // In this case we have no way to return the message to the user,
437 // but we can log it.
438 $logger->debug( __METHOD__ . ": denied by hook: $abortMessage" );
439 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
440 $session->persist();
441 $user->setId( 0 );
442 $user->loadFromId();
443 return false;
444 }
445
446 // Make sure the name has not been changed
447 if ( $user->getName() !== $userName ) {
448 $user->setId( 0 );
449 $user->loadFromId();
450 throw new \UnexpectedValueException(
451 'AbortAutoAccount hook tried to change the user name'
452 );
453 }
454
455 // Ignore warnings about master connections/writes...hard to avoid here
456 \Profiler::instance()->getTransactionProfiler()->resetExpectations();
457
458 $cache = \ObjectCache::getLocalClusterInstance();
459 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
460 if ( $cache->get( $backoffKey ) ) {
461 $logger->debug( __METHOD__ . ': denied by prior creation attempt failures' );
462 $user->setId( 0 );
463 $user->loadFromId();
464 return false;
465 }
466
467 // Checks passed, create the user...
468 $from = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : 'CLI';
469 $logger->info( __METHOD__ . ': creating new user ({username}) - from: {url}',
470 [
471 'username' => $userName,
472 'url' => $from,
473 ] );
474
475 try {
476 // Insert the user into the local DB master
477 $status = $user->addToDatabase();
478 if ( !$status->isOK() ) {
479 // @codeCoverageIgnoreStart
480 // double-check for a race condition (T70012)
481 $id = User::idFromName( $user->getName(), User::READ_LATEST );
482 if ( $id ) {
483 $logger->info( __METHOD__ . ': tried to autocreate existing user',
484 [
485 'username' => $userName,
486 ] );
487 } else {
488 $logger->error( __METHOD__ . ': failed with message ' . $status->getWikiText(),
489 [
490 'username' => $userName,
491 ] );
492 }
493 $user->setId( $id );
494 $user->loadFromId( User::READ_LATEST );
495 return false;
496 // @codeCoverageIgnoreEnd
497 }
498 } catch ( \Exception $ex ) {
499 // @codeCoverageIgnoreStart
500 $logger->error( __METHOD__ . ': failed with exception {exception}', [
501 'exception' => $ex,
502 'username' => $userName,
503 ] );
504 // Do not keep throwing errors for a while
505 $cache->set( $backoffKey, 1, 600 );
506 // Bubble up error; which should normally trigger DB rollbacks
507 throw $ex;
508 // @codeCoverageIgnoreEnd
509 }
510
511 # Notify AuthPlugin
512 $tmpUser = $user;
513 $wgAuth->initUser( $tmpUser, true );
514 if ( $tmpUser !== $user ) {
515 $logger->warning( __METHOD__ . ': ' .
516 get_class( $wgAuth ) . '::initUser() replaced the user object' );
517 }
518
519 # Notify hooks (e.g. Newuserlog)
520 \Hooks::run( 'AuthPluginAutoCreate', [ $user ] );
521 \Hooks::run( 'LocalUserCreated', [ $user, true ] );
522
523 $user->saveSettings();
524
525 # Update user count
526 \DeferredUpdates::addUpdate( new \SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
527
528 # Watch user's userpage and talk page
529 $user->addWatch( $user->getUserPage(), \WatchedItem::IGNORE_USER_RIGHTS );
530
531 return true;
532 }
533
534 /**
535 * Prevent future sessions for the user
536 *
537 * The intention is that the named account will never again be usable for
538 * normal login (i.e. there is no way to undo the prevention of access).
539 *
540 * @private For use from \\User::newSystemUser only
541 * @param string $username
542 */
543 public function preventSessionsForUser( $username ) {
544 $this->preventUsers[$username] = true;
545
546 // Instruct the session providers to kill any other sessions too.
547 foreach ( $this->getProviders() as $provider ) {
548 $provider->preventSessionsForUser( $username );
549 }
550 }
551
552 /**
553 * Test if a user is prevented
554 * @private For use from SessionBackend only
555 * @param string $username
556 * @return bool
557 */
558 public function isUserSessionPrevented( $username ) {
559 return !empty( $this->preventUsers[$username] );
560 }
561
562 /**
563 * Get the available SessionProviders
564 * @return SessionProvider[]
565 */
566 protected function getProviders() {
567 if ( $this->sessionProviders === null ) {
568 $this->sessionProviders = [];
569 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
570 $provider = \ObjectFactory::getObjectFromSpec( $spec );
571 $provider->setLogger( $this->logger );
572 $provider->setConfig( $this->config );
573 $provider->setManager( $this );
574 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
575 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
576 }
577 $this->sessionProviders[(string)$provider] = $provider;
578 }
579 }
580 return $this->sessionProviders;
581 }
582
583 /**
584 * Get a session provider by name
585 *
586 * Generally, this will only be used by internal implementation of some
587 * special session-providing mechanism. General purpose code, if it needs
588 * to access a SessionProvider at all, will use Session::getProvider().
589 *
590 * @param string $name
591 * @return SessionProvider|null
592 */
593 public function getProvider( $name ) {
594 $providers = $this->getProviders();
595 return isset( $providers[$name] ) ? $providers[$name] : null;
596 }
597
598 /**
599 * Save all active sessions on shutdown
600 * @private For internal use with register_shutdown_function()
601 */
602 public function shutdown() {
603 if ( $this->allSessionBackends ) {
604 $this->logger->debug( 'Saving all sessions on shutdown' );
605 if ( session_id() !== '' ) {
606 // @codeCoverageIgnoreStart
607 session_write_close();
608 }
609 // @codeCoverageIgnoreEnd
610 foreach ( $this->allSessionBackends as $backend ) {
611 $backend->save( true );
612 }
613 }
614 }
615
616 /**
617 * Fetch the SessionInfo(s) for a request
618 * @param WebRequest $request
619 * @return SessionInfo|null
620 */
621 private function getSessionInfoForRequest( WebRequest $request ) {
622 // Call all providers to fetch "the" session
623 $infos = [];
624 foreach ( $this->getProviders() as $provider ) {
625 $info = $provider->provideSessionInfo( $request );
626 if ( !$info ) {
627 continue;
628 }
629 if ( $info->getProvider() !== $provider ) {
630 throw new \UnexpectedValueException(
631 "$provider returned session info for a different provider: $info"
632 );
633 }
634 $infos[] = $info;
635 }
636
637 // Sort the SessionInfos. Then find the first one that can be
638 // successfully loaded, and then all the ones after it with the same
639 // priority.
640 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
641 $retInfos = [];
642 while ( $infos ) {
643 $info = array_pop( $infos );
644 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
645 $retInfos[] = $info;
646 while ( $infos ) {
647 $info = array_pop( $infos );
648 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
649 // We hit a lower priority, stop checking.
650 break;
651 }
652 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
653 // This is going to error out below, but we want to
654 // provide a complete list.
655 $retInfos[] = $info;
656 }
657 }
658 }
659 }
660
661 if ( count( $retInfos ) > 1 ) {
662 $ex = new \OverflowException(
663 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
664 );
665 $ex->sessionInfos = $retInfos;
666 throw $ex;
667 }
668
669 return $retInfos ? $retInfos[0] : null;
670 }
671
672 /**
673 * Load and verify the session info against the store
674 *
675 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
676 * @param WebRequest $request
677 * @return bool Whether the session info matches the stored data (if any)
678 */
679 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
680 $key = wfMemcKey( 'MWSession', $info->getId() );
681 $blob = $this->store->get( $key );
682
683 $newParams = [];
684
685 if ( $blob !== false ) {
686 // Sanity check: blob must be an array, if it's saved at all
687 if ( !is_array( $blob ) ) {
688 $this->logger->warning( 'Session "{session}": Bad data', [
689 'session' => $info,
690 ] );
691 $this->store->delete( $key );
692 return false;
693 }
694
695 // Sanity check: blob has data and metadata arrays
696 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
697 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
698 ) {
699 $this->logger->warning( 'Session "{session}": Bad data structure', [
700 'session' => $info,
701 ] );
702 $this->store->delete( $key );
703 return false;
704 }
705
706 $data = $blob['data'];
707 $metadata = $blob['metadata'];
708
709 // Sanity check: metadata must be an array and must contain certain
710 // keys, if it's saved at all
711 if ( !array_key_exists( 'userId', $metadata ) ||
712 !array_key_exists( 'userName', $metadata ) ||
713 !array_key_exists( 'userToken', $metadata ) ||
714 !array_key_exists( 'provider', $metadata )
715 ) {
716 $this->logger->warning( 'Session "{session}": Bad metadata', [
717 'session' => $info,
718 ] );
719 $this->store->delete( $key );
720 return false;
721 }
722
723 // First, load the provider from metadata, or validate it against the metadata.
724 $provider = $info->getProvider();
725 if ( $provider === null ) {
726 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
727 if ( !$provider ) {
728 $this->logger->warning(
729 'Session "{session}": Unknown provider ' . $metadata['provider'],
730 [
731 'session' => $info,
732 ]
733 );
734 $this->store->delete( $key );
735 return false;
736 }
737 } elseif ( $metadata['provider'] !== (string)$provider ) {
738 $this->logger->warning( 'Session "{session}": Wrong provider ' .
739 $metadata['provider'] . ' !== ' . $provider,
740 [
741 'session' => $info,
742 ] );
743 return false;
744 }
745
746 // Load provider metadata from metadata, or validate it against the metadata
747 $providerMetadata = $info->getProviderMetadata();
748 if ( isset( $metadata['providerMetadata'] ) ) {
749 if ( $providerMetadata === null ) {
750 $newParams['metadata'] = $metadata['providerMetadata'];
751 } else {
752 try {
753 $newProviderMetadata = $provider->mergeMetadata(
754 $metadata['providerMetadata'], $providerMetadata
755 );
756 if ( $newProviderMetadata !== $providerMetadata ) {
757 $newParams['metadata'] = $newProviderMetadata;
758 }
759 } catch ( MetadataMergeException $ex ) {
760 $this->logger->warning(
761 'Session "{session}": Metadata merge failed: {exception}',
762 [
763 'session' => $info,
764 'exception' => $ex,
765 ] + $ex->getContext()
766 );
767 return false;
768 }
769 }
770 }
771
772 // Next, load the user from metadata, or validate it against the metadata.
773 $userInfo = $info->getUserInfo();
774 if ( !$userInfo ) {
775 // For loading, id is preferred to name.
776 try {
777 if ( $metadata['userId'] ) {
778 $userInfo = UserInfo::newFromId( $metadata['userId'] );
779 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
780 $userInfo = UserInfo::newFromName( $metadata['userName'] );
781 } else {
782 $userInfo = UserInfo::newAnonymous();
783 }
784 } catch ( \InvalidArgumentException $ex ) {
785 $this->logger->error( 'Session "{session}": {exception}', [
786 'session' => $info,
787 'exception' => $ex,
788 ] );
789 return false;
790 }
791 $newParams['userInfo'] = $userInfo;
792 } else {
793 // User validation passes if user ID matches, or if there
794 // is no saved ID and the names match.
795 if ( $metadata['userId'] ) {
796 if ( $metadata['userId'] !== $userInfo->getId() ) {
797 $this->logger->warning(
798 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
799 [
800 'session' => $info,
801 'uid_a' => $metadata['userId'],
802 'uid_b' => $userInfo->getId(),
803 ] );
804 return false;
805 }
806
807 // If the user was renamed, probably best to fail here.
808 if ( $metadata['userName'] !== null &&
809 $userInfo->getName() !== $metadata['userName']
810 ) {
811 $this->logger->warning(
812 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
813 [
814 'session' => $info,
815 'uname_a' => $metadata['userName'],
816 'uname_b' => $userInfo->getName(),
817 ] );
818 return false;
819 }
820
821 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
822 if ( $metadata['userName'] !== $userInfo->getName() ) {
823 $this->logger->warning(
824 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
825 [
826 'session' => $info,
827 'uname_a' => $metadata['userName'],
828 'uname_b' => $userInfo->getName(),
829 ] );
830 return false;
831 }
832 } elseif ( !$userInfo->isAnon() ) {
833 // Metadata specifies an anonymous user, but the passed-in
834 // user isn't anonymous.
835 $this->logger->warning(
836 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
837 [
838 'session' => $info,
839 ] );
840 return false;
841 }
842 }
843
844 // And if we have a token in the metadata, it must match the loaded/provided user.
845 if ( $metadata['userToken'] !== null &&
846 $userInfo->getToken() !== $metadata['userToken']
847 ) {
848 $this->logger->warning( 'Session "{session}": User token mismatch', [
849 'session' => $info,
850 ] );
851 return false;
852 }
853 if ( !$userInfo->isVerified() ) {
854 $newParams['userInfo'] = $userInfo->verified();
855 }
856
857 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
858 $newParams['remembered'] = true;
859 }
860 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
861 $newParams['forceHTTPS'] = true;
862 }
863 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
864 $newParams['persisted'] = true;
865 }
866
867 if ( !$info->isIdSafe() ) {
868 $newParams['idIsSafe'] = true;
869 }
870 } else {
871 // No metadata, so we can't load the provider if one wasn't given.
872 if ( $info->getProvider() === null ) {
873 $this->logger->warning(
874 'Session "{session}": Null provider and no metadata',
875 [
876 'session' => $info,
877 ] );
878 return false;
879 }
880
881 // If no user was provided and no metadata, it must be anon.
882 if ( !$info->getUserInfo() ) {
883 if ( $info->getProvider()->canChangeUser() ) {
884 $newParams['userInfo'] = UserInfo::newAnonymous();
885 } else {
886 $this->logger->info(
887 'Session "{session}": No user provided and provider cannot set user',
888 [
889 'session' => $info,
890 ] );
891 return false;
892 }
893 } elseif ( !$info->getUserInfo()->isVerified() ) {
894 $this->logger->warning(
895 'Session "{session}": Unverified user provided and no metadata to auth it',
896 [
897 'session' => $info,
898 ] );
899 return false;
900 }
901
902 $data = false;
903 $metadata = false;
904
905 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
906 // The ID doesn't come from the user, so it should be safe
907 // (and if not, nothing we can do about it anyway)
908 $newParams['idIsSafe'] = true;
909 }
910 }
911
912 // Construct the replacement SessionInfo, if necessary
913 if ( $newParams ) {
914 $newParams['copyFrom'] = $info;
915 $info = new SessionInfo( $info->getPriority(), $newParams );
916 }
917
918 // Allow the provider to check the loaded SessionInfo
919 $providerMetadata = $info->getProviderMetadata();
920 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
921 return false;
922 }
923 if ( $providerMetadata !== $info->getProviderMetadata() ) {
924 $info = new SessionInfo( $info->getPriority(), [
925 'metadata' => $providerMetadata,
926 'copyFrom' => $info,
927 ] );
928 }
929
930 // Give hooks a chance to abort. Combined with the SessionMetadata
931 // hook, this can allow for tying a session to an IP address or the
932 // like.
933 $reason = 'Hook aborted';
934 if ( !\Hooks::run(
935 'SessionCheckInfo',
936 [ &$reason, $info, $request, $metadata, $data ]
937 ) ) {
938 $this->logger->warning( 'Session "{session}": ' . $reason, [
939 'session' => $info,
940 ] );
941 return false;
942 }
943
944 return true;
945 }
946
947 /**
948 * Create a session corresponding to the passed SessionInfo
949 * @private For use by a SessionProvider that needs to specially create its
950 * own session.
951 * @param SessionInfo $info
952 * @param WebRequest $request
953 * @return Session
954 */
955 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
956 if ( defined( 'MW_NO_SESSION' ) ) {
957 if ( MW_NO_SESSION === 'warn' ) {
958 // Undocumented safety case for converting existing entry points
959 $this->logger->error( 'Sessions are supposed to be disabled for this entry point' );
960 } else {
961 throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
962 }
963 }
964
965 $id = $info->getId();
966
967 if ( !isset( $this->allSessionBackends[$id] ) ) {
968 if ( !isset( $this->allSessionIds[$id] ) ) {
969 $this->allSessionIds[$id] = new SessionId( $id );
970 }
971 $backend = new SessionBackend(
972 $this->allSessionIds[$id],
973 $info,
974 $this->store,
975 $this->logger,
976 $this->config->get( 'ObjectCacheSessionExpiry' )
977 );
978 $this->allSessionBackends[$id] = $backend;
979 $delay = $backend->delaySave();
980 } else {
981 $backend = $this->allSessionBackends[$id];
982 $delay = $backend->delaySave();
983 if ( $info->wasPersisted() ) {
984 $backend->persist();
985 }
986 if ( $info->wasRemembered() ) {
987 $backend->setRememberUser( true );
988 }
989 }
990
991 $request->setSessionId( $backend->getSessionId() );
992 $session = $backend->getSession( $request );
993
994 if ( !$info->isIdSafe() ) {
995 $session->resetId();
996 }
997
998 \ScopedCallback::consume( $delay );
999 return $session;
1000 }
1001
1002 /**
1003 * Deregister a SessionBackend
1004 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1005 * @param SessionBackend $backend
1006 */
1007 public function deregisterSessionBackend( SessionBackend $backend ) {
1008 $id = $backend->getId();
1009 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
1010 $this->allSessionBackends[$id] !== $backend ||
1011 $this->allSessionIds[$id] !== $backend->getSessionId()
1012 ) {
1013 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1014 }
1015
1016 unset( $this->allSessionBackends[$id] );
1017 // Explicitly do not unset $this->allSessionIds[$id]
1018 }
1019
1020 /**
1021 * Change a SessionBackend's ID
1022 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1023 * @param SessionBackend $backend
1024 */
1025 public function changeBackendId( SessionBackend $backend ) {
1026 $sessionId = $backend->getSessionId();
1027 $oldId = (string)$sessionId;
1028 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
1029 $this->allSessionBackends[$oldId] !== $backend ||
1030 $this->allSessionIds[$oldId] !== $sessionId
1031 ) {
1032 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1033 }
1034
1035 $newId = $this->generateSessionId();
1036
1037 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
1038 $sessionId->setId( $newId );
1039 $this->allSessionBackends[$newId] = $backend;
1040 $this->allSessionIds[$newId] = $sessionId;
1041 }
1042
1043 /**
1044 * Generate a new random session ID
1045 * @return string
1046 */
1047 public function generateSessionId() {
1048 do {
1049 $id = wfBaseConvert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
1050 $key = wfMemcKey( 'MWSession', $id );
1051 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
1052 return $id;
1053 }
1054
1055 /**
1056 * Call setters on a PHPSessionHandler
1057 * @private Use PhpSessionHandler::install()
1058 * @param PHPSessionHandler $handler
1059 */
1060 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
1061 $handler->setManager( $this, $this->store, $this->logger );
1062 }
1063
1064 /**
1065 * Reset the internal caching for unit testing
1066 */
1067 public static function resetCache() {
1068 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1069 // @codeCoverageIgnoreStart
1070 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
1071 // @codeCoverageIgnoreEnd
1072 }
1073
1074 self::$globalSession = null;
1075 self::$globalSessionRequest = null;
1076 }
1077
1078 /**
1079 * Do a sanity check to make sure the session is not used from many different IP addresses
1080 * and store some data for later sanity checks.
1081 * FIXME remove this once SessionManager is considered stable
1082 * @private For use in Setup.php only
1083 * @param Session $session Defaults to the global session.
1084 */
1085 public function checkIpLimits( Session $session = null ) {
1086 $session = $session ?: self::getGlobalSession();
1087
1088 try {
1089 $ip = $session->getRequest()->getIP();
1090 } catch ( \MWException $e ) {
1091 return;
1092 }
1093 if ( $ip === '127.0.0.1' || \IP::isConfiguredProxy( $ip ) ) {
1094 return;
1095 }
1096 $now = time();
1097
1098 // Record (and possibly log) that the IP is using the current session.
1099 // Don't touch the stored data unless we are adding a new IP or re-adding an expired one.
1100 // This is slightly inaccurate (when an existing IP is seen again, the expiry is not
1101 // extended) but that shouldn't make much difference and limits the session write frequency
1102 // to # of IPs / $wgSuspiciousIpExpiry.
1103 $data = $session->get( 'SessionManager-ip', [] );
1104 if (
1105 !isset( $data[$ip] )
1106 || $data[$ip] < $now
1107 ) {
1108 $data[$ip] = time() + $this->config->get( 'SuspiciousIpExpiry' );
1109 foreach ( $data as $key => $expires ) {
1110 if ( $expires < $now ) {
1111 unset( $data[$key] );
1112 }
1113 }
1114 $session->set( 'SessionManager-ip', $data );
1115
1116 $logger = \MediaWiki\Logger\LoggerFactory::getInstance( 'session-ip' );
1117 $logLevel = count( $data ) >= $this->config->get( 'SuspiciousIpPerSessionLimit' )
1118 ? LogLevel::WARNING : ( count( $data ) === 1 ? LogLevel::DEBUG : LogLevel::INFO );
1119 $logger->log(
1120 $logLevel,
1121 'Same session used from {count} IPs',
1122 [
1123 'count' => count( $data ),
1124 'ips' => $data,
1125 'session' => $session->getId(),
1126 'user' => $session->getUser()->getName(),
1127 'persistent' => $session->isPersistent(),
1128 ]
1129 );
1130 }
1131
1132 // Now do the same thing globally for the current user.
1133 // We are using the object cache and assume it is shared between all wikis of a farm,
1134 // and further assume that the same name belongs to the same user on all wikis. (It's either
1135 // that or a central ID lookup which would mean an extra SQL query on every request.)
1136 if ( $session->getUser()->isLoggedIn() ) {
1137 $userKey = 'SessionManager-ip:' . md5( $session->getUser()->getName() );
1138 $data = $this->store->get( $userKey ) ?: [];
1139 if (
1140 !isset( $data[$ip] )
1141 || $data[$ip] < $now
1142 ) {
1143 $data[$ip] = time() + $this->config->get( 'SuspiciousIpExpiry' );
1144 foreach ( $data as $key => $expires ) {
1145 if ( $expires < $now ) {
1146 unset( $data[$key] );
1147 }
1148 }
1149 $this->store->set( $userKey, $data, $this->config->get( 'SuspiciousIpExpiry' ) );
1150 $logger = \MediaWiki\Logger\LoggerFactory::getInstance( 'session-ip' );
1151 $logLevel = count( $data ) >= $this->config->get( 'SuspiciousIpPerUserLimit' )
1152 ? LogLevel::WARNING : ( count( $data ) === 1 ? LogLevel::DEBUG : LogLevel::INFO );
1153 $logger->log(
1154 $logLevel,
1155 'Same user had sessions from {count} IPs',
1156 [
1157 'count' => count( $data ),
1158 'ips' => $data,
1159 'session' => $session->getId(),
1160 'user' => $session->getUser()->getName(),
1161 'persistent' => $session->isPersistent(),
1162 ]
1163 );
1164 }
1165 }
1166 }
1167
1168 /**@}*/
1169
1170 }