xref: /dokuwiki/inc/PassHash.php (revision 925105e82bbaf10d0b6330b81350f14a5a176eb4)
1<?php
2// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
3
4namespace dokuwiki;
5
6/**
7 * Password Hashing Class
8 *
9 * This class implements various mechanisms used to hash passwords
10 *
11 * @author  Andreas Gohr <andi@splitbrain.org>
12 * @license LGPL2
13 */
14class PassHash {
15    /**
16     * Verifies a cleartext password against a crypted hash
17     *
18     * The method and salt used for the crypted hash is determined automatically,
19     * then the clear text password is crypted using the same method. If both hashs
20     * match true is is returned else false
21     *
22     * @author  Andreas Gohr <andi@splitbrain.org>
23     *
24     * @param string $clear Clear-Text password
25     * @param string $hash  Hash to compare against
26     * @return  bool
27     */
28    public function verify_hash($clear, $hash) {
29        $method = '';
30        $salt   = '';
31        $magic  = '';
32
33        //determine the used method and salt
34        $len = strlen($hash);
35        if(preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
36            $method = 'smd5';
37            $salt   = $m[1];
38            $magic  = '1';
39        } elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
40            $method = 'apr1';
41            $salt   = $m[1];
42            $magic  = 'apr1';
43        } elseif(preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
44            $method = 'pmd5';
45            $salt   = $m[1];
46            $magic  = 'P';
47        } elseif(preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
48            $method = 'pmd5';
49            $salt = $m[1];
50            $magic = 'H';
51        } elseif(preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
52            $method = 'djangopbkdf2';
53            $magic = array(
54                'algo' => $m[1],
55                'iter' => $m[2],
56            );
57            $salt = $m[3];
58        } elseif(preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
59            $method = 'djangosha1';
60            $salt   = $m[1];
61        } elseif(preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
62            $method = 'djangomd5';
63            $salt   = $m[1];
64        } elseif(preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) {
65            $method = 'bcrypt';
66            $salt   = $hash;
67        } elseif(substr($hash, 0, 6) == '{SSHA}') {
68            $method = 'ssha';
69            $salt   = substr(base64_decode(substr($hash, 6)), 20);
70        } elseif(substr($hash, 0, 6) == '{SMD5}') {
71            $method = 'lsmd5';
72            $salt   = substr(base64_decode(substr($hash, 6)), 16);
73        } elseif(preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
74            $method = 'mediawiki';
75            $salt   = $m[1];
76        } elseif(preg_match('/^\$6\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
77            $method = 'sha512';
78            $salt   = $m[2];
79            $magic  = $m[1];
80        } elseif($len == 32) {
81            $method = 'md5';
82        } elseif($len == 40) {
83            $method = 'sha1';
84        } elseif($len == 16) {
85            $method = 'mysql';
86        } elseif($len == 41 && $hash[0] == '*') {
87            $method = 'my411';
88        } elseif($len == 34) {
89            $method = 'kmd5';
90            $salt   = $hash;
91        } else {
92            $method = 'crypt';
93            $salt   = substr($hash, 0, 2);
94        }
95
96        //crypt and compare
97        $call = 'hash_'.$method;
98        $newhash = $this->$call($clear, $salt, $magic);
99        if(\hash_equals($newhash, $hash)) {
100            return true;
101        }
102        return false;
103    }
104
105    /**
106     * Create a random salt
107     *
108     * @param int $len The length of the salt
109     * @return string
110     */
111    public function gen_salt($len = 32) {
112        $salt  = '';
113        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
114        for($i = 0; $i < $len; $i++) {
115            $salt .= $chars[$this->random(0, 61)];
116        }
117        return $salt;
118    }
119
120    /**
121     * Initialize the passed variable with a salt if needed.
122     *
123     * If $salt is not null, the value is kept, but the lenght restriction is
124     * applied (unless, $cut is false).
125     *
126     * @param string|null &$salt  The salt, pass null if you want one generated
127     * @param int          $len   The length of the salt
128     * @param bool         $cut   Apply length restriction to existing salt?
129     */
130    public function init_salt(&$salt, $len = 32, $cut = true) {
131        if(is_null($salt)) {
132            $salt = $this->gen_salt($len);
133            $cut  = true; // for new hashes we alway apply length restriction
134        }
135        if(strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
136    }
137
138    // Password hashing methods follow below
139
140    /**
141     * Password hashing method 'smd5'
142     *
143     * Uses salted MD5 hashs. Salt is 8 bytes long.
144     *
145     * The same mechanism is used by Apache's 'apr1' method. This will
146     * fallback to a implementation in pure PHP if MD5 support is not
147     * available in crypt()
148     *
149     * @author Andreas Gohr <andi@splitbrain.org>
150     * @author <mikey_nich at hotmail dot com>
151     * @link   http://php.net/manual/en/function.crypt.php#73619
152     *
153     * @param string $clear The clear text to hash
154     * @param string $salt  The salt to use, null for random
155     * @return string Hashed password
156     */
157    public function hash_smd5($clear, $salt = null) {
158        $this->init_salt($salt, 8);
159
160        if(defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
161            return crypt($clear, '$1$'.$salt.'$');
162        } else {
163            // Fall back to PHP-only implementation
164            return $this->hash_apr1($clear, $salt, '1');
165        }
166    }
167
168    /**
169     * Password hashing method 'lsmd5'
170     *
171     * Uses salted MD5 hashs. Salt is 8 bytes long.
172     *
173     * This is the format used by LDAP.
174     *
175     * @param string $clear The clear text to hash
176     * @param string $salt  The salt to use, null for random
177     * @return string Hashed password
178     */
179    public function hash_lsmd5($clear, $salt = null) {
180        $this->init_salt($salt, 8);
181        return "{SMD5}".base64_encode(md5($clear.$salt, true).$salt);
182    }
183
184    /**
185     * Password hashing method 'apr1'
186     *
187     * Uses salted MD5 hashs. Salt is 8 bytes long.
188     *
189     * This is basically the same as smd1 above, but as used by Apache.
190     *
191     * @author <mikey_nich at hotmail dot com>
192     * @link   http://php.net/manual/en/function.crypt.php#73619
193     *
194     * @param string $clear The clear text to hash
195     * @param string $salt  The salt to use, null for random
196     * @param string $magic The hash identifier (apr1 or 1)
197     * @return string Hashed password
198     */
199    public function hash_apr1($clear, $salt = null, $magic = 'apr1') {
200        $this->init_salt($salt, 8);
201
202        $len  = strlen($clear);
203        $text = $clear.'$'.$magic.'$'.$salt;
204        $bin  = pack("H32", md5($clear.$salt.$clear));
205        for($i = $len; $i > 0; $i -= 16) {
206            $text .= substr($bin, 0, min(16, $i));
207        }
208        for($i = $len; $i > 0; $i >>= 1) {
209            $text .= ($i & 1) ? chr(0) : $clear{0};
210        }
211        $bin = pack("H32", md5($text));
212        for($i = 0; $i < 1000; $i++) {
213            $new = ($i & 1) ? $clear : $bin;
214            if($i % 3) $new .= $salt;
215            if($i % 7) $new .= $clear;
216            $new .= ($i & 1) ? $bin : $clear;
217            $bin = pack("H32", md5($new));
218        }
219        $tmp = '';
220        for($i = 0; $i < 5; $i++) {
221            $k = $i + 6;
222            $j = $i + 12;
223            if($j == 16) $j = 5;
224            $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
225        }
226        $tmp = chr(0).chr(0).$bin[11].$tmp;
227        $tmp = strtr(
228            strrev(substr(base64_encode($tmp), 2)),
229            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
230            "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
231        );
232        return '$'.$magic.'$'.$salt.'$'.$tmp;
233    }
234
235    /**
236     * Password hashing method 'md5'
237     *
238     * Uses MD5 hashs.
239     *
240     * @param string $clear The clear text to hash
241     * @return string Hashed password
242     */
243    public function hash_md5($clear) {
244        return md5($clear);
245    }
246
247    /**
248     * Password hashing method 'sha1'
249     *
250     * Uses SHA1 hashs.
251     *
252     * @param string $clear The clear text to hash
253     * @return string Hashed password
254     */
255    public function hash_sha1($clear) {
256        return sha1($clear);
257    }
258
259    /**
260     * Password hashing method 'ssha' as used by LDAP
261     *
262     * Uses salted SHA1 hashs. Salt is 4 bytes long.
263     *
264     * @param string $clear The clear text to hash
265     * @param string $salt  The salt to use, null for random
266     * @return string Hashed password
267     */
268    public function hash_ssha($clear, $salt = null) {
269        $this->init_salt($salt, 4);
270        return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
271    }
272
273    /**
274     * Password hashing method 'crypt'
275     *
276     * Uses salted crypt hashs. Salt is 2 bytes long.
277     *
278     * @param string $clear The clear text to hash
279     * @param string $salt  The salt to use, null for random
280     * @return string Hashed password
281     */
282    public function hash_crypt($clear, $salt = null) {
283        $this->init_salt($salt, 2);
284        return crypt($clear, $salt);
285    }
286
287    /**
288     * Password hashing method 'mysql'
289     *
290     * This method was used by old MySQL systems
291     *
292     * @link   http://php.net/mysql
293     * @author <soren at byu dot edu>
294     * @param string $clear The clear text to hash
295     * @return string Hashed password
296     */
297    public function hash_mysql($clear) {
298        $nr      = 0x50305735;
299        $nr2     = 0x12345671;
300        $add     = 7;
301        $charArr = preg_split("//", $clear);
302        foreach($charArr as $char) {
303            if(($char == '') || ($char == ' ') || ($char == '\t')) continue;
304            $charVal = ord($char);
305            $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
306            $nr2 += ($nr2 << 8) ^ $nr;
307            $add += $charVal;
308        }
309        return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
310    }
311
312    /**
313     * Password hashing method 'my411'
314     *
315     * Uses SHA1 hashs. This method is used by MySQL 4.11 and above
316     *
317     * @param string $clear The clear text to hash
318     * @return string Hashed password
319     */
320    public function hash_my411($clear) {
321        return '*'.strtoupper(sha1(pack("H*", sha1($clear))));
322    }
323
324    /**
325     * Password hashing method 'kmd5'
326     *
327     * Uses salted MD5 hashs.
328     *
329     * Salt is 2 bytes long, but stored at position 16, so you need to pass at
330     * least 18 bytes. You can pass the crypted hash as salt.
331     *
332     * @param string $clear The clear text to hash
333     * @param string $salt  The salt to use, null for random
334     * @return string Hashed password
335     */
336    public function hash_kmd5($clear, $salt = null) {
337        $this->init_salt($salt);
338
339        $key   = substr($salt, 16, 2);
340        $hash1 = strtolower(md5($key.md5($clear)));
341        $hash2 = substr($hash1, 0, 16).$key.substr($hash1, 16);
342        return $hash2;
343    }
344
345    /**
346     * Password hashing method 'pmd5'
347     *
348     * Uses salted MD5 hashs. Salt is 1+8 bytes long, 1st byte is the
349     * iteration count when given, for null salts $compute is used.
350     *
351     * The actual iteration count is the given count squared, maximum is
352     * 30 (-> 1073741824). If a higher one is given, the function throws
353     * an exception.
354     *
355     * @link  http://www.openwall.com/phpass/
356     *
357     * @param string $clear   The clear text to hash
358     * @param string $salt    The salt to use, null for random
359     * @param string $magic   The hash identifier (P or H)
360     * @param int    $compute The iteration count for new passwords
361     * @throws \Exception
362     * @return string Hashed password
363     */
364    public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8) {
365        $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
366        if(is_null($salt)) {
367            $this->init_salt($salt);
368            $salt = $itoa64[$compute].$salt; // prefix iteration count
369        }
370        $iterc = $salt[0]; // pos 0 of salt is iteration count
371        $iter  = strpos($itoa64, $iterc);
372
373        if($iter > 30) {
374            throw new \Exception("Too high iteration count ($iter) in ".
375                                    __CLASS__.'::'.__FUNCTION__);
376        }
377
378        $iter = 1 << $iter;
379        $salt = substr($salt, 1, 8);
380
381        // iterate
382        $hash = md5($salt.$clear, true);
383        do {
384            $hash = md5($hash.$clear, true);
385        } while(--$iter);
386
387        // encode
388        $output = '';
389        $count  = 16;
390        $i      = 0;
391        do {
392            $value = ord($hash[$i++]);
393            $output .= $itoa64[$value & 0x3f];
394            if($i < $count)
395                $value |= ord($hash[$i]) << 8;
396            $output .= $itoa64[($value >> 6) & 0x3f];
397            if($i++ >= $count)
398                break;
399            if($i < $count)
400                $value |= ord($hash[$i]) << 16;
401            $output .= $itoa64[($value >> 12) & 0x3f];
402            if($i++ >= $count)
403                break;
404            $output .= $itoa64[($value >> 18) & 0x3f];
405        } while($i < $count);
406
407        return '$'.$magic.'$'.$iterc.$salt.$output;
408    }
409
410    /**
411     * Alias for hash_pmd5
412     *
413     * @param string $clear
414     * @param null|string $salt
415     * @param string $magic
416     * @param int $compute
417     *
418     * @return string
419     * @throws \Exception
420     */
421    public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8) {
422        return $this->hash_pmd5($clear, $salt, $magic, $compute);
423    }
424
425    /**
426     * Password hashing method 'djangosha1'
427     *
428     * Uses salted SHA1 hashs. Salt is 5 bytes long.
429     * This is used by the Django Python framework
430     *
431     * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
432     *
433     * @param string $clear The clear text to hash
434     * @param string $salt  The salt to use, null for random
435     * @return string Hashed password
436     */
437    public function hash_djangosha1($clear, $salt = null) {
438        $this->init_salt($salt, 5);
439        return 'sha1$'.$salt.'$'.sha1($salt.$clear);
440    }
441
442    /**
443     * Password hashing method 'djangomd5'
444     *
445     * Uses salted MD5 hashs. Salt is 5 bytes long.
446     * This is used by the Django Python framework
447     *
448     * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
449     *
450     * @param string $clear The clear text to hash
451     * @param string $salt  The salt to use, null for random
452     * @return string Hashed password
453     */
454    public function hash_djangomd5($clear, $salt = null) {
455        $this->init_salt($salt, 5);
456        return 'md5$'.$salt.'$'.md5($salt.$clear);
457    }
458
459    /**
460     * Password hashing method 'djangopbkdf2'
461     *
462     * An algorithm and iteration count should be given in the opts array.
463     * Defaults to sha256 and 24000 iterations
464     *
465     * @param string $clear The clear text to hash
466     * @param string $salt  The salt to use, null for random
467     * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
468     * @return string Hashed password
469     * @throws \Exception when PHP is missing support for the method/algo
470     */
471    public function hash_djangopbkdf2($clear, $salt=null, $opts=array()) {
472        $this->init_salt($salt, 12);
473        if(empty($opts['algo'])) {
474            $algo = 'sha256';
475        } else {
476            $algo = $opts['algo'];
477        }
478        if(empty($opts['iter'])) {
479            $iter = 24000;
480        } else {
481            $iter = (int) $opts['iter'];
482        }
483        if(!function_exists('hash_pbkdf2')) {
484            throw new \Exception('This PHP installation has no PBKDF2 support');
485        }
486        if(!in_array($algo, hash_algos())) {
487            throw new \Exception("This PHP installation has no $algo support");
488        }
489
490        $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true));
491        return "pbkdf2_$algo\$$iter\$$salt\$$hash";
492    }
493
494    /**
495     * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm
496     *
497     * @param string $clear The clear text to hash
498     * @param string $salt  The salt to use, null for random
499     * @param array $opts ('iter' => iterations)
500     * @return string Hashed password
501     * @throws \Exception when PHP is missing support for the method/algo
502     */
503    public function hash_djangopbkdf2_sha256($clear, $salt=null, $opts=array()) {
504        $opts['algo'] = 'sha256';
505        return $this->hash_djangopbkdf2($clear, $salt, $opts);
506    }
507
508    /**
509     * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm
510     *
511     * @param string $clear The clear text to hash
512     * @param string $salt  The salt to use, null for random
513     * @param array $opts ('iter' => iterations)
514     * @return string Hashed password
515     * @throws \Exception when PHP is missing support for the method/algo
516     */
517    public function hash_djangopbkdf2_sha1($clear, $salt=null, $opts=array()) {
518        $opts['algo'] = 'sha1';
519        return $this->hash_djangopbkdf2($clear, $salt, $opts);
520    }
521
522    /**
523     * Passwordhashing method 'bcrypt'
524     *
525     * Uses a modified blowfish algorithm called eksblowfish
526     * This method works on PHP 5.3+ only and will throw an exception
527     * if the needed crypt support isn't available
528     *
529     * A full hash should be given as salt (starting with $a2$) or this
530     * will break. When no salt is given, the iteration count can be set
531     * through the $compute variable.
532     *
533     * @param string $clear   The clear text to hash
534     * @param string $salt    The salt to use, null for random
535     * @param int    $compute The iteration count (between 4 and 31)
536     * @throws \Exception
537     * @return string Hashed password
538     */
539    public function hash_bcrypt($clear, $salt = null, $compute = 10) {
540        if(!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH != 1) {
541            throw new \Exception('This PHP installation has no bcrypt support');
542        }
543
544        if(is_null($salt)) {
545            if($compute < 4 || $compute > 31) $compute = 8;
546            $salt = '$2y$'.str_pad($compute, 2, '0', STR_PAD_LEFT).'$'.
547                $this->gen_salt(22);
548        }
549
550        return crypt($clear, $salt);
551    }
552
553    /**
554     * Password hashing method SHA512
555     *
556     * This is only supported on PHP 5.3.2 or higher and will throw an exception if
557     * the needed crypt support is not available
558     *
559     * @param string $clear The clear text to hash
560     * @param string $salt  The salt to use, null for random
561     * @param string $magic The rounds for sha512 (for example "rounds=3000"), null for default value
562     * @return string Hashed password
563     * @throws \Exception
564     */
565    public function hash_sha512($clear, $salt = null, $magic = null) {
566        if(!defined('CRYPT_SHA512') || CRYPT_SHA512 != 1) {
567            throw new \Exception('This PHP installation has no SHA512 support');
568        }
569        $this->init_salt($salt, 8, false);
570        if(empty($magic)) {
571            return crypt($clear, '$6$'.$salt.'$');
572        }else{
573            return crypt($clear, '$6$'.$magic.'$'.$salt.'$');
574        }
575    }
576
577    /**
578     * Password hashing method 'mediawiki'
579     *
580     * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5
581     * method 'A' is not supported.
582     *
583     * @link  http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column
584     *
585     * @param string $clear The clear text to hash
586     * @param string $salt  The salt to use, null for random
587     * @return string Hashed password
588     */
589    public function hash_mediawiki($clear, $salt = null) {
590        $this->init_salt($salt, 8, false);
591        return ':B:'.$salt.':'.md5($salt.'-'.md5($clear));
592    }
593
594    /**
595     * Wraps around native hash_hmac() or reimplents it
596     *
597     * This is not directly used as password hashing method, and thus isn't callable via the
598     * verify_hash() method. It should be used to create signatures and might be used in other
599     * password hashing methods.
600     *
601     * @see hash_hmac()
602     * @author KC Cloyd
603     * @link http://php.net/manual/en/function.hash-hmac.php#93440
604     *
605     * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4",
606     *                     etc..) See hash_algos() for a list of supported algorithms.
607     * @param string $data Message to be hashed.
608     * @param string $key  Shared secret key used for generating the HMAC variant of the message digest.
609     * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
610     * @return string
611     */
612    public static function hmac($algo, $data, $key, $raw_output = false) {
613        // use native function if available and not in unit test
614        if(function_exists('hash_hmac') && !defined('SIMPLE_TEST')){
615            return hash_hmac($algo, $data, $key, $raw_output);
616        }
617
618        $algo = strtolower($algo);
619        $pack = 'H' . strlen($algo('test'));
620        $size = 64;
621        $opad = str_repeat(chr(0x5C), $size);
622        $ipad = str_repeat(chr(0x36), $size);
623
624        if(strlen($key) > $size) {
625            $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
626        } else {
627            $key = str_pad($key, $size, chr(0x00));
628        }
629
630        for($i = 0; $i < strlen($key) - 1; $i++) {
631            $opad[$i] = $opad[$i] ^ $key[$i];
632            $ipad[$i] = $ipad[$i] ^ $key[$i];
633        }
634
635        $output = $algo($opad . pack($pack, $algo($ipad . $data)));
636
637        return ($raw_output) ? pack($pack, $output) : $output;
638    }
639
640    /**
641     * Use a secure random generator
642     *
643     * @param int $min
644     * @param int $max
645     * @return int
646     */
647    protected function random($min, $max){
648        try {
649            return random_int($min, $max);
650        } catch (\Exception $e) {
651            // availability of random source is checked elsewhere in DokuWiki
652            // we demote this to an unchecked runtime exception here
653            throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
654        }
655    }
656}
657