Passed
Push — master ( d9e5dd...36764d )
by Spuds
01:07 queued 26s
created

PasswordHash::CheckPassword()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
dl 0
loc 10
rs 10
c 0
b 0
f 0
nc 3
nop 2
1
<?php
2
#
3
# Portable PHP password hashing framework.
4
#
5
# Version 0.3 / elkarte.
6
#
7
# Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
8
# the public domain.  Revised in subsequent years, still public domain.
9
#
10
# There's absolutely no warranty.
11
#
12
# The homepage URL for this framework is:
13
#
14
#	http://www.openwall.com/phpass/
15
#
16
# Please be sure to update the Version line if you edit this file in any way.
17
# It is suggested that you leave the main version number intact, but indicate
18
# your project name (after the slash) and add your own revision information.
19
#
20
# Please do not change the "private" password hashing method implemented in
21
# here, thereby making your hashes incompatible.  However, if you must, please
22
# change the hash type identifier (the "$P$") to something different.
23
#
24
# Obviously, since this code is in the public domain, the above are not
25
# requirements (there can be none), but merely suggestions.
26
#
27
28
class PasswordHash {
29
	var $itoa64;
30
	var $iteration_count_log2;
31
	var $portable_hashes;
32
	var $random_state;
33
34
	public function __construct( $iteration_count_log2, $portable_hashes )
35
	{
36
		$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
37
38
		if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
39
			$iteration_count_log2 = 8;
40
		$this->iteration_count_log2 = $iteration_count_log2;
41
42
		$this->portable_hashes = $portable_hashes;
43
44
		$this->random_state = microtime() . uniqid(rand(), TRUE);
45
	}
46
47
	private function get_random_bytes($count)
48
	{
49
		$output = '';
50
51
		// PHP >= 7
52
		if (is_callable('random_bytes')) {
53
			$output = random_bytes($count);
54
		}
55
		// *nix
56
		elseif (@is_readable('/dev/urandom') &&
57
			($fh = @fopen('/dev/urandom', 'rb'))) {
58
			$output = fread($fh, $count);
59
			fclose($fh);
60
		}
61
		// This is much to slow on windows php < 5.3.4
62
		elseif (function_exists('openssl_random_pseudo_bytes') &&
63
			(substr(PHP_OS, 0, 3) !== 'WIN' || version_compare(PHP_VERSION, '5.3.4', '>='))) {
64
			$output = openssl_random_pseudo_bytes($count);
65
		}
66
67
		// Do it ourselves then
68
		if (strlen($output) < $count) {
69
			$output = '';
70
			for ($i = 0; $i < $count; $i += 16) {
71
				$this->random_state =
72
					md5(microtime() . $this->random_state);
73
				$output .=
74
					pack('H*', md5($this->random_state));
75
			}
76
			$output = substr($output, 0, $count);
77
		}
78
79
		return $output;
80
	}
81
82
	private function encode64($input, $count)
83
	{
84
		$output = '';
85
		$i = 0;
86
		do {
87
			$value = ord($input[$i++]);
88
			$output .= $this->itoa64[$value & 0x3f];
89
			if ($i < $count)
90
				$value |= ord($input[$i]) << 8;
91
			$output .= $this->itoa64[($value >> 6) & 0x3f];
92
			if ($i++ >= $count)
93
				break;
94
			if ($i < $count)
95
				$value |= ord($input[$i]) << 16;
96
			$output .= $this->itoa64[($value >> 12) & 0x3f];
97
			if ($i++ >= $count)
98
				break;
99
			$output .= $this->itoa64[($value >> 18) & 0x3f];
100
		} while ($i < $count);
101
102
		return $output;
103
	}
104
105
	private function gensalt_private($input)
106
	{
107
		$output = '$P$';
108
		$output .= $this->itoa64[min($this->iteration_count_log2 +
109
			((PHP_VERSION >= '5') ? 5 : 3), 30)];
110
		$output .= $this->encode64($input, 6);
111
112
		return $output;
113
	}
114
115
	private function crypt_private($password, $setting)
116
	{
117
		$output = '*0';
118
		if (substr($setting, 0, 2) == $output)
119
			$output = '*1';
120
121
		$id = substr($setting, 0, 3);
122
		# We use "$P$", phpBB3 uses "$H$" for the same thing
123
		if ($id != '$P$' && $id != '$H$')
124
			return $output;
125
126
		$count_log2 = strpos($this->itoa64, $setting[3]);
127
		if ($count_log2 < 7 || $count_log2 > 30)
128
			return $output;
129
130
		$count = 1 << $count_log2;
131
132
		$salt = substr($setting, 4, 8);
133
		if (strlen($salt) != 8)
134
			return $output;
135
136
		# We're kind of forced to use MD5 here since it's the only
137
		# cryptographic primitive available in all versions of PHP
138
		# currently in use.  To implement our own low-level crypto
139
		# in PHP would result in much worse performance and
140
		# consequently in lower iteration counts and hashes that are
141
		# quicker to crack (by non-PHP code).
142
		if (PHP_VERSION >= '5') {
143
			$hash = md5($salt . $password, TRUE);
144
			do {
145
				$hash = md5($hash . $password, TRUE);
146
			} while (--$count);
147
		} else {
148
			$hash = pack('H*', md5($salt . $password));
149
			do {
150
				$hash = pack('H*', md5($hash . $password));
151
			} while (--$count);
152
		}
153
154
		$output = substr($setting, 0, 12);
155
		$output .= $this->encode64($hash, 16);
156
157
		return $output;
158
	}
159
160
	private function gensalt_extended($input)
161
	{
162
		$count_log2 = min($this->iteration_count_log2 + 8, 24);
163
		# This should be odd to not reveal weak DES keys, and the
164
		# maximum valid value is (2**24 - 1) which is odd anyway.
165
		$count = (1 << $count_log2) - 1;
166
167
		$output = '_';
168
		$output .= $this->itoa64[$count & 0x3f];
169
		$output .= $this->itoa64[($count >> 6) & 0x3f];
170
		$output .= $this->itoa64[($count >> 12) & 0x3f];
171
		$output .= $this->itoa64[($count >> 18) & 0x3f];
172
173
		$output .= $this->encode64($input, 3);
174
175
		return $output;
176
	}
177
178
	private function gensalt_blowfish($input)
179
	{
180
		# This one needs to use a different order of characters and a
181
		# different encoding scheme from the one in encode64() above.
182
		# We care because the last character in our encoded string will
183
		# only represent 2 bits.  While two known implementations of
184
		# bcrypt will happily accept and correct a salt string which
185
		# has the 4 unused bits set to non-zero, we do not want to take
186
		# chances and we also do not want to waste an additional byte
187
		# of entropy.
188
		$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
189
190
		$output = '$2a$';
191
		$output .= chr(ord('0') + (int) $this->iteration_count_log2 / 10);
192
		$output .= chr(ord('0') + (int) $this->iteration_count_log2 % 10);
193
		$output .= '$';
194
195
		$i = 0;
196
		do {
197
			$c1 = ord($input[$i++]);
198
			$output .= $itoa64[$c1 >> 2];
199
			$c1 = ($c1 & 0x03) << 4;
200
			if ($i >= 16) {
201
				$output .= $itoa64[$c1];
202
				break;
203
			}
204
205
			$c2 = ord($input[$i++]);
206
			$c1 |= $c2 >> 4;
207
			$output .= $itoa64[$c1];
208
			$c1 = ($c2 & 0x0f) << 2;
209
210
			$c2 = ord($input[$i++]);
211
			$c1 |= $c2 >> 6;
212
			$output .= $itoa64[$c1];
213
			$output .= $itoa64[$c2 & 0x3f];
214
		} while (1);
215
216
		return $output;
217
	}
218
219
	public function HashPassword($password)
220
	{
221
		if ( strlen( $password ) > 4096 )
222
			return '*';
223
224
		$random = '';
225
226
		if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) {
227
			$random = $this->get_random_bytes(16);
228
			$hash =
229
				crypt($password, $this->gensalt_blowfish($random));
230
			if (strlen($hash) == 60)
231
				return $hash;
232
		}
233
234
		if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) {
235
			if (strlen($random) < 3)
236
				$random = $this->get_random_bytes(3);
237
			$hash =
238
				crypt($password, $this->gensalt_extended($random));
239
			if (strlen($hash) == 20)
240
				return $hash;
241
		}
242
243
		if (strlen($random) < 6)
244
			$random = $this->get_random_bytes(6);
245
		$hash =
246
			$this->crypt_private($password,
247
				$this->gensalt_private($random));
248
		if (strlen($hash) == 34)
249
			return $hash;
250
251
		# Returning '*' on error is safe here, but would _not_ be safe
252
		# in a crypt(3)-like function used _both_ for generating new
253
		# hashes and for validating passwords against existing hashes.
254
		return '*';
255
	}
256
257
	public function CheckPassword($password, $stored_hash)
258
	{
259
		if ( strlen( $password ) > 4096 )
260
			return false;
261
262
		$hash = $this->crypt_private($password, $stored_hash);
263
		if ($hash[0] == '*')
264
			$hash = crypt($password, $stored_hash);
265
266
		return $this->_hash_equals($hash, $stored_hash);
267
	}
268
269
	/**
270
	 * Timing attack safe string comparison
271
	 *
272
	 * Unlike normal === comparisons where the function returns after the
273
	 * first non match, here the time taken is independent of the number of
274
	 * characters that match.
275
	 *
276
	 * @see http://php.net/manual/en/function.hash-equals.php#117101
277
	 *
278
	 * This function should be used to mitigate timing attacks; for instance,
279
	 * when testing crypt() password hashes.
280
	 *
281
	 * @param string $a
282
	 * @param string $b
283
	 *
284
	 * @return bool
285
	 */
286
	private function _hash_equals($a, $b)
287
	{
288
		// PHP 5.6+
289
		if (function_exists('hash_equals'))
290
		{
291
			return hash_equals($a, $b);
292
		}
293
294
		$ret = strlen($a) ^ strlen($b);
295
		$ret |= array_sum(unpack("C*", $a ^ $b));
296
297
		return !$ret;
298
	}
299
}
300