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