Subversion Repositories php_utils

Rev

Rev 63 | Rev 65 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * ViaThinkSoft Modular Crypt Format 1.0 / vts_password_hash() / vts_password_verify()
  5.  * Copyright 2023 Daniel Marschall, ViaThinkSoft
  6.  * Revision 2023-02-27
  7.  *
  8.  * Licensed under the Apache License, Version 2.0 (the "License");
  9.  * you may not use this file except in compliance with the License.
  10.  * You may obtain a copy of the License at
  11.  *
  12.  *     http://www.apache.org/licenses/LICENSE-2.0
  13.  *
  14.  * Unless required by applicable law or agreed to in writing, software
  15.  * distributed under the License is distributed on an "AS IS" BASIS,
  16.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17.  * See the License for the specific language governing permissions and
  18.  * limitations under the License.
  19.  */
  20.  
  21. /*
  22.  
  23. The function vts_password_hash() replaces password_hash()
  24. and adds the ViaThinkSoft Modular Crypt Format 1.0 hash as well as
  25. all hashes from password_hash() and crypt().
  26.  
  27. The function vts_password_verify() replaces password_verify().
  28.  
  29. ViaThinkSoft Modular Crypt Format 1.0 performs a simple hash or HMAC operation.
  30. No key derivation function or iterations are performed.
  31. Format:
  32.         $1.3.6.1.4.1.37476.3.0.1.1$a=<algo>,m=<mode>$<salt>$<hash>
  33. where <algo> is any valid hash algorithm (name scheme of PHP hash_algos() preferred), e.g.
  34.         sha3-512
  35.         sha3-384
  36.         sha3-256
  37.         sha3-224
  38.         sha512
  39.         sha512/256
  40.         sha512/224
  41.         sha384
  42.         sha256
  43.         sha224
  44.         sha1
  45.         md5
  46. Valid <mode> :
  47.         sp = salt + password
  48.         ps = password + salt
  49.         sps = salt + password + salt
  50.         hmac = HMAC (salt is the key)
  51. Like most Crypt-hashes, <salt> and <hash> are Radix64 coded
  52. with alphabet './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' and no padding.
  53. Link to the online specification:
  54.         https://oidplus.viathinksoft.com/oidplus/?goto=oid%3A1.3.6.1.4.1.37476.3.0.1.1
  55. Reference implementation in PHP:
  56.         https://github.com/danielmarschall/php_utils/blob/master/vts_crypt.inc.php
  57.  
  58. */
  59.  
  60. require_once __DIR__ . '/misc_functions.inc.php';
  61.  
  62. define('OID_MCF_VTS_V1',     '1.3.6.1.4.1.37476.3.0.1.1'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 specifications(3) misc(0) modular-crypt-format(1) vts-crypt-v1(1) }
  63.  
  64. // Valid algorithms for vts_password_hash():
  65. define('PASSWORD_STD_DES',   'std_des');       // Algorithm from crypt()
  66. define('PASSWORD_EXT_DES',   'ext_des');       // Algorithm from crypt()
  67. define('PASSWORD_MD5',       'md5');           // Algorithm from crypt()
  68. define('PASSWORD_BLOWFISH',  'blowfish');      // Algorithm from crypt()
  69. define('PASSWORD_SHA256',    'sha256');        // Algorithm from crypt()
  70. define('PASSWORD_SHA512',    'sha512');        // Algorithm from crypt()
  71. define('PASSWORD_VTS_MCF1',  OID_MCF_VTS_V1);  // Algorithm from ViaThinkSoft
  72. // Other valid values (already defined in PHP):
  73. // - PASSWORD_DEFAULT
  74. // - PASSWORD_BCRYPT
  75. // - PASSWORD_ARGON2I
  76. // - PASSWORD_ARGON2ID
  77.  
  78. // --- Part 1: Modular Crypt Format encode/decode
  79.  
  80. function crypt_modular_format_encode($id, $bin_salt, $bin_hash, $params=null) {
  81.         // $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
  82.         $out = '$'.$id;
  83.         if (!is_null($params)) {
  84.                 $ary_params = array();
  85.                 foreach ($params as $name => $value) {
  86.                         $ary_params[] = "$name=$value";
  87.                 }
  88.                 $out .= '$'.implode(',',$ary_params);
  89.         }
  90.         $out .= '$'.crypt_radix64_encode($bin_salt);
  91.         $out .= '$'.crypt_radix64_encode($bin_hash);
  92.         return $out;
  93. }
  94.  
  95. function crypt_modular_format_decode($mcf) {
  96.         $ary = explode('$', $mcf);
  97.  
  98.         $dummy = array_shift($ary);
  99.         if ($dummy !== '') return false;
  100.  
  101.         $dummy = array_shift($ary);
  102.         $id = $dummy;
  103.  
  104.         $params = array();
  105.         $dummy = array_shift($ary);
  106.         if (strpos($dummy, '=') !== false) {
  107.                 $params_ary = explode(',',$dummy);
  108.                 foreach ($params_ary as $param) {
  109.                         $bry = explode('=', $param, 2);
  110.                         if (count($bry) > 1) {
  111.                                 $params[$bry[0]] = $bry[1];
  112.                         }
  113.                 }
  114.         } else {
  115.                 array_unshift($ary, $dummy);
  116.         }
  117.  
  118.         if (count($ary) > 1) {
  119.                 $dummy = array_shift($ary);
  120.                 $bin_salt = crypt_radix64_decode($dummy);
  121.         } else {
  122.                 $bin_salt = '';
  123.         }
  124.  
  125.         $dummy = array_shift($ary);
  126.         $bin_hash = crypt_radix64_decode($dummy);
  127.  
  128.         return array('id' => $id, 'salt' => $bin_salt, 'hash' => $bin_hash, 'params' => $params);
  129. }
  130.  
  131. // --- Part 2: ViaThinkSoft Modular Crypt Format 1.0
  132.  
  133. function vts_crypt_version($hash) {
  134.         if (str_starts_with($hash, '$'.OID_MCF_VTS_V1.'$')) {
  135.                 return '1';
  136.         } else {
  137.                 return '0';
  138.         }
  139. }
  140.  
  141. function vts_crypt_hash($algo, $str_password, $str_salt, $ver='1', $mode='ps') {
  142.         if ($ver == '1') {
  143.                 if ($mode == 'sp') {
  144.                         $payload = $str_salt.$str_password;
  145.                         if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512')) {
  146.                                 $bin_hash = sha3_512($payload, true);
  147.                         } else {
  148.                                 $bin_hash = hash($algo, $payload, true);
  149.                         }
  150.                 } else if ($mode == 'ps') {
  151.                         $payload = $str_password.$str_salt;
  152.                         if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512')) {
  153.                                 $bin_hash = sha3_512($payload, true);
  154.                         } else {
  155.                                 $bin_hash = hash($algo, $payload, true);
  156.                         }
  157.                 } else if ($mode == 'sps') {
  158.                         $payload = $str_salt.$str_password.$str_salt;
  159.                         if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512')) {
  160.                                 $bin_hash = sha3_512($payload, true);
  161.                         } else {
  162.                                 $bin_hash = hash($algo, $payload, true);
  163.                         }
  164.                 } else if ($mode == 'hmac') {
  165.                         // Note: Actually, we should use hash_hmac_algos(), but this requires PHP 7.2, and we would like to stay compatible with PHP 7.0 for now
  166.                         if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512_hmac')) {
  167.                                 $bin_hash = sha3_512_hmac($str_password, $str_salt, true);
  168.                         } else {
  169.                                 $bin_hash = hash_hmac($algo, $str_password, $str_salt, true);
  170.                         }
  171.                 } else {
  172.                         throw new Exception("Invalid VTS crypt version 1 mode. Expect sp, ps, sps, or hmac.");
  173.                 }
  174.                 $bin_salt = $str_salt;
  175.                 return crypt_modular_format_encode(OID_MCF_VTS_V1, $bin_salt, $bin_hash, array('a'=>$algo,'m'=>$mode));
  176.         } else {
  177.                 throw new Exception("Invalid VTS crypt version, expect 1.");
  178.         }
  179. }
  180.  
  181. function vts_crypt_verify($password, $hash): bool {
  182.         $ver = vts_crypt_version($hash);
  183.         if ($ver == '1') {
  184.                 // Decode the MCF hash parameters
  185.                 $data = crypt_modular_format_decode($hash);
  186.                 if ($data === false) throw new Exception('Invalid auth key');
  187.                 $id = $data['id'];
  188.                 $bin_salt = $data['salt'];
  189.                 $bin_hash = $data['hash'];
  190.                 $params = $data['params'];
  191.                 $algo = $params['a'];
  192.                 $mode = $params['m'];
  193.  
  194.                 // Create a VTS MCF 1.0 hash based on the parameters of $hash and the password $password
  195.                 $calc_authkey_1 = vts_crypt_hash($algo, $password, $bin_salt, $ver, $mode);
  196.  
  197.                 // We rewrite the MCF to make sure that they match (if params have the wrong order)
  198.                 $calc_authkey_2 = crypt_modular_format_encode($id, $bin_salt, $bin_hash, $params);
  199.  
  200.                 return hash_equals($calc_authkey_1, $calc_authkey_2);
  201.         } else {
  202.                 throw new Exception("Invalid VTS crypt version, expect 1.");
  203.         }
  204. }
  205.  
  206. // --- Part 3: vts_password_hash() and vts_password_verify()
  207.  
  208. /** This function extends password_verify() by adding ViaThinkSoft Modular Crypt Format 1.0.
  209.  * @param string $password to be checked
  210.  * @param string $hash Hash created by crypt(), password_hash(), or vts_password_hash().
  211.  * @return bool true if password is valid
  212.  */
  213. function vts_password_verify($password, $hash): bool {
  214.         if (vts_crypt_version($hash) != '0') {
  215.                 // Hash created by vts_password_hash(), or vts_crypt_hash()
  216.                 return vts_crypt_verify($password, $hash);
  217.         } else {
  218.                 // Hash created by vts_password_hash(), password_hash(), or crypt()
  219.                 return password_verify($password, $hash);
  220.         }
  221. }
  222.  
  223. /** This function extends password_hash() with the algorithms supported by crypt().
  224.  * It also adds vts_crypt_hash() which implements the ViaThinkSoft Modular Crypt Format 1.0.
  225.  * The result can be verified using vts_password_verify().
  226.  * @param string $password to be hashed
  227.  * @param mixed $algo algorithm
  228.  * @param array $options options for the hashing algorithm
  229.  * @return string Crypt style password hash
  230.  */
  231. function vts_password_hash($password, $algo, $options=array()): string {
  232.         $crypt_salt = null;
  233.         if (($algo === PASSWORD_STD_DES) && defined('CRYPT_STD_DES')) {
  234.                 // Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  235.                 $crypt_salt = des_compat_salt(2);
  236.         } else if (($algo === PASSWORD_EXT_DES) && defined('CRYPT_EXT_DES')) {
  237.                 // Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 characters of iteration count and 4 characters of salt. Each of these 4-character strings encode 24 bits, least significant character first. The values 0 to 63 are encoded as ./0-9A-Za-z. Using invalid characters in the salt will cause crypt() to fail.
  238.                 $iterations = isset($options['iterations']) ? $options['iterations'] : 725;
  239.                 $crypt_salt = '_' . base64_int_encode($iterations) . des_compat_salt(4);
  240.         } else if (($algo === PASSWORD_MD5) && defined('CRYPT_MD5')) {
  241.                 // MD5 hashing with a twelve character salt starting with $1$
  242.                 $crypt_salt = '$1$'.des_compat_salt(12).'$';
  243.         } else if (($algo === PASSWORD_BLOWFISH) && defined('CRYPT_BLOWFISH')) {
  244.                 // Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithm and must be in range 04-31, values outside this range will cause crypt() to fail. "$2x$" hashes are potentially weak; "$2a$" hashes are compatible and mitigate this weakness. For new hashes, "$2y$" should be used.
  245.                 $algo = '$2y$'; // most secure
  246.                 $cost = isset($options['cost']) ? $options['cost'] : 10;
  247.                 $crypt_salt = $algo.str_pad($cost,2,'0',STR_PAD_LEFT).'$'.des_compat_salt(22).'$';
  248.         } else if (($algo === PASSWORD_SHA256) && defined('CRYPT_SHA256')) {
  249.                 // SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  250.                 $algo = '$5$';
  251.                 $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
  252.                 $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
  253.         } else if (($algo === PASSWORD_SHA512) && defined('CRYPT_SHA512')) {
  254.                 // SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  255.                 $algo = '$6$';
  256.                 $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
  257.                 $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
  258.         }
  259.  
  260.         if (!is_null($crypt_salt)) {
  261.                 // Algorithms: PASSWORD_STD_DES
  262.                 //             PASSWORD_EXT_DES
  263.                 //             PASSWORD_MD5
  264.                 //             PASSWORD_BLOWFISH
  265.                 //             PASSWORD_SHA256
  266.                 //             PASSWORD_SHA512
  267.                 $out = crypt($password, $crypt_salt);
  268.                 if (strlen($out) < 13) throw new Exception("crypt() failed");
  269.                 return $out;
  270.         } else if ($algo === PASSWORD_VTS_MCF1) {
  271.                 // Algorithms: PASSWORD_VTS_MCF1
  272.                 $ver  = '1';
  273.                 $algo = isset($options['algo']) ? $options['algo'] : 'sha3-512';
  274.                 $mode = isset($options['mode']) ? $options['mode'] : 'ps';
  275.                 $salt_len = isset($options['salt_length']) ? $options['salt_length'] : 50;
  276.                 $salt = random_bytes_ex($salt_len, true, true);
  277.                 return vts_crypt_hash($algo, $password, $salt, $ver, $mode);
  278.         } else {
  279.                 // Algorithms: PASSWORD_DEFAULT
  280.                 //             PASSWORD_BCRYPT
  281.                 //             PASSWORD_ARGON2I
  282.                 //             PASSWORD_ARGON2ID
  283.                 return password_hash($password, $algo, $options);
  284.         }
  285. }
  286.  
  287. // --- Part 4: Useful functions required by the crypt-functions
  288.  
  289. define('BASE64_RFC4648_ALPHABET', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/');
  290. define('BASE64_CRYPT_ALPHABET',   './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
  291.  
  292. function des_compat_salt($salt_len) {
  293.         if ($salt_len <= 0) return '';
  294.         $characters = BASE64_CRYPT_ALPHABET;
  295.         $salt = '';
  296.         $bytes = random_bytes_ex($salt_len, true, true);
  297.         for ($i=0; $i<$salt_len; $i++) {
  298.                 $salt .= $characters[ord($bytes[$i]) % strlen($characters)];
  299.         }
  300.         return $salt;
  301. }
  302.  
  303. function base64_int_encode($num) {
  304.         // https://stackoverflow.com/questions/15534982/which-iteration-rules-apply-on-crypt-using-crypt-ext-des
  305.         $alphabet_raw = BASE64_CRYPT_ALPHABET;
  306.         $alphabet = str_split($alphabet_raw);
  307.         $arr = array();
  308.         $base = sizeof($alphabet);
  309.         while ($num) {
  310.                 $rem = $num % $base;
  311.                 $num = (int)($num / $base);
  312.                 $arr[] = $alphabet[$rem];
  313.         }
  314.         $string = implode($arr);
  315.         return str_pad($string, 4, '.', STR_PAD_RIGHT);
  316. }
  317.  
  318. function crypt_radix64_encode($str) {
  319.         $x = $str;
  320.         $x = base64_encode($x);
  321.         $x = rtrim($x, '='); // remove padding
  322.         $x = strtr($x, BASE64_RFC4648_ALPHABET, BASE64_CRYPT_ALPHABET);
  323.         return $x;
  324. }
  325.  
  326. function crypt_radix64_decode($str) {
  327.         $x = $str;
  328.         $x = strtr($x, BASE64_CRYPT_ALPHABET, BASE64_RFC4648_ALPHABET);
  329.         $x = base64_decode($x);
  330.         return $x;
  331. }
  332.  
  333. // --- Part 5: Selftest
  334.  
  335. /*
  336. $rnd = random_bytes_ex(50, true, true);
  337. assert(crypt_radix64_decode(crypt_radix64_encode($rnd)) === $rnd);
  338.  
  339. $password = random_bytes_ex(20, false, true);
  340. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_STD_DES)));
  341. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_EXT_DES)));
  342. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_MD5)));
  343. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_BLOWFISH)));
  344. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_SHA256)));
  345. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_SHA512)));
  346. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_VTS_MCF1)));
  347. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_DEFAULT)));
  348. assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_BCRYPT)));
  349. if (defined('PASSWORD_ARGON2I'))
  350.         assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_ARGON2I)));
  351. if (defined('PASSWORD_ARGON2ID'))
  352.         assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_ARGON2ID)));
  353. echo "OK, Password $password\n";
  354. */
  355.