Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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 /**
50 * Check if the password has expired and needs a reset
51 *
52 * @param string $username
53 * @param \stdClass $row A row from the user table
54 * @return \stdClass|null
55 */
56 protected function getPasswordResetData( $username, $row ) {
57 $now = wfTimestamp();
58 $expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
59 if ( $expiration === null || $expiration >= $now ) {
60 return null;
61 }
62
63 $grace = $this->config->get( 'PasswordExpireGrace' );
64 if ( $expiration + $grace < $now ) {
65 $data = [
66 'hard' => true,
67 'msg' => \Status::newFatal( 'resetpass-expired' )->getMessage(),
68 ];
69 } else {
70 $data = [
71 'hard' => false,
72 'msg' => \Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
73 ];
74 }
75
76 return (object)$data;
77 }
78
79 public function beginPrimaryAuthentication( array $reqs ) {
80 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
81 if ( !$req ) {
82 return AuthenticationResponse::newAbstain();
83 }
84
85 if ( $req->username === null || $req->password === null ) {
86 return AuthenticationResponse::newAbstain();
87 }
88
89 $username = User::getCanonicalName( $req->username, 'usable' );
90 if ( $username === false ) {
91 return AuthenticationResponse::newAbstain();
92 }
93
94 $fields = [
95 'user_id', 'user_password', 'user_password_expires',
96 ];
97
98 $dbr = wfGetDB( DB_REPLICA );
99 $row = $dbr->selectRow(
100 'user',
101 $fields,
102 [ 'user_name' => $username ],
103 __METHOD__
104 );
105 if ( !$row ) {
106 // Do not reveal whether its bad username or
107 // bad password to prevent username enumeration
108 // on private wikis. (T134100)
109 return $this->failResponse( $req );
110 }
111
112 $oldRow = clone $row;
113 // Check for *really* old password hashes that don't even have a type
114 // The old hash format was just an md5 hex hash, with no type information
115 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
116 if ( $this->config->get( 'PasswordSalt' ) ) {
117 $row->user_password = ":B:{$row->user_id}:{$row->user_password}";
118 } else {
119 $row->user_password = ":A:{$row->user_password}";
120 }
121 }
122
123 $status = $this->checkPasswordValidity( $username, $req->password );
124 if ( !$status->isOK() ) {
125 // Fatal, can't log in
126 return AuthenticationResponse::newFail( $status->getMessage() );
127 }
128
129 $pwhash = $this->getPassword( $row->user_password );
130 if ( !$pwhash->verify( $req->password ) ) {
131 if ( $this->config->get( 'LegacyEncoding' ) ) {
132 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
133 // Check for this with iconv
134 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
135 if ( $cp1252Password === $req->password || !$pwhash->verify( $cp1252Password ) ) {
136 return $this->failResponse( $req );
137 }
138 } else {
139 return $this->failResponse( $req );
140 }
141 }
142
143 // @codeCoverageIgnoreStart
144 if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
145 $newHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
146 $fname = __METHOD__;
147 \DeferredUpdates::addCallableUpdate( function () use ( $newHash, $oldRow, $fname ) {
148 $dbw = wfGetDB( DB_MASTER );
149 $dbw->update(
150 'user',
151 [ 'user_password' => $newHash->toString() ],
152 [
153 'user_id' => $oldRow->user_id,
154 'user_password' => $oldRow->user_password
155 ],
156 $fname
157 );
158 } );
159 }
160 // @codeCoverageIgnoreEnd
161
162 $this->setPasswordResetFlag( $username, $status, $row );
163
164 return AuthenticationResponse::newPass( $username );
165 }
166
167 public function testUserCanAuthenticate( $username ) {
168 $username = User::getCanonicalName( $username, 'usable' );
169 if ( $username === false ) {
170 return false;
171 }
172
173 $dbr = wfGetDB( DB_REPLICA );
174 $row = $dbr->selectRow(
175 'user',
176 [ 'user_password' ],
177 [ 'user_name' => $username ],
178 __METHOD__
179 );
180 if ( !$row ) {
181 return false;
182 }
183
184 // Check for *really* old password hashes that don't even have a type
185 // The old hash format was just an md5 hex hash, with no type information
186 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
187 return true;
188 }
189
190 return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
191 }
192
193 public function testUserExists( $username, $flags = User::READ_NORMAL ) {
194 $username = User::getCanonicalName( $username, 'usable' );
195 if ( $username === false ) {
196 return false;
197 }
198
199 list( $db, $options ) = \DBAccessObjectUtils::getDBOptions( $flags );
200 return (bool)wfGetDB( $db )->selectField(
201 [ 'user' ],
202 'user_id',
203 [ 'user_name' => $username ],
204 __METHOD__,
205 $options
206 );
207 }
208
209 public function providerAllowsAuthenticationDataChange(
210 AuthenticationRequest $req, $checkData = true
211 ) {
212 // We only want to blank the password if something else will accept the
213 // new authentication data, so return 'ignore' here.
214 if ( $this->loginOnly ) {
215 return \StatusValue::newGood( 'ignored' );
216 }
217
218 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
219 if ( !$checkData ) {
220 return \StatusValue::newGood();
221 }
222
223 $username = User::getCanonicalName( $req->username, 'usable' );
224 if ( $username !== false ) {
225 $row = wfGetDB( DB_MASTER )->selectRow(
226 'user',
227 [ 'user_id' ],
228 [ 'user_name' => $username ],
229 __METHOD__
230 );
231 if ( $row ) {
232 $sv = \StatusValue::newGood();
233 if ( $req->password !== null ) {
234 if ( $req->password !== $req->retype ) {
235 $sv->fatal( 'badretype' );
236 } else {
237 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
238 }
239 }
240 return $sv;
241 }
242 }
243 }
244
245 return \StatusValue::newGood( 'ignored' );
246 }
247
248 public function providerChangeAuthenticationData( AuthenticationRequest $req ) {
249 $username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
250 if ( $username === false ) {
251 return;
252 }
253
254 $pwhash = null;
255
256 if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
257 if ( $this->loginOnly ) {
258 $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
259 $expiry = null;
260 } else {
261 $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
262 $expiry = $this->getNewPasswordExpiry( $username );
263 }
264 }
265
266 if ( $pwhash ) {
267 $dbw = wfGetDB( DB_MASTER );
268 $dbw->update(
269 'user',
270 [
271 'user_password' => $pwhash->toString(),
272 'user_password_expires' => $dbw->timestampOrNull( $expiry ),
273 ],
274 [ 'user_name' => $username ],
275 __METHOD__
276 );
277 }
278 }
279
280 public function accountCreationType() {
281 return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
282 }
283
284 public function testForAccountCreation( $user, $creator, array $reqs ) {
285 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
286
287 $ret = \StatusValue::newGood();
288 if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
289 if ( $req->password !== $req->retype ) {
290 $ret->fatal( 'badretype' );
291 } else {
292 $ret->merge(
293 $this->checkPasswordValidity( $user->getName(), $req->password )
294 );
295 }
296 }
297 return $ret;
298 }
299
300 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
301 if ( $this->accountCreationType() === self::TYPE_NONE ) {
302 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
303 }
304
305 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
306 if ( $req && $req->username !== null && $req->password !== null ) {
307 // Nothing we can do besides claim it, because the user isn't in
308 // the DB yet
309 if ( $req->username !== $user->getName() ) {
310 $req = clone $req;
311 $req->username = $user->getName();
312 }
313 $ret = AuthenticationResponse::newPass( $req->username );
314 $ret->createRequest = $req;
315 return $ret;
316 }
317 return AuthenticationResponse::newAbstain();
318 }
319
320 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
321 if ( $this->accountCreationType() === self::TYPE_NONE ) {
322 throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
323 }
324
325 // Now that the user is in the DB, set the password on it.
326 $this->providerChangeAuthenticationData( $res->createRequest );
327
328 return null;
329 }
330 }