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