Merge "Use a ScopedCallback to silence transaction profiler in SqlBagOStuff"
[lhc/web/wiklou.git] / includes / auth / LocalPasswordPrimaryAuthenticationProvider.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Auth
20 */
21
22 namespace MediaWiki\Auth;
23
24 use User;
25
26 /**
27 * A primary authentication provider that uses the password field in the 'user' table.
28 * @ingroup Auth
29 * @since 1.27
30 */
31 class LocalPasswordPrimaryAuthenticationProvider
32 extends AbstractPasswordPrimaryAuthenticationProvider
33 {
34
35 /** @var bool If true, this instance is for legacy logins only. */
36 protected $loginOnly = false;
37
38 /**
39 * @param array $params Settings
40 * - loginOnly: If true, the local passwords are for legacy logins only:
41 * the local password will be invalidated when authentication is changed
42 * and new users will not have a valid local password set.
43 */
44 public function __construct( $params = [] ) {
45 parent::__construct( $params );
46 $this->loginOnly = !empty( $params['loginOnly'] );
47 }
48
49 protected function getPasswordResetData( $username, $row ) {
50 $now = wfTimestamp();
51 $expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
52 if ( $expiration === null || $expiration >= $now ) {
53 return null;
54 }
55
56 $grace = $this->config->get( 'PasswordExpireGrace' );
57 if ( $expiration + $grace < $now ) {
58 $data = [
59 'hard' => true,
60 'msg' => \Status::newFatal( 'resetpass-expired' )->getMessage(),
61 ];
62 } else {
63 $data = [
64 'hard' => false,
65 'msg' => \Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
66 ];
67 }
68
69 return (object)$data;
70 }
71
72 public function beginPrimaryAuthentication( array $reqs ) {
73 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
74 if ( !$req ) {
75 return AuthenticationResponse::newAbstain();
76 }
77
78 if ( $req->username === null || $req->password === null ) {
79 return AuthenticationResponse::newAbstain();
80 }
81
82 $username = User::getCanonicalName( $req->username, 'usable' );
83 if ( $username === false ) {
84 return AuthenticationResponse::newAbstain();
85 }
86
87 $fields = [
88 'user_id', 'user_password', 'user_password_expires',
89 ];
90
91 $dbr = wfGetDB( DB_REPLICA );
92 $row = $dbr->selectRow(
93 'user',
94 $fields,
95 [ 'user_name' => $username ],
96 __METHOD__
97 );
98 if ( !$row ) {
99 // Do not reveal whether its bad username or
100 // bad password to prevent username enumeration
101 // on private wikis. (T134100)
102 return $this->failResponse( $req );
103 }
104
105 $oldRow = clone $row;
106 // Check for *really* old password hashes that don't even have a type
107 // The old hash format was just an md5 hex hash, with no type information
108 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
109 if ( $this->config->get( 'PasswordSalt' ) ) {
110 $row->user_password = ":B:{$row->user_id}:{$row->user_password}";
111 } else {
112 $row->user_password = ":A:{$row->user_password}";
113 }
114 }
115
116 $status = $this->checkPasswordValidity( $username, $req->password );
117 if ( !$status->isOK() ) {
118 // Fatal, can't log in
119 return AuthenticationResponse::newFail( $status->getMessage() );
120 }
121
122 $pwhash = $this->getPassword( $row->user_password );
123 if ( !$pwhash->equals( $req->password ) ) {
124 if ( $this->config->get( 'LegacyEncoding' ) ) {
125 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
126 // Check for this with iconv
127 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
128 if ( $cp1252Password === $req->password || !$pwhash->equals( $cp1252Password ) ) {
129 return $this->failResponse( $req );
130 }
131 } else {
132 return $this->failResponse( $req );
133 }
134 }
135
136 // @codeCoverageIgnoreStart
137 if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
138 $newHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
139 $fname = __METHOD__;
140 \DeferredUpdates::addCallableUpdate( function () use ( $newHash, $oldRow, $fname ) {
141 $dbw = wfGetDB( DB_MASTER );
142 $dbw->update(
143 'user',
144 [ 'user_password' => $newHash->toString() ],
145 [
146 'user_id' => $oldRow->user_id,
147 'user_password' => $oldRow->user_password
148 ],
149 $fname
150 );
151 } );
152 }
153 // @codeCoverageIgnoreEnd
154
155 $this->setPasswordResetFlag( $username, $status, $row );
156
157 return AuthenticationResponse::newPass( $username );
158 }
159
160 public function testUserCanAuthenticate( $username ) {
161 $username = User::getCanonicalName( $username, 'usable' );
162 if ( $username === false ) {
163 return false;
164 }
165
166 $dbr = wfGetDB( DB_REPLICA );
167 $row = $dbr->selectRow(
168 'user',
169 [ 'user_password' ],
170 [ 'user_name' => $username ],
171 __METHOD__
172 );
173 if ( !$row ) {
174 return false;
175 }
176
177 // Check for *really* old password hashes that don't even have a type
178 // The old hash format was just an md5 hex hash, with no type information
179 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
180 return true;
181 }
182
183 return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
184 }
185
186 public function testUserExists( $username, $flags = User::READ_NORMAL ) {
187 $username = User::getCanonicalName( $username, 'usable' );
188 if ( $username === false ) {
189 return false;
190 }
191
192 list( $db, $options ) = \DBAccessObjectUtils::getDBOptions( $flags );
193 return (bool)wfGetDB( $db )->selectField(
194 [ 'user' ],
195 [ 'user_id' ],
196 [ 'user_name' => $username ],
197 __METHOD__,
198 $options
199 );
200 }
201
202 public function providerAllowsAuthenticationDataChange(
203 AuthenticationRequest $req, $checkData = true
204 ) {
205 // We only want to blank the password if something else will accept the
206 // new authentication data, so return 'ignore' here.
207 if ( $this->loginOnly ) {
208 return \StatusValue::newGood( 'ignored' );
209 }
210
211 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
212 if ( !$checkData ) {
213 return \StatusValue::newGood();
214 }
215
216 $username = User::getCanonicalName( $req->username, 'usable' );
217 if ( $username !== false ) {
218 $row = wfGetDB( DB_MASTER )->selectRow(
219 'user',
220 [ 'user_id' ],
221 [ 'user_name' => $username ],
222 __METHOD__
223 );
224 if ( $row ) {
225 $sv = \StatusValue::newGood();
226 if ( $req->password !== null ) {
227 if ( $req->password !== $req->retype ) {
228 $sv->fatal( 'badretype' );
229 } else {
230 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
231 }
232 }
233 return $sv;
234 }
235 }
236 }
237
238 return \StatusValue::newGood( 'ignored' );
239 }
240
241 public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
242 $username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
243 if ( $username === false ) {
244 return;
245 }
246
247 $pwhash = null;
248
249 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
250 if ( $this->loginOnly ) {
251 $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
252 $expiry = null;
253 } else {
254 $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
255 $expiry = $this->getNewPasswordExpiry( $username );
256 }
257 }
258
259 if ( $pwhash ) {
260 $dbw = wfGetDB( DB_MASTER );
261 $dbw->update(
262 'user',
263 [
264 'user_password' => $pwhash->toString(),
265 'user_password_expires' => $dbw->timestampOrNull( $expiry ),
266 ],
267 [ 'user_name' => $username ],
268 __METHOD__
269 );
270 }
271 }
272
273 public function accountCreationType() {
274 return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
275 }
276
277 public function testForAccountCreation( $user, $creator, array $reqs ) {
278 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
279
280 $ret = \StatusValue::newGood();
281 if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
282 if ( $req->password !== $req->retype ) {
283 $ret->fatal( 'badretype' );
284 } else {
285 $ret->merge(
286 $this->checkPasswordValidity( $user->getName(), $req->password )
287 );
288 }
289 }
290 return $ret;
291 }
292
293 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
294 if ( $this->accountCreationType() === self::TYPE_NONE ) {
295 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
296 }
297
298 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
299 if ( $req ) {
300 if ( $req->username !== null && $req->password !== null ) {
301 // Nothing we can do besides claim it, because the user isn't in
302 // the DB yet
303 if ( $req->username !== $user->getName() ) {
304 $req = clone $req;
305 $req->username = $user->getName();
306 }
307 $ret = AuthenticationResponse::newPass( $req->username );
308 $ret->createRequest = $req;
309 return $ret;
310 }
311 }
312 return AuthenticationResponse::newAbstain();
313 }
314
315 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
316 if ( $this->accountCreationType() === self::TYPE_NONE ) {
317 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
318 }
319
320 // Now that the user is in the DB, set the password on it.
321 $this->providerChangeAuthenticationData( $res->createRequest );
322
323 return null;
324 }
325 }