Add better logging to password reset
[lhc/web/wiklou.git] / includes / user / PasswordReset.php
1 <?php
2 /**
3 * User password reset helper for MediaWiki.
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 */
22
23 use MediaWiki\Auth\AuthManager;
24 use MediaWiki\Auth\TemporaryPasswordAuthenticationRequest;
25 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
27 use MediaWiki\Logger\LoggerFactory;
28
29 /**
30 * Helper class for the password reset functionality shared by the web UI and the API.
31 *
32 * Requires the TemporaryPasswordPrimaryAuthenticationProvider and the
33 * EmailNotificationSecondaryAuthenticationProvider (or something providing equivalent
34 * functionality) to be enabled.
35 */
36 class PasswordReset implements LoggerAwareInterface {
37 /** @var Config */
38 protected $config;
39
40 /** @var AuthManager */
41 protected $authManager;
42
43 /** @var LoggerInterface */
44 protected $logger;
45
46 /**
47 * In-process cache for isAllowed lookups, by username. Contains pairs of StatusValue objects
48 * (for false and true value of $displayPassword, respectively).
49 * @var HashBagOStuff
50 */
51 private $permissionCache;
52
53 public function __construct( Config $config, AuthManager $authManager ) {
54 $this->config = $config;
55 $this->authManager = $authManager;
56 $this->permissionCache = new HashBagOStuff( [ 'maxKeys' => 1 ] );
57 $this->logger = LoggerFactory::getInstance( 'authentication' );
58 }
59
60 /**
61 * Set the logger instance to use.
62 *
63 * @param LoggerInterface $logger
64 * @since 1.29
65 */
66 public function setLogger( LoggerInterface $logger ) {
67 $this->logger = $logger;
68 }
69
70 /**
71 * Check if a given user has permission to use this functionality.
72 * @param User $user
73 * @param bool $displayPassword If set, also check whether the user is allowed to reset the
74 * password of another user and see the temporary password.
75 * @return StatusValue
76 */
77 public function isAllowed( User $user, $displayPassword = false ) {
78 $statuses = $this->permissionCache->get( $user->getName() );
79 if ( $statuses ) {
80 list ( $status, $status2 ) = $statuses;
81 } else {
82 $resetRoutes = $this->config->get( 'PasswordResetRoutes' );
83 $status = StatusValue::newGood();
84
85 if ( !is_array( $resetRoutes ) ||
86 !in_array( true, array_values( $resetRoutes ), true )
87 ) {
88 // Maybe password resets are disabled, or there are no allowable routes
89 $status = StatusValue::newFatal( 'passwordreset-disabled' );
90 } elseif (
91 ( $providerStatus = $this->authManager->allowsAuthenticationDataChange(
92 new TemporaryPasswordAuthenticationRequest(), false ) )
93 && !$providerStatus->isGood()
94 ) {
95 // Maybe the external auth plugin won't allow local password changes
96 $status = StatusValue::newFatal( 'resetpass_forbidden-reason',
97 $providerStatus->getMessage() );
98 } elseif ( !$this->config->get( 'EnableEmail' ) ) {
99 // Maybe email features have been disabled
100 $status = StatusValue::newFatal( 'passwordreset-emaildisabled' );
101 } elseif ( !$user->isAllowed( 'editmyprivateinfo' ) ) {
102 // Maybe not all users have permission to change private data
103 $status = StatusValue::newFatal( 'badaccess' );
104 } elseif ( $user->isBlocked() ) {
105 // Maybe the user is blocked (check this here rather than relying on the parent
106 // method as we have a more specific error message to use here
107 $status = StatusValue::newFatal( 'blocked-mailpassword' );
108 }
109
110 $status2 = StatusValue::newGood();
111 if ( !$user->isAllowed( 'passwordreset' ) ) {
112 $status2 = StatusValue::newFatal( 'badaccess' );
113 }
114
115 $this->permissionCache->set( $user->getName(), [ $status, $status2 ] );
116 }
117
118 if ( !$displayPassword || !$status->isGood() ) {
119 return $status;
120 } else {
121 return $status2;
122 }
123 }
124
125 /**
126 * Do a password reset. Authorization is the caller's responsibility.
127 *
128 * Process the form. At this point we know that the user passes all the criteria in
129 * userCanExecute(), and if the data array contains 'Username', etc, then Username
130 * resets are allowed.
131 * @param User $performingUser The user that does the password reset
132 * @param string $username The user whose password is reset
133 * @param string $email Alternative way to specify the user
134 * @param bool $displayPassword Whether to display the password
135 * @return StatusValue Will contain the passwords as a username => password array if the
136 * $displayPassword flag was set
137 * @throws LogicException When the user is not allowed to perform the action
138 * @throws MWException On unexpected DB errors
139 */
140 public function execute(
141 User $performingUser, $username = null, $email = null, $displayPassword = false
142 ) {
143 if ( !$this->isAllowed( $performingUser, $displayPassword )->isGood() ) {
144 $action = $this->isAllowed( $performingUser )->isGood() ? 'display' : 'reset';
145 throw new LogicException( 'User ' . $performingUser->getName()
146 . ' is not allowed to ' . $action . ' passwords' );
147 }
148
149 $resetRoutes = $this->config->get( 'PasswordResetRoutes' )
150 + [ 'username' => false, 'email' => false ];
151 if ( $resetRoutes['username'] && $username ) {
152 $method = 'username';
153 $users = [ User::newFromName( $username ) ];
154 } elseif ( $resetRoutes['email'] && $email ) {
155 if ( !Sanitizer::validateEmail( $email ) ) {
156 return StatusValue::newFatal( 'passwordreset-invalidemail' );
157 }
158 $method = 'email';
159 $users = $this->getUsersByEmail( $email );
160 } else {
161 // The user didn't supply any data
162 return StatusValue::newFatal( 'passwordreset-nodata' );
163 }
164
165 // Check for hooks (captcha etc), and allow them to modify the users list
166 $error = [];
167 $data = [
168 'Username' => $username,
169 'Email' => $email,
170 'Capture' => $displayPassword ? '1' : null,
171 ];
172 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
173 return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
174 }
175
176 if ( !$users ) {
177 if ( $method === 'email' ) {
178 // Don't reveal whether or not an email address is in use
179 return StatusValue::newGood( [] );
180 } else {
181 return StatusValue::newFatal( 'noname' );
182 }
183 }
184
185 $firstUser = $users[0];
186
187 if ( !$firstUser instanceof User || !$firstUser->getId() ) {
188 // Don't parse username as wikitext (bug 65501)
189 return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
190 }
191
192 // Check against the rate limiter
193 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
194 return StatusValue::newFatal( 'actionthrottledtext' );
195 }
196
197 // All the users will have the same email address
198 if ( !$firstUser->getEmail() ) {
199 // This won't be reachable from the email route, so safe to expose the username
200 return StatusValue::newFatal( wfMessage( 'noemail',
201 wfEscapeWikiText( $firstUser->getName() ) ) );
202 }
203
204 // We need to have a valid IP address for the hook, but per bug 18347, we should
205 // send the user's name if they're logged in.
206 $ip = $performingUser->getRequest()->getIP();
207 if ( !$ip ) {
208 return StatusValue::newFatal( 'badipaddress' );
209 }
210
211 Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
212
213 $result = StatusValue::newGood();
214 $reqs = [];
215 foreach ( $users as $user ) {
216 $req = TemporaryPasswordAuthenticationRequest::newRandom();
217 $req->username = $user->getName();
218 $req->mailpassword = true;
219 $req->hasBackchannel = $displayPassword;
220 $req->caller = $performingUser->getName();
221 $status = $this->authManager->allowsAuthenticationDataChange( $req, true );
222 if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
223 $reqs[] = $req;
224 } elseif ( $result->isGood() ) {
225 // only record the first error, to avoid exposing the number of users having the
226 // same email address
227 if ( $status->getValue() === 'ignored' ) {
228 $status = StatusValue::newFatal( 'passwordreset-ignored' );
229 }
230 $result->merge( $status );
231 }
232 }
233
234 $logContext = [
235 'requestingIp' => $ip,
236 'requestingUser' => $performingUser->getName(),
237 'targetUsername' => $username,
238 'targetEmail' => $email,
239 'actualUser' => $firstUser->getName(),
240 'capture' => $displayPassword,
241 ];
242
243 if ( !$result->isGood() ) {
244 $this->logger->info(
245 "{requestingUser} attempted password reset of {actualUser} but failed",
246 $logContext + [ 'errors' => $result->getErrors() ]
247 );
248 return $result;
249 }
250
251 $passwords = [];
252 foreach ( $reqs as $req ) {
253 $this->authManager->changeAuthenticationData( $req );
254 // TODO record mail sending errors
255 if ( $displayPassword ) {
256 $passwords[$req->username] = $req->password;
257 }
258 }
259
260 if ( $displayPassword ) {
261 // The password capture thing is scary, so log
262 // at a higher warning level.
263 $this->logger->warning(
264 "{requestingUser} did password reset of {actualUser} with password capturing!",
265 $logContext
266 );
267 } else {
268 $this->logger->info(
269 "{requestingUser} did password reset of {actualUser}",
270 $logContext
271 );
272 }
273
274 return StatusValue::newGood( $passwords );
275 }
276
277 /**
278 * @param string $email
279 * @return User[]
280 * @throws MWException On unexpected database errors
281 */
282 protected function getUsersByEmail( $email ) {
283 $res = wfGetDB( DB_REPLICA )->select(
284 'user',
285 User::selectFields(),
286 [ 'user_email' => $email ],
287 __METHOD__
288 );
289
290 if ( !$res ) {
291 // Some sort of database error, probably unreachable
292 throw new MWException( 'Unknown database error in ' . __METHOD__ );
293 }
294
295 $users = [];
296 foreach ( $res as $row ) {
297 $users[] = User::newFromRow( $row );
298 }
299 return $users;
300 }
301 }