Merge "Fix HeaderCallback failing on headers without a colon"
[lhc/web/wiklou.git] / includes / password / Password.php
1 <?php
2 /**
3 * Implements the Password class for the MediaWiki software.
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 Wikimedia\Assert\Assert;
24
25 /**
26 * Represents a password hash for use in authentication
27 *
28 * Note: All password types are transparently prefixed with :<TYPE>:, where <TYPE>
29 * is the registered type of the hash. This prefix is stripped in the constructor
30 * and is added back in the toString() function.
31 *
32 * When inheriting this class, there are a couple of expectations
33 * to be fulfilled:
34 * * If Password::toString() is called on an object, and the result is passed back in
35 * to PasswordFactory::newFromCiphertext(), the result will be identical to the original.
36 * * The string representations of two Password objects are equal only if
37 * the original plaintext passwords match. In other words, if the toString() result of
38 * two objects match, the passwords are the same, and the user will be logged in.
39 * Since the string representation of a hash includes its type name (@see Password::toString),
40 * this property is preserved across all classes that inherit Password.
41 * If a hashing scheme does not fulfill this expectation, it must make sure to override the
42 * Password::equals() function and use custom comparison logic. However, this is not
43 * recommended unless absolutely required by the hashing mechanism.
44 * With these two points in mind, when creating a new Password sub-class, there are some functions
45 * you have to override (because they are abstract) and others that you may want to override.
46 *
47 * The abstract functions that must be overridden are:
48 * * Password::crypt(), which takes a plaintext password and hashes it into a string hash suitable
49 * for being passed to the constructor of that class, and then stores that hash (and whatever
50 * other data) into the internal state of the object.
51 * The functions that can optionally be overridden are:
52 * * Password::parseHash(), which can be useful to override if you need to extract values from or
53 * otherwise parse a password hash when it's passed to the constructor.
54 * * Password::needsUpdate(), which can be useful if a specific password hash has different
55 * logic for when the hash needs to be updated.
56 * * Password::toString(), which can be useful if the hash was changed in the constructor and
57 * needs to be re-assembled before being returned as a string. This function is expected to add
58 * the type back on to the hash, so make sure to do that if you override the function.
59 * * Password::equals() - This function compares two Password objects to see if they are equal.
60 * The default is to just do a timing-safe string comparison on the $this->hash values.
61 *
62 * After creating a new password hash type, it can be registered using the static
63 * Password::register() method. The default type is set using the Password::setDefaultType() type.
64 * Types must be registered before they can be set as the default.
65 *
66 * @since 1.24
67 */
68 abstract class Password {
69 /**
70 * @var PasswordFactory Factory that created the object
71 */
72 protected $factory;
73
74 /**
75 * String representation of the hash without the type
76 * @var string
77 */
78 protected $hash;
79
80 /**
81 * Array of configuration variables injected from the constructor
82 * @var array
83 */
84 protected $config;
85
86 /**
87 * Hash must fit in user_password, which is a tinyblob
88 */
89 const MAX_HASH_SIZE = 255;
90
91 /**
92 * Construct the Password object using a string hash
93 *
94 * It is strongly recommended not to call this function directly unless you
95 * have a reason to. Use the PasswordFactory class instead.
96 *
97 * @throws MWException If $config does not contain required parameters
98 *
99 * @param PasswordFactory $factory Factory object that created the password
100 * @param array $config Array of engine configuration options for hashing
101 * @param string|null $hash The raw hash, including the type
102 */
103 final public function __construct( PasswordFactory $factory, array $config, $hash = null ) {
104 if ( !$this->isSupported() ) {
105 throw new Exception( 'PHP support not found for ' . get_class( $this ) );
106 }
107 if ( !isset( $config['type'] ) ) {
108 throw new Exception( 'Password configuration must contain a type name.' );
109 }
110 $this->config = $config;
111 $this->factory = $factory;
112
113 if ( $hash !== null && strlen( $hash ) >= 3 ) {
114 // Strip the type from the hash for parsing
115 $hash = substr( $hash, strpos( $hash, ':', 1 ) + 1 );
116 }
117
118 $this->hash = $hash;
119 $this->parseHash( $hash );
120 }
121
122 /**
123 * Get the type name of the password
124 *
125 * @return string Password type
126 */
127 final public function getType() {
128 return $this->config['type'];
129 }
130
131 /**
132 * Whether current password type is supported on this system.
133 *
134 * @return bool
135 */
136 protected function isSupported() {
137 return true;
138 }
139
140 /**
141 * Perform any parsing necessary on the hash to see if the hash is valid
142 * and/or to perform logic for seeing if the hash needs updating.
143 *
144 * @param string $hash The hash, with the :<TYPE>: prefix stripped
145 * @throws PasswordError If there is an error in parsing the hash
146 */
147 protected function parseHash( $hash ) {
148 }
149
150 /**
151 * Determine if the hash needs to be updated
152 *
153 * @return bool True if needs update, false otherwise
154 */
155 abstract public function needsUpdate();
156
157 /**
158 * Compare one Password object to this object
159 *
160 * By default, do a timing-safe string comparison on the result of
161 * Password::toString() for each object. This can be overridden to do
162 * custom comparison, but it is not recommended unless necessary.
163 *
164 * @deprecated since 1.33, use verify()
165 *
166 * @param Password|string $other The other password
167 * @return bool True if equal, false otherwise
168 */
169 public function equals( $other ) {
170 if ( is_string( $other ) ) {
171 return $this->verify( $other );
172 }
173
174 return hash_equals( $this->toString(), $other->toString() );
175 }
176
177 /**
178 * Checks whether the given password matches the hash stored in this object.
179 *
180 * @param string $password Password to check
181 * @return bool
182 */
183 public function verify( $password ) {
184 Assert::parameterType( 'string', $password, '$password' );
185
186 // No need to use the factory because we're definitely making
187 // an object of the same type.
188 $obj = clone $this;
189 $obj->crypt( $password );
190
191 return hash_equals( $this->toString(), $obj->toString() );
192 }
193
194 /**
195 * Convert this hash to a string that can be stored in the database
196 *
197 * The resulting string should be considered the seralized representation
198 * of this hash, i.e., if the return value were recycled back into
199 * PasswordFactory::newFromCiphertext, the returned object would be equivalent to
200 * this; also, if two objects return the same value from this function, they
201 * are considered equivalent.
202 *
203 * @return string
204 * @throws PasswordError if password cannot be serialized to fit a tinyblob.
205 */
206 public function toString() {
207 $result = ':' . $this->config['type'] . ':' . $this->hash;
208 $this->assertIsSafeSize( $result );
209 return $result;
210 }
211
212 /**
213 * Assert that hash will fit in a tinyblob field.
214 *
215 * This prevents MW from inserting it into the DB
216 * and having MySQL silently truncating it, locking
217 * the user out of their account.
218 *
219 * @param string $hash The hash in question.
220 * @throws PasswordError If hash does not fit in DB.
221 */
222 final protected function assertIsSafeSize( $hash ) {
223 if ( strlen( $hash ) > self::MAX_HASH_SIZE ) {
224 throw new PasswordError( "Password hash is too big" );
225 }
226 }
227
228 /**
229 * Hash a password and store the result in this object
230 *
231 * The result of the password hash should be put into the internal
232 * state of the hash object.
233 *
234 * @param string $password Password to hash
235 * @throws PasswordError If an internal error occurs in hashing
236 */
237 abstract public function crypt( $password );
238 }