Subversion Repositories php_utils

Rev

Rev 60 | Rev 64 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
58 daniel-mar 1
<?php
2
 
3
/*
63 daniel-mar 4
 * ViaThinkSoft Modular Crypt Format 1.0 / vts_password_hash() / vts_password_verify()
58 daniel-mar 5
 * Copyright 2023 Daniel Marschall, ViaThinkSoft
63 daniel-mar 6
 * Revision 2023-02-27
58 daniel-mar 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
 
63 daniel-mar 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
 
58 daniel-mar 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)
60 daniel-mar 51
Like most Crypt-hashes, <salt> and <hash> are Radix64 coded
52
with alphabet './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' and no padding.
58 daniel-mar 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
 
63 daniel-mar 60
require_once __DIR__ . '/misc_functions.inc.php';
58 daniel-mar 61
 
63 daniel-mar 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
define('PASSWORD_STD_DES',   'std_des');
65
define('PASSWORD_EXT_DES',   'ext_des');
66
define('PASSWORD_MD5',       'md5');
67
define('PASSWORD_BLOWFISH',  'blowfish');
68
define('PASSWORD_SHA256',    'sha256');
69
define('PASSWORD_SHA512',    'sha512');
70
define('PASSWORD_VTS_MCF1',  OID_MCF_VTS_V1);
71
 
60 daniel-mar 72
define('BASE64_RFC4648_ALPHABET', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/');
73
define('BASE64_CRYPT_ALPHABET',   './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
58 daniel-mar 74
 
63 daniel-mar 75
// --- Part 1: Modular Crypt Format encode/decode
58 daniel-mar 76
 
77
function crypt_modular_format($id, $bin_salt, $bin_hash, $params=null) {
78
        // $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
79
        $out = '$'.$id;
80
        if (!is_null($params)) {
81
                $ary_params = array();
82
                //ksort($params);
83
                foreach ($params as $name => $value) {
84
                        $ary_params[] = "$name=$value";
85
                }
86
                $out .= '$'.implode(',',$ary_params);
87
        }
59 daniel-mar 88
        $out .= '$'.crypt_radix64_encode($bin_salt);
89
        $out .= '$'.crypt_radix64_encode($bin_hash);
58 daniel-mar 90
        return $out;
91
}
92
 
59 daniel-mar 93
function crypt_modular_format_decode($mcf) {
94
        $ary = explode('$', $mcf);
95
 
96
        $dummy = array_shift($ary);
97
        if ($dummy !== '') return false;
98
 
99
        $dummy = array_shift($ary);
100
        $id = $dummy;
101
 
102
        $params = array();
103
        $dummy = array_shift($ary);
104
        if (strpos($dummy, '=') !== false) {
105
                $params_ary = explode(',',$dummy);
106
                foreach ($params_ary as $param) {
107
                        $bry = explode('=', $param, 2);
108
                        if (count($bry) > 1) {
109
                                $params[$bry[0]] = $bry[1];
110
                        }
111
                }
112
        } else {
113
                array_unshift($ary, $dummy);
114
        }
115
 
116
        if (count($ary) > 1) {
117
                $dummy = array_shift($ary);
118
                $bin_salt = crypt_radix64_decode($dummy);
119
        } else {
120
                $bin_salt = '';
121
        }
122
 
123
        $dummy = array_shift($ary);
124
        $bin_hash = crypt_radix64_decode($dummy);
125
 
126
        return array('id' => $id, 'salt' => $bin_salt, 'hash' => $bin_hash, 'params' => $params);
127
}
128
 
63 daniel-mar 129
// --- Part 2: ViaThinkSoft Modular Crypt Format 1.0
130
 
58 daniel-mar 131
function vts_crypt($algo, $str_password, $str_salt, $ver='1', $mode='ps') {
132
        if ($ver == '1') {
133
                if ($mode == 'sp') {
134
                        $payload = $str_salt.$str_password;
135
                        if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512')) {
136
                                $bin_hash = sha3_512($payload, true);
137
                        } else {
138
                                $bin_hash = hash($algo, $payload, true);
139
                        }
140
                } else if ($mode == 'ps') {
141
                        $payload = $str_password.$str_salt;
142
                        if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512')) {
143
                                $bin_hash = sha3_512($payload, true);
144
                        } else {
145
                                $bin_hash = hash($algo, $payload, true);
146
                        }
147
                } else if ($mode == 'sps') {
148
                        $payload = $str_salt.$str_password.$str_salt;
149
                        if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512')) {
150
                                $bin_hash = sha3_512($payload, true);
151
                        } else {
152
                                $bin_hash = hash($algo, $payload, true);
153
                        }
154
                } else if ($mode == 'hmac') {
155
                        // 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
156
                        if (($algo === 'sha3-512') && !in_array($algo, hash_algos()) && function_exists('sha3_512_hmac')) {
157
                                $bin_hash = sha3_512_hmac($str_password, $str_salt, true);
158
                        } else {
159
                                $bin_hash = hash_hmac($algo, $str_password, $str_salt, true);
160
                        }
161
                } else {
162
                        throw new Exception("Invalid VTS crypt version 1 mode. Expect sp, ps, sps, or hmac.");
163
                }
164
                $bin_salt = $str_salt;
165
                return crypt_modular_format(OID_MCF_VTS_V1, $bin_salt, $bin_hash, array('a'=>$algo,'m'=>$mode));
166
        } else {
59 daniel-mar 167
                throw new Exception("Invalid VTS crypt version, expect 1.");
58 daniel-mar 168
        }
169
}
63 daniel-mar 170
 
171
// --- Part 3: vts_password_hash() and vts_password_verify()
172
 
173
/** This function extends password_verify() by adding ViaThinkSoft Modular Crypt Format 1.0.
174
 * @param string $password to be checked
175
 * @param string $hash Hash created by crypt(), password_hash(), or vts_password_hash().
176
 * @return bool true if password is valid
177
 */
178
function vts_password_verify($password, $hash): bool {
179
        if (str_starts_with($hash, '$'.PASSWORD_VTS_MCF1.'$')) {
180
 
181
                // Decode the MCF hash parameters
182
                $data = crypt_modular_format_decode($hash);
183
                if ($data === false) throw new Exception('Invalid auth key');
184
                $id = $data['id'];
185
                $bin_salt = $data['salt'];
186
                $bin_hash = $data['hash'];
187
                $params = $data['params'];
188
                $algo = $params['a'];
189
                $mode = $params['m'];
190
                $ver = '1';
191
 
192
                // Create a VTS MCF 1.0 hash based on the parameters of $hash and the password $password
193
                $calc_authkey_1 = vts_crypt($algo, $password, $bin_salt, $ver, $mode);
194
 
195
                // We rewrite the MCF to make sure that they match (if params) have the wrong order
196
                $calc_authkey_2 = crypt_modular_format($id, $bin_salt, $bin_hash, $params);
197
 
198
                return hash_equals($calc_authkey_1, $calc_authkey_2);
199
 
200
        } else {
201
                // password_hash() and crypt() hashes
202
                return password_verify($password, $hash);
203
        }
204
}
205
 
206
/** This function extends password_hash() with the algorithms supported by crypt().
207
 * It also adds ViaThinkSoft Modular Crypt Format 1.0.
208
 * The result can be verified using vts_password_verify().
209
 * @param string $password to be hashed
210
 * @param mixed $algo algorithm
211
 * @param array $options options for the hashing algorithm
212
 * @return string Crypt compatible password hash
213
 */
214
function vts_password_hash($password, $algo, $options=array()): string {
215
        $crypt_salt = null;
216
        if (($algo === PASSWORD_STD_DES) && defined('CRYPT_STD_DES')) {
217
                // 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.
218
                $crypt_salt = des_compat_salt(2);
219
        } else if (($algo === PASSWORD_EXT_DES) && defined('CRYPT_EXT_DES')) {
220
                // 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.
221
                $iterations = isset($options['iterations']) ? $options['iterations'] : 725;
222
                $crypt_salt = '_' . base64_int_encode($iterations) . des_compat_salt(4);
223
        } else if (($algo === PASSWORD_MD5) && defined('CRYPT_MD5')) {
224
                // MD5 hashing with a twelve character salt starting with $1$
225
                $crypt_salt = '$1$'.des_compat_salt(12).'$';
226
        } else if (($algo === PASSWORD_BLOWFISH) && defined('CRYPT_BLOWFISH')) {
227
                // 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.
228
                $algo = '$2y$'; // most secure
229
                $cost = isset($options['cost']) ? $options['cost'] : 10;
230
                $crypt_salt = $algo.str_pad($cost,2,'0',STR_PAD_LEFT).'$'.des_compat_salt(22).'$';
231
        } else if (($algo === PASSWORD_SHA256) && defined('CRYPT_SHA256')) {
232
                // 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.
233
                $algo = '$5$';
234
                $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
235
                $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
236
        } else if (($algo === PASSWORD_SHA512) && defined('CRYPT_SHA512')) {
237
                // 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.
238
                $algo = '$6$';
239
                $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
240
                $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
241
        }
242
 
243
        if (!is_null($crypt_salt)) {
244
                $out = crypt($password, $crypt_salt);
245
                if (strlen($out) < 13) throw new Exception("crypt() failed");
246
                return $out;
247
        } else if ($algo === PASSWORD_VTS_MCF1) {
248
                $ver  = '1';
249
                $algo = isset($options['algo']) ? $options['algo'] : 'sha3-512';
250
                $mode = isset($options['mode']) ? $options['mode'] : 'ps';
251
                $salt_len = isset($options['salt_length']) ? $options['salt_length'] : 50;
252
                $salt = random_bytes_ex($salt_len, true, true);
253
                return vts_crypt($algo, $password, $salt, $ver, $mode);
254
        } else {
255
                // $algo === PASSWORD_DEFAULT
256
                // $algo === PASSWORD_BCRYPT
257
                // $algo === PASSWORD_ARGON2I
258
                // $algo === PASSWORD_ARGON2ID
259
                return password_hash($password, $algo, $options);
260
        }
261
}
262
 
263
// --- Part 4: Useful functions required by the above functions
264
 
265
function des_compat_salt($salt_len) {
266
        if ($salt_len <= 0) return '';
267
        $characters = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
268
        $salt = '';
269
        $bytes = random_bytes_ex($salt_len, true, true);
270
        for ($i=0; $i<$salt_len; $i++) {
271
                $salt .= $characters[ord($bytes[$i]) % strlen($characters)];
272
        }
273
        return $salt;
274
}
275
 
276
function base64_int_encode($num) {
277
        // https://stackoverflow.com/questions/15534982/which-iteration-rules-apply-on-crypt-using-crypt-ext-des
278
        $alphabet_raw='./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
279
        $alphabet=str_split($alphabet_raw);
280
        $arr=array();
281
        $base=sizeof($alphabet);
282
        while($num) {
283
                $rem=$num % $base;
284
                $num=(int)($num / $base);
285
                $arr[]=$alphabet[$rem];
286
        }
287
        $string=implode($arr);
288
        return str_pad($string, 4, '.', STR_PAD_RIGHT);
289
}
290
 
291
function crypt_radix64_encode($str) {
292
        $x = $str;
293
        $x = base64_encode($x);
294
        $x = rtrim($x, '=');
295
        $x = strtr($x, BASE64_RFC4648_ALPHABET, BASE64_CRYPT_ALPHABET);
296
        return $x;
297
}
298
 
299
function crypt_radix64_decode($str) {
300
        $x = $str;
301
        $x = strtr($x, BASE64_CRYPT_ALPHABET, BASE64_RFC4648_ALPHABET);
302
        $x = base64_decode($x);
303
        return $x;
304
}
305
 
306
// --- Part 5: Selftest
307
 
308
/*
309
assert(crypt_radix64_decode(crypt_radix64_encode('test123')) === 'test123');
310
 
311
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_STD_DES)));
312
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_EXT_DES)));
313
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_MD5)));
314
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_BLOWFISH)));
315
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_SHA256)));
316
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_SHA512)));
317
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_VTS_MCF1)));
318
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_DEFAULT)));
319
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_BCRYPT)));
320
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_ARGON2I)));
321
assert(vts_password_Verify('test123',vts_password_hash('test123', PASSWORD_ARGON2ID)));
322
*/
323