1 /*
2 +----------------------------------------------------------------------+
3 | Copyright (c) The PHP Group |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.01 of the PHP license, |
6 | that is bundled with this package in the file LICENSE, and is |
7 | available through the world-wide-web at the following url: |
8 | http://www.php.net/license/3_01.txt |
9 | If you did not receive a copy of the PHP license and are unable to |
10 | obtain it through the world-wide-web, please send a note to |
11 | license@php.net so we can mail you a copy immediately. |
12 +----------------------------------------------------------------------+
13 | Author: Sara Golemon <pollita@php.net> |
14 | Scott MacVicar <scottmac@php.net> |
15 +----------------------------------------------------------------------+
16 */
17
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <math.h>
23 #include "php_hash.h"
24 #include "ext/standard/info.h"
25 #include "ext/standard/file.h"
26 #include "ext/standard/php_var.h"
27 #include "ext/spl/spl_exceptions.h"
28
29 #include "zend_interfaces.h"
30 #include "zend_exceptions.h"
31 #include "zend_smart_str.h"
32
33 #include "hash_arginfo.h"
34
35 #ifdef PHP_WIN32
36 # define __alignof__ __alignof
37 #else
38 # ifndef HAVE_ALIGNOF
39 # include <stddef.h>
40 # define __alignof__(type) offsetof (struct { char c; type member;}, member)
41 # endif
42 #endif
43
44 HashTable php_hash_hashtable;
45 zend_class_entry *php_hashcontext_ce;
46 static zend_object_handlers php_hashcontext_handlers;
47
48 #ifdef PHP_MHASH_BC
49 struct mhash_bc_entry {
50 char *mhash_name;
51 char *hash_name;
52 int value;
53 };
54
55 #define MHASH_NUM_ALGOS 35
56
57 static struct mhash_bc_entry mhash_to_hash[MHASH_NUM_ALGOS] = {
58 {"CRC32", "crc32", 0}, /* used by bzip */
59 {"MD5", "md5", 1},
60 {"SHA1", "sha1", 2},
61 {"HAVAL256", "haval256,3", 3},
62 {NULL, NULL, 4},
63 {"RIPEMD160", "ripemd160", 5},
64 {NULL, NULL, 6},
65 {"TIGER", "tiger192,3", 7},
66 {"GOST", "gost", 8},
67 {"CRC32B", "crc32b", 9}, /* used by ethernet (IEEE 802.3), gzip, zip, png, etc */
68 {"HAVAL224", "haval224,3", 10},
69 {"HAVAL192", "haval192,3", 11},
70 {"HAVAL160", "haval160,3", 12},
71 {"HAVAL128", "haval128,3", 13},
72 {"TIGER128", "tiger128,3", 14},
73 {"TIGER160", "tiger160,3", 15},
74 {"MD4", "md4", 16},
75 {"SHA256", "sha256", 17},
76 {"ADLER32", "adler32", 18},
77 {"SHA224", "sha224", 19},
78 {"SHA512", "sha512", 20},
79 {"SHA384", "sha384", 21},
80 {"WHIRLPOOL", "whirlpool", 22},
81 {"RIPEMD128", "ripemd128", 23},
82 {"RIPEMD256", "ripemd256", 24},
83 {"RIPEMD320", "ripemd320", 25},
84 {NULL, NULL, 26}, /* support needs to be added for snefru 128 */
85 {"SNEFRU256", "snefru256", 27},
86 {"MD2", "md2", 28},
87 {"FNV132", "fnv132", 29},
88 {"FNV1A32", "fnv1a32", 30},
89 {"FNV164", "fnv164", 31},
90 {"FNV1A64", "fnv1a64", 32},
91 {"JOAAT", "joaat", 33},
92 {"CRC32C", "crc32c", 34}, /* Castagnoli's CRC, used by iSCSI, SCTP, Btrfs, ext4, etc */
93 };
94 #endif
95
96 /* Hash Registry Access */
97
php_hash_fetch_ops(zend_string * algo)98 PHP_HASH_API const php_hash_ops *php_hash_fetch_ops(zend_string *algo) /* {{{ */
99 {
100 zend_string *lower = zend_string_tolower(algo);
101 php_hash_ops *ops = zend_hash_find_ptr(&php_hash_hashtable, lower);
102 zend_string_release(lower);
103
104 return ops;
105 }
106 /* }}} */
107
php_hash_register_algo(const char * algo,const php_hash_ops * ops)108 PHP_HASH_API void php_hash_register_algo(const char *algo, const php_hash_ops *ops) /* {{{ */
109 {
110 size_t algo_len = strlen(algo);
111 char *lower = zend_str_tolower_dup(algo, algo_len);
112 zend_hash_add_ptr(&php_hash_hashtable, zend_string_init_interned(lower, algo_len, 1), (void *) ops);
113 efree(lower);
114 }
115 /* }}} */
116
php_hash_copy(const void * ops,void * orig_context,void * dest_context)117 PHP_HASH_API int php_hash_copy(const void *ops, void *orig_context, void *dest_context) /* {{{ */
118 {
119 php_hash_ops *hash_ops = (php_hash_ops *)ops;
120
121 memcpy(dest_context, orig_context, hash_ops->context_size);
122 return SUCCESS;
123 }
124 /* }}} */
125
126
align_to(size_t pos,size_t alignment)127 static inline size_t align_to(size_t pos, size_t alignment) {
128 size_t offset = pos & (alignment - 1);
129 return pos + (offset ? alignment - offset : 0);
130 }
131
parse_serialize_spec(const char ** specp,size_t * pos,size_t * sz,size_t * max_alignment)132 static size_t parse_serialize_spec(
133 const char **specp, size_t *pos, size_t *sz, size_t *max_alignment) {
134 size_t count, alignment;
135 const char *spec = *specp;
136 /* parse size */
137 if (*spec == 's' || *spec == 'S') {
138 *sz = 2;
139 alignment = __alignof__(uint16_t); /* usually 2 */
140 } else if (*spec == 'l' || *spec == 'L') {
141 *sz = 4;
142 alignment = __alignof__(uint32_t); /* usually 4 */
143 } else if (*spec == 'q' || *spec == 'Q') {
144 *sz = 8;
145 alignment = __alignof__(uint64_t); /* usually 8 */
146 } else if (*spec == 'i' || *spec == 'I') {
147 *sz = sizeof(int);
148 alignment = __alignof__(int); /* usually 4 */
149 } else {
150 ZEND_ASSERT(*spec == 'b' || *spec == 'B');
151 *sz = 1;
152 alignment = 1;
153 }
154 /* process alignment */
155 *pos = align_to(*pos, alignment);
156 *max_alignment = *max_alignment < alignment ? alignment : *max_alignment;
157 /* parse count */
158 ++spec;
159 if (isdigit((unsigned char) *spec)) {
160 count = 0;
161 while (isdigit((unsigned char) *spec)) {
162 count = 10 * count + *spec - '0';
163 ++spec;
164 }
165 } else {
166 count = 1;
167 }
168 *specp = spec;
169 return count;
170 }
171
one_from_buffer(size_t sz,const unsigned char * buf)172 static uint64_t one_from_buffer(size_t sz, const unsigned char *buf) {
173 if (sz == 2) {
174 const uint16_t *x = (const uint16_t *) buf;
175 return *x;
176 } else if (sz == 4) {
177 const uint32_t *x = (const uint32_t *) buf;
178 return *x;
179 } else if (sz == 8) {
180 const uint64_t *x = (const uint64_t *) buf;
181 return *x;
182 } else {
183 ZEND_ASSERT(sz == 1);
184 return *buf;
185 }
186 }
187
one_to_buffer(size_t sz,unsigned char * buf,uint64_t val)188 static void one_to_buffer(size_t sz, unsigned char *buf, uint64_t val) {
189 if (sz == 2) {
190 uint16_t *x = (uint16_t *) buf;
191 *x = val;
192 } else if (sz == 4) {
193 uint32_t *x = (uint32_t *) buf;
194 *x = val;
195 } else if (sz == 8) {
196 uint64_t *x = (uint64_t *) buf;
197 *x = val;
198 } else {
199 ZEND_ASSERT(sz == 1);
200 *buf = val;
201 }
202 }
203
204 /* Serialize a hash context according to a `spec` string.
205 Spec contents:
206 b[COUNT] -- serialize COUNT bytes
207 s[COUNT] -- serialize COUNT 16-bit integers
208 l[COUNT] -- serialize COUNT 32-bit integers
209 q[COUNT] -- serialize COUNT 64-bit integers
210 i[COUNT] -- serialize COUNT `int`s
211 B[COUNT] -- skip COUNT bytes
212 S[COUNT], L[COUNT], etc. -- uppercase versions skip instead of read
213 . (must be last character) -- assert that the hash context has exactly
214 this size
215 Example: "llllllb64l16." is the spec for an MD5 context: 6 32-bit
216 integers, followed by 64 bytes, then 16 32-bit integers, and that's
217 exactly the size of the context.
218
219 The serialization result is an array. Each integer is serialized as a
220 32-bit integer, except that a run of 2 or more bytes is encoded as a
221 string, and each 64-bit integer is serialized as two 32-bit integers, least
222 significant bits first. This allows 32-bit and 64-bit architectures to
223 interchange serialized HashContexts. */
224
php_hash_serialize_spec(const php_hashcontext_object * hash,zval * zv,const char * spec)225 PHP_HASH_API int php_hash_serialize_spec(const php_hashcontext_object *hash, zval *zv, const char *spec) /* {{{ */
226 {
227 size_t pos = 0, max_alignment = 1;
228 unsigned char *buf = (unsigned char *) hash->context;
229 zval tmp;
230 if (buf == NULL) {
231 return FAILURE;
232 }
233 array_init(zv);
234 while (*spec != '\0' && *spec != '.') {
235 char spec_ch = *spec;
236 size_t sz, count = parse_serialize_spec(&spec, &pos, &sz, &max_alignment);
237 if (pos + count * sz > hash->ops->context_size) {
238 return FAILURE;
239 }
240 if (isupper((unsigned char) spec_ch)) {
241 pos += count * sz;
242 } else if (sz == 1 && count > 1) {
243 ZVAL_STRINGL(&tmp, (char *) buf + pos, count);
244 zend_hash_next_index_insert(Z_ARRVAL_P(zv), &tmp);
245 pos += count;
246 } else {
247 while (count > 0) {
248 uint64_t val = one_from_buffer(sz, buf + pos);
249 pos += sz;
250 ZVAL_LONG(&tmp, (int32_t) val);
251 zend_hash_next_index_insert(Z_ARRVAL_P(zv), &tmp);
252 if (sz == 8) {
253 ZVAL_LONG(&tmp, (int32_t) (val >> 32));
254 zend_hash_next_index_insert(Z_ARRVAL_P(zv), &tmp);
255 }
256 --count;
257 }
258 }
259 }
260 if (*spec == '.' && align_to(pos, max_alignment) != hash->ops->context_size) {
261 return FAILURE;
262 }
263 return SUCCESS;
264 }
265 /* }}} */
266
267 /* Unserialize a hash context serialized by `php_hash_serialize_spec` with `spec`.
268 Returns SUCCESS on success and a negative error code on failure.
269 Codes: FAILURE (-1) == generic failure
270 -999 == spec wrong size for context
271 -1000 - POS == problem at byte offset POS */
272
php_hash_unserialize_spec(php_hashcontext_object * hash,const zval * zv,const char * spec)273 PHP_HASH_API int php_hash_unserialize_spec(php_hashcontext_object *hash, const zval *zv, const char *spec) /* {{{ */
274 {
275 size_t pos = 0, max_alignment = 1, j = 0;
276 unsigned char *buf = (unsigned char *) hash->context;
277 zval *elt;
278 if (Z_TYPE_P(zv) != IS_ARRAY) {
279 return FAILURE;
280 }
281 while (*spec != '\0' && *spec != '.') {
282 char spec_ch = *spec;
283 size_t sz, count = parse_serialize_spec(&spec, &pos, &sz, &max_alignment);
284 if (pos + count * sz > hash->ops->context_size) {
285 return -999;
286 }
287 if (isupper((unsigned char) spec_ch)) {
288 pos += count * sz;
289 } else if (sz == 1 && count > 1) {
290 elt = zend_hash_index_find(Z_ARRVAL_P(zv), j);
291 if (!elt || Z_TYPE_P(elt) != IS_STRING || Z_STRLEN_P(elt) != count) {
292 return -1000 - pos;
293 }
294 ++j;
295 memcpy(buf + pos, Z_STRVAL_P(elt), count);
296 pos += count;
297 } else {
298 while (count > 0) {
299 uint64_t val;
300 elt = zend_hash_index_find(Z_ARRVAL_P(zv), j);
301 if (!elt || Z_TYPE_P(elt) != IS_LONG) {
302 return -1000 - pos;
303 }
304 ++j;
305 val = (uint32_t) Z_LVAL_P(elt);
306 if (sz == 8) {
307 elt = zend_hash_index_find(Z_ARRVAL_P(zv), j);
308 if (!elt || Z_TYPE_P(elt) != IS_LONG) {
309 return -1000 - pos;
310 }
311 ++j;
312 val += ((uint64_t) Z_LVAL_P(elt)) << 32;
313 }
314 one_to_buffer(sz, buf + pos, val);
315 pos += sz;
316 --count;
317 }
318 }
319 }
320 if (*spec == '.' && align_to(pos, max_alignment) != hash->ops->context_size) {
321 return -999;
322 }
323 return SUCCESS;
324 }
325 /* }}} */
326
php_hash_serialize(const php_hashcontext_object * hash,zend_long * magic,zval * zv)327 PHP_HASH_API int php_hash_serialize(const php_hashcontext_object *hash, zend_long *magic, zval *zv) /* {{{ */
328 {
329 if (hash->ops->serialize_spec) {
330 *magic = PHP_HASH_SERIALIZE_MAGIC_SPEC;
331 return php_hash_serialize_spec(hash, zv, hash->ops->serialize_spec);
332 } else {
333 return FAILURE;
334 }
335 }
336 /* }}} */
337
php_hash_unserialize(php_hashcontext_object * hash,zend_long magic,const zval * zv)338 PHP_HASH_API int php_hash_unserialize(php_hashcontext_object *hash, zend_long magic, const zval *zv) /* {{{ */
339 {
340 if (hash->ops->serialize_spec
341 && magic == PHP_HASH_SERIALIZE_MAGIC_SPEC) {
342 return php_hash_unserialize_spec(hash, zv, hash->ops->serialize_spec);
343 } else {
344 return FAILURE;
345 }
346 }
347 /* }}} */
348
349 /* Userspace */
350
php_hash_do_hash(zval * return_value,zend_string * algo,char * data,size_t data_len,zend_bool raw_output,bool isfilename)351 static void php_hash_do_hash(
352 zval *return_value, zend_string *algo, char *data, size_t data_len, zend_bool raw_output, bool isfilename
353 ) /* {{{ */ {
354 zend_string *digest;
355 const php_hash_ops *ops;
356 void *context;
357 php_stream *stream = NULL;
358
359 ops = php_hash_fetch_ops(algo);
360 if (!ops) {
361 zend_argument_value_error(1, "must be a valid hashing algorithm");
362 RETURN_THROWS();
363 }
364 if (isfilename) {
365 if (CHECK_NULL_PATH(data, data_len)) {
366 zend_argument_value_error(1, "must not contain any null bytes");
367 RETURN_THROWS();
368 }
369 stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, FG(default_context));
370 if (!stream) {
371 /* Stream will report errors opening file */
372 RETURN_FALSE;
373 }
374 }
375
376 context = php_hash_alloc_context(ops);
377 ops->hash_init(context);
378
379 if (isfilename) {
380 char buf[1024];
381 ssize_t n;
382
383 while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
384 ops->hash_update(context, (unsigned char *) buf, n);
385 }
386 php_stream_close(stream);
387 if (n < 0) {
388 efree(context);
389 RETURN_FALSE;
390 }
391 } else {
392 ops->hash_update(context, (unsigned char *) data, data_len);
393 }
394
395 digest = zend_string_alloc(ops->digest_size, 0);
396 ops->hash_final((unsigned char *) ZSTR_VAL(digest), context);
397 efree(context);
398
399 if (raw_output) {
400 ZSTR_VAL(digest)[ops->digest_size] = 0;
401 RETURN_NEW_STR(digest);
402 } else {
403 zend_string *hex_digest = zend_string_safe_alloc(ops->digest_size, 2, 0, 0);
404
405 php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
406 ZSTR_VAL(hex_digest)[2 * ops->digest_size] = 0;
407 zend_string_release_ex(digest, 0);
408 RETURN_NEW_STR(hex_digest);
409 }
410 }
411 /* }}} */
412
413 /* {{{ Generate a hash of a given input string
414 Returns lowercase hexits by default */
PHP_FUNCTION(hash)415 PHP_FUNCTION(hash)
416 {
417 zend_string *algo;
418 char *data;
419 size_t data_len;
420 zend_bool raw_output = 0;
421
422 ZEND_PARSE_PARAMETERS_START(2, 3)
423 Z_PARAM_STR(algo)
424 Z_PARAM_STRING(data, data_len)
425 Z_PARAM_OPTIONAL
426 Z_PARAM_BOOL(raw_output)
427 ZEND_PARSE_PARAMETERS_END();
428
429 php_hash_do_hash(return_value, algo, data, data_len, raw_output, 0);
430 }
431 /* }}} */
432
433 /* {{{ Generate a hash of a given file
434 Returns lowercase hexits by default */
PHP_FUNCTION(hash_file)435 PHP_FUNCTION(hash_file)
436 {
437 zend_string *algo;
438 char *data;
439 size_t data_len;
440 zend_bool raw_output = 0;
441
442 ZEND_PARSE_PARAMETERS_START(2, 3)
443 Z_PARAM_STR(algo)
444 Z_PARAM_STRING(data, data_len)
445 Z_PARAM_OPTIONAL
446 Z_PARAM_BOOL(raw_output)
447 ZEND_PARSE_PARAMETERS_END();
448
449 php_hash_do_hash(return_value, algo, data, data_len, raw_output, 1);
450 }
451 /* }}} */
452
php_hash_string_xor_char(unsigned char * out,const unsigned char * in,const unsigned char xor_with,const size_t length)453 static inline void php_hash_string_xor_char(unsigned char *out, const unsigned char *in, const unsigned char xor_with, const size_t length) {
454 size_t i;
455 for (i=0; i < length; i++) {
456 out[i] = in[i] ^ xor_with;
457 }
458 }
459
php_hash_string_xor(unsigned char * out,const unsigned char * in,const unsigned char * xor_with,const size_t length)460 static inline void php_hash_string_xor(unsigned char *out, const unsigned char *in, const unsigned char *xor_with, const size_t length) {
461 size_t i;
462 for (i=0; i < length; i++) {
463 out[i] = in[i] ^ xor_with[i];
464 }
465 }
466
php_hash_hmac_prep_key(unsigned char * K,const php_hash_ops * ops,void * context,const unsigned char * key,const size_t key_len)467 static inline void php_hash_hmac_prep_key(unsigned char *K, const php_hash_ops *ops, void *context, const unsigned char *key, const size_t key_len) {
468 memset(K, 0, ops->block_size);
469 if (key_len > ops->block_size) {
470 /* Reduce the key first */
471 ops->hash_init(context);
472 ops->hash_update(context, key, key_len);
473 ops->hash_final(K, context);
474 } else {
475 memcpy(K, key, key_len);
476 }
477 /* XOR the key with 0x36 to get the ipad) */
478 php_hash_string_xor_char(K, K, 0x36, ops->block_size);
479 }
480
php_hash_hmac_round(unsigned char * final,const php_hash_ops * ops,void * context,const unsigned char * key,const unsigned char * data,const zend_long data_size)481 static inline void php_hash_hmac_round(unsigned char *final, const php_hash_ops *ops, void *context, const unsigned char *key, const unsigned char *data, const zend_long data_size) {
482 ops->hash_init(context);
483 ops->hash_update(context, key, ops->block_size);
484 ops->hash_update(context, data, data_size);
485 ops->hash_final(final, context);
486 }
487
php_hash_do_hash_hmac(zval * return_value,zend_string * algo,char * data,size_t data_len,char * key,size_t key_len,zend_bool raw_output,bool isfilename)488 static void php_hash_do_hash_hmac(
489 zval *return_value, zend_string *algo, char *data, size_t data_len, char *key, size_t key_len, zend_bool raw_output, bool isfilename
490 ) /* {{{ */ {
491 zend_string *digest;
492 unsigned char *K;
493 const php_hash_ops *ops;
494 void *context;
495 php_stream *stream = NULL;
496
497 ops = php_hash_fetch_ops(algo);
498 if (!ops || !ops->is_crypto) {
499 zend_argument_value_error(1, "must be a valid cryptographic hashing algorithm");
500 RETURN_THROWS();
501 }
502
503 if (isfilename) {
504 if (CHECK_NULL_PATH(data, data_len)) {
505 zend_argument_value_error(2, "must not contain any null bytes");
506 RETURN_THROWS();
507 }
508 stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, FG(default_context));
509 if (!stream) {
510 /* Stream will report errors opening file */
511 RETURN_FALSE;
512 }
513 }
514
515 context = php_hash_alloc_context(ops);
516
517 K = emalloc(ops->block_size);
518 digest = zend_string_alloc(ops->digest_size, 0);
519
520 php_hash_hmac_prep_key(K, ops, context, (unsigned char *) key, key_len);
521
522 if (isfilename) {
523 char buf[1024];
524 ssize_t n;
525 ops->hash_init(context);
526 ops->hash_update(context, K, ops->block_size);
527 while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
528 ops->hash_update(context, (unsigned char *) buf, n);
529 }
530 php_stream_close(stream);
531 if (n < 0) {
532 efree(context);
533 efree(K);
534 zend_string_release(digest);
535 RETURN_FALSE;
536 }
537
538 ops->hash_final((unsigned char *) ZSTR_VAL(digest), context);
539 } else {
540 php_hash_hmac_round((unsigned char *) ZSTR_VAL(digest), ops, context, K, (unsigned char *) data, data_len);
541 }
542
543 php_hash_string_xor_char(K, K, 0x6A, ops->block_size);
544
545 php_hash_hmac_round((unsigned char *) ZSTR_VAL(digest), ops, context, K, (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
546
547 /* Zero the key */
548 ZEND_SECURE_ZERO(K, ops->block_size);
549 efree(K);
550 efree(context);
551
552 if (raw_output) {
553 ZSTR_VAL(digest)[ops->digest_size] = 0;
554 RETURN_NEW_STR(digest);
555 } else {
556 zend_string *hex_digest = zend_string_safe_alloc(ops->digest_size, 2, 0, 0);
557
558 php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
559 ZSTR_VAL(hex_digest)[2 * ops->digest_size] = 0;
560 zend_string_release_ex(digest, 0);
561 RETURN_NEW_STR(hex_digest);
562 }
563 }
564 /* }}} */
565
566 /* {{{ Generate a hash of a given input string with a key using HMAC
567 Returns lowercase hexits by default */
PHP_FUNCTION(hash_hmac)568 PHP_FUNCTION(hash_hmac)
569 {
570 zend_string *algo;
571 char *data, *key;
572 size_t data_len, key_len;
573 zend_bool raw_output = 0;
574
575 if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sss|b", &algo, &data, &data_len, &key, &key_len, &raw_output) == FAILURE) {
576 RETURN_THROWS();
577 }
578
579 php_hash_do_hash_hmac(return_value, algo, data, data_len, key, key_len, raw_output, 0);
580 }
581 /* }}} */
582
583 /* {{{ Generate a hash of a given file with a key using HMAC
584 Returns lowercase hexits by default */
PHP_FUNCTION(hash_hmac_file)585 PHP_FUNCTION(hash_hmac_file)
586 {
587 zend_string *algo;
588 char *data, *key;
589 size_t data_len, key_len;
590 zend_bool raw_output = 0;
591
592 if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sss|b", &algo, &data, &data_len, &key, &key_len, &raw_output) == FAILURE) {
593 RETURN_THROWS();
594 }
595
596 php_hash_do_hash_hmac(return_value, algo, data, data_len, key, key_len, raw_output, 1);
597 }
598 /* }}} */
599
600 /* {{{ Initialize a hashing context */
PHP_FUNCTION(hash_init)601 PHP_FUNCTION(hash_init)
602 {
603 zend_string *algo, *key = NULL;
604 zend_long options = 0;
605 void *context;
606 const php_hash_ops *ops;
607 php_hashcontext_object *hash;
608
609 if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|lS", &algo, &options, &key) == FAILURE) {
610 RETURN_THROWS();
611 }
612
613 ops = php_hash_fetch_ops(algo);
614 if (!ops) {
615 zend_argument_value_error(1, "must be a valid hashing algorithm");
616 RETURN_THROWS();
617 }
618
619 if (options & PHP_HASH_HMAC) {
620 if (!ops->is_crypto) {
621 zend_argument_value_error(1, "must be a cryptographic hashing algorithm if HMAC is requested");
622 RETURN_THROWS();
623 }
624 if (!key || (ZSTR_LEN(key) == 0)) {
625 /* Note: a zero length key is no key at all */
626 zend_argument_value_error(3, "cannot be empty when HMAC is requested");
627 RETURN_THROWS();
628 }
629 }
630
631 object_init_ex(return_value, php_hashcontext_ce);
632 hash = php_hashcontext_from_object(Z_OBJ_P(return_value));
633
634 context = php_hash_alloc_context(ops);
635 ops->hash_init(context);
636
637 hash->ops = ops;
638 hash->context = context;
639 hash->options = options;
640 hash->key = NULL;
641
642 if (options & PHP_HASH_HMAC) {
643 char *K = emalloc(ops->block_size);
644 size_t i, block_size;
645
646 memset(K, 0, ops->block_size);
647
648 if (ZSTR_LEN(key) > ops->block_size) {
649 /* Reduce the key first */
650 ops->hash_update(context, (unsigned char *) ZSTR_VAL(key), ZSTR_LEN(key));
651 ops->hash_final((unsigned char *) K, context);
652 /* Make the context ready to start over */
653 ops->hash_init(context);
654 } else {
655 memcpy(K, ZSTR_VAL(key), ZSTR_LEN(key));
656 }
657
658 /* XOR ipad */
659 block_size = ops->block_size;
660 for(i = 0; i < block_size; i++) {
661 K[i] ^= 0x36;
662 }
663 ops->hash_update(context, (unsigned char *) K, ops->block_size);
664 hash->key = (unsigned char *) K;
665 }
666 }
667 /* }}} */
668
669 #define PHP_HASHCONTEXT_VERIFY(hash) { \
670 if (!hash->context) { \
671 zend_argument_type_error(1, "must be a valid Hash Context resource"); \
672 RETURN_THROWS(); \
673 } \
674 }
675
676 /* {{{ Pump data into the hashing algorithm */
PHP_FUNCTION(hash_update)677 PHP_FUNCTION(hash_update)
678 {
679 zval *zhash;
680 php_hashcontext_object *hash;
681 zend_string *data;
682
683 if (zend_parse_parameters(ZEND_NUM_ARGS(), "OS", &zhash, php_hashcontext_ce, &data) == FAILURE) {
684 RETURN_THROWS();
685 }
686
687 hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
688 PHP_HASHCONTEXT_VERIFY(hash);
689 hash->ops->hash_update(hash->context, (unsigned char *) ZSTR_VAL(data), ZSTR_LEN(data));
690
691 RETURN_TRUE;
692 }
693 /* }}} */
694
695 /* {{{ Pump data into the hashing algorithm from an open stream */
PHP_FUNCTION(hash_update_stream)696 PHP_FUNCTION(hash_update_stream)
697 {
698 zval *zhash, *zstream;
699 php_hashcontext_object *hash;
700 php_stream *stream = NULL;
701 zend_long length = -1, didread = 0;
702
703 if (zend_parse_parameters(ZEND_NUM_ARGS(), "Or|l", &zhash, php_hashcontext_ce, &zstream, &length) == FAILURE) {
704 RETURN_THROWS();
705 }
706
707 hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
708 PHP_HASHCONTEXT_VERIFY(hash);
709 php_stream_from_zval(stream, zstream);
710
711 while (length) {
712 char buf[1024];
713 zend_long toread = 1024;
714 ssize_t n;
715
716 if (length > 0 && toread > length) {
717 toread = length;
718 }
719
720 if ((n = php_stream_read(stream, buf, toread)) <= 0) {
721 RETURN_LONG(didread);
722 }
723 hash->ops->hash_update(hash->context, (unsigned char *) buf, n);
724 length -= n;
725 didread += n;
726 }
727
728 RETURN_LONG(didread);
729 }
730 /* }}} */
731
732 /* {{{ Pump data into the hashing algorithm from a file */
PHP_FUNCTION(hash_update_file)733 PHP_FUNCTION(hash_update_file)
734 {
735 zval *zhash, *zcontext = NULL;
736 php_hashcontext_object *hash;
737 php_stream_context *context = NULL;
738 php_stream *stream;
739 zend_string *filename;
740 char buf[1024];
741 ssize_t n;
742
743 if (zend_parse_parameters(ZEND_NUM_ARGS(), "OP|r!", &zhash, php_hashcontext_ce, &filename, &zcontext) == FAILURE) {
744 RETURN_THROWS();
745 }
746
747 hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
748 PHP_HASHCONTEXT_VERIFY(hash);
749 context = php_stream_context_from_zval(zcontext, 0);
750
751 stream = php_stream_open_wrapper_ex(ZSTR_VAL(filename), "rb", REPORT_ERRORS, NULL, context);
752 if (!stream) {
753 /* Stream will report errors opening file */
754 RETURN_FALSE;
755 }
756
757 while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
758 hash->ops->hash_update(hash->context, (unsigned char *) buf, n);
759 }
760 php_stream_close(stream);
761
762 RETURN_BOOL(n >= 0);
763 }
764 /* }}} */
765
766 /* {{{ Output resulting digest */
PHP_FUNCTION(hash_final)767 PHP_FUNCTION(hash_final)
768 {
769 zval *zhash;
770 php_hashcontext_object *hash;
771 zend_bool raw_output = 0;
772 zend_string *digest;
773 size_t digest_len;
774
775 if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|b", &zhash, php_hashcontext_ce, &raw_output) == FAILURE) {
776 RETURN_THROWS();
777 }
778
779 hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
780 PHP_HASHCONTEXT_VERIFY(hash);
781
782 digest_len = hash->ops->digest_size;
783 digest = zend_string_alloc(digest_len, 0);
784 hash->ops->hash_final((unsigned char *) ZSTR_VAL(digest), hash->context);
785 if (hash->options & PHP_HASH_HMAC) {
786 size_t i, block_size;
787
788 /* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
789 block_size = hash->ops->block_size;
790 for(i = 0; i < block_size; i++) {
791 hash->key[i] ^= 0x6A;
792 }
793
794 /* Feed this result into the outer hash */
795 hash->ops->hash_init(hash->context);
796 hash->ops->hash_update(hash->context, hash->key, hash->ops->block_size);
797 hash->ops->hash_update(hash->context, (unsigned char *) ZSTR_VAL(digest), hash->ops->digest_size);
798 hash->ops->hash_final((unsigned char *) ZSTR_VAL(digest), hash->context);
799
800 /* Zero the key */
801 ZEND_SECURE_ZERO(hash->key, hash->ops->block_size);
802 efree(hash->key);
803 hash->key = NULL;
804 }
805 ZSTR_VAL(digest)[digest_len] = 0;
806
807 /* Invalidate the object from further use */
808 efree(hash->context);
809 hash->context = NULL;
810
811 if (raw_output) {
812 RETURN_NEW_STR(digest);
813 } else {
814 zend_string *hex_digest = zend_string_safe_alloc(digest_len, 2, 0, 0);
815
816 php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), digest_len);
817 ZSTR_VAL(hex_digest)[2 * digest_len] = 0;
818 zend_string_release_ex(digest, 0);
819 RETURN_NEW_STR(hex_digest);
820 }
821 }
822 /* }}} */
823
824 /* {{{ Copy hash object */
PHP_FUNCTION(hash_copy)825 PHP_FUNCTION(hash_copy)
826 {
827 zval *zhash;
828
829 if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &zhash, php_hashcontext_ce) == FAILURE) {
830 RETURN_THROWS();
831 }
832
833 RETVAL_OBJ(Z_OBJ_HANDLER_P(zhash, clone_obj)(Z_OBJ_P(zhash)));
834
835 if (php_hashcontext_from_object(Z_OBJ_P(return_value))->context == NULL) {
836 zval_ptr_dtor(return_value);
837
838 zend_throw_error(NULL, "Cannot copy hash");
839 RETURN_THROWS();
840 }
841 }
842 /* }}} */
843
844 /* {{{ Return a list of registered hashing algorithms */
PHP_FUNCTION(hash_algos)845 PHP_FUNCTION(hash_algos)
846 {
847 zend_string *str;
848
849 if (zend_parse_parameters_none() == FAILURE) {
850 RETURN_THROWS();
851 }
852
853 array_init(return_value);
854 ZEND_HASH_FOREACH_STR_KEY(&php_hash_hashtable, str) {
855 add_next_index_str(return_value, zend_string_copy(str));
856 } ZEND_HASH_FOREACH_END();
857 }
858 /* }}} */
859
860 /* {{{ Return a list of registered hashing algorithms suitable for hash_hmac() */
PHP_FUNCTION(hash_hmac_algos)861 PHP_FUNCTION(hash_hmac_algos)
862 {
863 zend_string *str;
864 const php_hash_ops *ops;
865
866 if (zend_parse_parameters_none() == FAILURE) {
867 RETURN_THROWS();
868 }
869
870 array_init(return_value);
871 ZEND_HASH_FOREACH_STR_KEY_PTR(&php_hash_hashtable, str, ops) {
872 if (ops->is_crypto) {
873 add_next_index_str(return_value, zend_string_copy(str));
874 }
875 } ZEND_HASH_FOREACH_END();
876 }
877 /* }}} */
878
879 /* {{{ RFC5869 HMAC-based key derivation function */
PHP_FUNCTION(hash_hkdf)880 PHP_FUNCTION(hash_hkdf)
881 {
882 zend_string *returnval, *ikm, *algo, *info = NULL, *salt = NULL;
883 zend_long length = 0;
884 unsigned char *prk, *digest, *K;
885 size_t i;
886 size_t rounds;
887 const php_hash_ops *ops;
888 void *context;
889
890 if (zend_parse_parameters(ZEND_NUM_ARGS(), "SS|lSS", &algo, &ikm, &length, &info, &salt) == FAILURE) {
891 RETURN_THROWS();
892 }
893
894 ops = php_hash_fetch_ops(algo);
895 if (!ops || !ops->is_crypto) {
896 zend_argument_value_error(1, "must be a valid cryptographic hashing algorithm");
897 RETURN_THROWS();
898 }
899
900 if (ZSTR_LEN(ikm) == 0) {
901 zend_argument_value_error(2, "cannot be empty");
902 RETURN_THROWS();
903 }
904
905 if (length < 0) {
906 zend_argument_value_error(3, "must be greater than or equal to 0");
907 RETURN_THROWS();
908 } else if (length == 0) {
909 length = ops->digest_size;
910 } else if (length > (zend_long) (ops->digest_size * 255)) {
911 zend_argument_value_error(3, "must be less than or equal to %zd", ops->digest_size * 255);
912 RETURN_THROWS();
913 }
914
915 context = php_hash_alloc_context(ops);
916
917 // Extract
918 ops->hash_init(context);
919 K = emalloc(ops->block_size);
920 php_hash_hmac_prep_key(K, ops, context,
921 (unsigned char *) (salt ? ZSTR_VAL(salt) : ""), salt ? ZSTR_LEN(salt) : 0);
922
923 prk = emalloc(ops->digest_size);
924 php_hash_hmac_round(prk, ops, context, K, (unsigned char *) ZSTR_VAL(ikm), ZSTR_LEN(ikm));
925 php_hash_string_xor_char(K, K, 0x6A, ops->block_size);
926 php_hash_hmac_round(prk, ops, context, K, prk, ops->digest_size);
927 ZEND_SECURE_ZERO(K, ops->block_size);
928
929 // Expand
930 returnval = zend_string_alloc(length, 0);
931 digest = emalloc(ops->digest_size);
932 for (i = 1, rounds = (length - 1) / ops->digest_size + 1; i <= rounds; i++) {
933 // chr(i)
934 unsigned char c[1];
935 c[0] = (i & 0xFF);
936
937 php_hash_hmac_prep_key(K, ops, context, prk, ops->digest_size);
938 ops->hash_init(context);
939 ops->hash_update(context, K, ops->block_size);
940
941 if (i > 1) {
942 ops->hash_update(context, digest, ops->digest_size);
943 }
944
945 if (info != NULL && ZSTR_LEN(info) > 0) {
946 ops->hash_update(context, (unsigned char *) ZSTR_VAL(info), ZSTR_LEN(info));
947 }
948
949 ops->hash_update(context, c, 1);
950 ops->hash_final(digest, context);
951 php_hash_string_xor_char(K, K, 0x6A, ops->block_size);
952 php_hash_hmac_round(digest, ops, context, K, digest, ops->digest_size);
953 memcpy(
954 ZSTR_VAL(returnval) + ((i - 1) * ops->digest_size),
955 digest,
956 (i == rounds ? length - ((i - 1) * ops->digest_size) : ops->digest_size)
957 );
958 }
959
960 ZEND_SECURE_ZERO(K, ops->block_size);
961 ZEND_SECURE_ZERO(digest, ops->digest_size);
962 ZEND_SECURE_ZERO(prk, ops->digest_size);
963 efree(K);
964 efree(context);
965 efree(prk);
966 efree(digest);
967 ZSTR_VAL(returnval)[length] = 0;
968 RETURN_STR(returnval);
969 }
970
971 /* {{{ Generate a PBKDF2 hash of the given password and salt
972 Returns lowercase hexits by default */
PHP_FUNCTION(hash_pbkdf2)973 PHP_FUNCTION(hash_pbkdf2)
974 {
975 zend_string *returnval, *algo;
976 char *salt, *pass = NULL;
977 unsigned char *computed_salt, *digest, *temp, *result, *K1, *K2 = NULL;
978 zend_long loops, i, j, iterations, digest_length = 0, length = 0;
979 size_t pass_len, salt_len = 0;
980 zend_bool raw_output = 0;
981 const php_hash_ops *ops;
982 void *context;
983
984 if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sssl|lb", &algo, &pass, &pass_len, &salt, &salt_len, &iterations, &length, &raw_output) == FAILURE) {
985 RETURN_THROWS();
986 }
987
988 ops = php_hash_fetch_ops(algo);
989 if (!ops || !ops->is_crypto) {
990 zend_argument_value_error(1, "must be a valid cryptographic hashing algorithm");
991 RETURN_THROWS();
992 }
993
994 if (salt_len > INT_MAX - 4) {
995 zend_argument_value_error(3, "must be less than or equal to INT_MAX - 4 bytes");
996 RETURN_THROWS();
997 }
998
999 if (iterations <= 0) {
1000 zend_argument_value_error(4, "must be greater than 0");
1001 RETURN_THROWS();
1002 }
1003
1004 if (length < 0) {
1005 zend_argument_value_error(5, "must be greater than or equal to 0");
1006 RETURN_THROWS();
1007 }
1008
1009 context = php_hash_alloc_context(ops);
1010 ops->hash_init(context);
1011
1012 K1 = emalloc(ops->block_size);
1013 K2 = emalloc(ops->block_size);
1014 digest = emalloc(ops->digest_size);
1015 temp = emalloc(ops->digest_size);
1016
1017 /* Setup Keys that will be used for all hmac rounds */
1018 php_hash_hmac_prep_key(K1, ops, context, (unsigned char *) pass, pass_len);
1019 /* Convert K1 to opad -- 0x6A = 0x36 ^ 0x5C */
1020 php_hash_string_xor_char(K2, K1, 0x6A, ops->block_size);
1021
1022 /* Setup Main Loop to build a long enough result */
1023 if (length == 0) {
1024 length = ops->digest_size;
1025 if (!raw_output) {
1026 length = length * 2;
1027 }
1028 }
1029 digest_length = length;
1030 if (!raw_output) {
1031 digest_length = (zend_long) ceil((float) length / 2.0);
1032 }
1033
1034 loops = (zend_long) ceil((float) digest_length / (float) ops->digest_size);
1035
1036 result = safe_emalloc(loops, ops->digest_size, 0);
1037
1038 computed_salt = safe_emalloc(salt_len, 1, 4);
1039 memcpy(computed_salt, (unsigned char *) salt, salt_len);
1040
1041 for (i = 1; i <= loops; i++) {
1042 /* digest = hash_hmac(salt + pack('N', i), password) { */
1043
1044 /* pack("N", i) */
1045 computed_salt[salt_len] = (unsigned char) (i >> 24);
1046 computed_salt[salt_len + 1] = (unsigned char) ((i & 0xFF0000) >> 16);
1047 computed_salt[salt_len + 2] = (unsigned char) ((i & 0xFF00) >> 8);
1048 computed_salt[salt_len + 3] = (unsigned char) (i & 0xFF);
1049
1050 php_hash_hmac_round(digest, ops, context, K1, computed_salt, (zend_long) salt_len + 4);
1051 php_hash_hmac_round(digest, ops, context, K2, digest, ops->digest_size);
1052 /* } */
1053
1054 /* temp = digest */
1055 memcpy(temp, digest, ops->digest_size);
1056
1057 /*
1058 * Note that the loop starting at 1 is intentional, since we've already done
1059 * the first round of the algorithm.
1060 */
1061 for (j = 1; j < iterations; j++) {
1062 /* digest = hash_hmac(digest, password) { */
1063 php_hash_hmac_round(digest, ops, context, K1, digest, ops->digest_size);
1064 php_hash_hmac_round(digest, ops, context, K2, digest, ops->digest_size);
1065 /* } */
1066 /* temp ^= digest */
1067 php_hash_string_xor(temp, temp, digest, ops->digest_size);
1068 }
1069 /* result += temp */
1070 memcpy(result + ((i - 1) * ops->digest_size), temp, ops->digest_size);
1071 }
1072 /* Zero potentially sensitive variables */
1073 ZEND_SECURE_ZERO(K1, ops->block_size);
1074 ZEND_SECURE_ZERO(K2, ops->block_size);
1075 ZEND_SECURE_ZERO(computed_salt, salt_len + 4);
1076 efree(K1);
1077 efree(K2);
1078 efree(computed_salt);
1079 efree(context);
1080 efree(digest);
1081 efree(temp);
1082
1083 returnval = zend_string_alloc(length, 0);
1084 if (raw_output) {
1085 memcpy(ZSTR_VAL(returnval), result, length);
1086 } else {
1087 php_hash_bin2hex(ZSTR_VAL(returnval), result, digest_length);
1088 }
1089 ZSTR_VAL(returnval)[length] = 0;
1090 efree(result);
1091 RETURN_NEW_STR(returnval);
1092 }
1093 /* }}} */
1094
1095 /* {{{ Compares two strings using the same time whether they're equal or not.
1096 A difference in length will leak */
PHP_FUNCTION(hash_equals)1097 PHP_FUNCTION(hash_equals)
1098 {
1099 zval *known_zval, *user_zval;
1100 char *known_str, *user_str;
1101 int result = 0;
1102 size_t j;
1103
1104 if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &known_zval, &user_zval) == FAILURE) {
1105 RETURN_THROWS();
1106 }
1107
1108 /* We only allow comparing string to prevent unexpected results. */
1109 if (Z_TYPE_P(known_zval) != IS_STRING) {
1110 zend_argument_type_error(1, "must be of type string, %s given", zend_zval_type_name(known_zval));
1111 RETURN_THROWS();
1112 }
1113
1114 if (Z_TYPE_P(user_zval) != IS_STRING) {
1115 zend_argument_type_error(2, "must be of type string, %s given", zend_zval_type_name(user_zval));
1116 RETURN_THROWS();
1117 }
1118
1119 if (Z_STRLEN_P(known_zval) != Z_STRLEN_P(user_zval)) {
1120 RETURN_FALSE;
1121 }
1122
1123 known_str = Z_STRVAL_P(known_zval);
1124 user_str = Z_STRVAL_P(user_zval);
1125
1126 /* This is security sensitive code. Do not optimize this for speed. */
1127 for (j = 0; j < Z_STRLEN_P(known_zval); j++) {
1128 result |= known_str[j] ^ user_str[j];
1129 }
1130
1131 RETURN_BOOL(0 == result);
1132 }
1133 /* }}} */
1134
1135 /* {{{ */
PHP_METHOD(HashContext,__construct)1136 PHP_METHOD(HashContext, __construct) {
1137 /* Normally unreachable as private/final */
1138 zend_throw_exception(zend_ce_error, "Illegal call to private/final constructor", 0);
1139 }
1140 /* }}} */
1141
1142 /* Module Housekeeping */
1143
1144 #define PHP_HASH_HAVAL_REGISTER(p,b) php_hash_register_algo("haval" #b "," #p , &php_hash_##p##haval##b##_ops);
1145
1146 #ifdef PHP_MHASH_BC
1147
1148 #if 0
1149 /* See #69823, we should not insert module into module_registry while doing startup */
1150
1151 PHP_MINFO_FUNCTION(mhash)
1152 {
1153 php_info_print_table_start();
1154 php_info_print_table_row(2, "MHASH support", "Enabled");
1155 php_info_print_table_row(2, "MHASH API Version", "Emulated Support");
1156 php_info_print_table_end();
1157 }
1158
1159 zend_module_entry mhash_module_entry = {
1160 STANDARD_MODULE_HEADER,
1161 "mhash",
1162 NULL,
1163 NULL,
1164 NULL,
1165 NULL,
1166 NULL,
1167 PHP_MINFO(mhash),
1168 PHP_MHASH_VERSION,
1169 STANDARD_MODULE_PROPERTIES,
1170 };
1171 #endif
1172
mhash_init(INIT_FUNC_ARGS)1173 static void mhash_init(INIT_FUNC_ARGS)
1174 {
1175 char buf[128];
1176 int len;
1177 int algo_number = 0;
1178
1179 for (algo_number = 0; algo_number < MHASH_NUM_ALGOS; algo_number++) {
1180 struct mhash_bc_entry algorithm = mhash_to_hash[algo_number];
1181 if (algorithm.mhash_name == NULL) {
1182 continue;
1183 }
1184
1185 len = slprintf(buf, 127, "MHASH_%s", algorithm.mhash_name);
1186 zend_register_long_constant(buf, len, algorithm.value, CONST_CS | CONST_PERSISTENT, module_number);
1187 }
1188
1189 /* TODO: this cause #69823 zend_register_internal_module(&mhash_module_entry); */
1190 }
1191
1192 /* {{{ Hash data with hash */
PHP_FUNCTION(mhash)1193 PHP_FUNCTION(mhash)
1194 {
1195 zend_long algorithm;
1196 zend_string *algo = NULL;
1197 char *data, *key = NULL;
1198 size_t data_len, key_len = 0;
1199
1200 if (zend_parse_parameters(ZEND_NUM_ARGS(), "ls|s!", &algorithm, &data, &data_len, &key, &key_len) == FAILURE) {
1201 RETURN_THROWS();
1202 }
1203
1204 /* need to convert the first parameter from int constant to string algorithm name */
1205 if (algorithm >= 0 && algorithm < MHASH_NUM_ALGOS) {
1206 struct mhash_bc_entry algorithm_lookup = mhash_to_hash[algorithm];
1207 if (algorithm_lookup.hash_name) {
1208 algo = zend_string_init(algorithm_lookup.hash_name, strlen(algorithm_lookup.hash_name), 0);
1209 }
1210 }
1211
1212 if (key) {
1213 php_hash_do_hash_hmac(return_value, algo, data, data_len, key, key_len, 1, 0);
1214 } else {
1215 php_hash_do_hash(return_value, algo, data, data_len, 1, 0);
1216 }
1217
1218 if (algo) {
1219 zend_string_release(algo);
1220 }
1221 }
1222 /* }}} */
1223
1224 /* {{{ Gets the name of hash */
PHP_FUNCTION(mhash_get_hash_name)1225 PHP_FUNCTION(mhash_get_hash_name)
1226 {
1227 zend_long algorithm;
1228
1229 if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &algorithm) == FAILURE) {
1230 RETURN_THROWS();
1231 }
1232
1233 if (algorithm >= 0 && algorithm < MHASH_NUM_ALGOS) {
1234 struct mhash_bc_entry algorithm_lookup = mhash_to_hash[algorithm];
1235 if (algorithm_lookup.mhash_name) {
1236 RETURN_STRING(algorithm_lookup.mhash_name);
1237 }
1238 }
1239 RETURN_FALSE;
1240 }
1241 /* }}} */
1242
1243 /* {{{ Gets the number of available hashes */
PHP_FUNCTION(mhash_count)1244 PHP_FUNCTION(mhash_count)
1245 {
1246 if (zend_parse_parameters_none() == FAILURE) {
1247 RETURN_THROWS();
1248 }
1249 RETURN_LONG(MHASH_NUM_ALGOS - 1);
1250 }
1251 /* }}} */
1252
1253 /* {{{ Gets the block size of hash */
PHP_FUNCTION(mhash_get_block_size)1254 PHP_FUNCTION(mhash_get_block_size)
1255 {
1256 zend_long algorithm;
1257
1258 if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &algorithm) == FAILURE) {
1259 RETURN_THROWS();
1260 }
1261 RETVAL_FALSE;
1262
1263 if (algorithm >= 0 && algorithm < MHASH_NUM_ALGOS) {
1264 struct mhash_bc_entry algorithm_lookup = mhash_to_hash[algorithm];
1265 if (algorithm_lookup.mhash_name) {
1266 const php_hash_ops *ops = zend_hash_str_find_ptr(&php_hash_hashtable, algorithm_lookup.hash_name, strlen(algorithm_lookup.hash_name));
1267 if (ops) {
1268 RETVAL_LONG(ops->digest_size);
1269 }
1270 }
1271 }
1272 }
1273 /* }}} */
1274
1275 #define SALT_SIZE 8
1276
1277 /* {{{ Generates a key using hash functions */
PHP_FUNCTION(mhash_keygen_s2k)1278 PHP_FUNCTION(mhash_keygen_s2k)
1279 {
1280 zend_long algorithm, l_bytes;
1281 int bytes;
1282 char *password, *salt;
1283 size_t password_len, salt_len;
1284 char padded_salt[SALT_SIZE];
1285
1286 if (zend_parse_parameters(ZEND_NUM_ARGS(), "lssl", &algorithm, &password, &password_len, &salt, &salt_len, &l_bytes) == FAILURE) {
1287 RETURN_THROWS();
1288 }
1289
1290 bytes = (int)l_bytes;
1291 if (bytes <= 0){
1292 zend_argument_value_error(4, "must be a greater than 0");
1293 RETURN_THROWS();
1294 }
1295
1296 salt_len = MIN(salt_len, SALT_SIZE);
1297
1298 memcpy(padded_salt, salt, salt_len);
1299 if (salt_len < SALT_SIZE) {
1300 memset(padded_salt + salt_len, 0, SALT_SIZE - salt_len);
1301 }
1302 salt_len = SALT_SIZE;
1303
1304 RETVAL_FALSE;
1305 if (algorithm >= 0 && algorithm < MHASH_NUM_ALGOS) {
1306 struct mhash_bc_entry algorithm_lookup = mhash_to_hash[algorithm];
1307 if (algorithm_lookup.mhash_name) {
1308 const php_hash_ops *ops = zend_hash_str_find_ptr(&php_hash_hashtable, algorithm_lookup.hash_name, strlen(algorithm_lookup.hash_name));
1309 if (ops) {
1310 unsigned char null = '\0';
1311 void *context;
1312 char *key, *digest;
1313 int i = 0, j = 0;
1314 size_t block_size = ops->digest_size;
1315 size_t times = bytes / block_size;
1316
1317 if ((bytes % block_size) != 0) {
1318 times++;
1319 }
1320
1321 context = php_hash_alloc_context(ops);
1322 ops->hash_init(context);
1323
1324 key = ecalloc(1, times * block_size);
1325 digest = emalloc(ops->digest_size + 1);
1326
1327 for (i = 0; i < times; i++) {
1328 ops->hash_init(context);
1329
1330 for (j=0;j<i;j++) {
1331 ops->hash_update(context, &null, 1);
1332 }
1333 ops->hash_update(context, (unsigned char *)padded_salt, salt_len);
1334 ops->hash_update(context, (unsigned char *)password, password_len);
1335 ops->hash_final((unsigned char *)digest, context);
1336 memcpy( &key[i*block_size], digest, block_size);
1337 }
1338
1339 RETVAL_STRINGL(key, bytes);
1340 ZEND_SECURE_ZERO(key, bytes);
1341 efree(digest);
1342 efree(context);
1343 efree(key);
1344 }
1345 }
1346 }
1347 }
1348 /* }}} */
1349
1350 #endif
1351
1352 /* ----------------------------------------------------------------------- */
1353
1354 /* {{{ php_hashcontext_create */
php_hashcontext_create(zend_class_entry * ce)1355 static zend_object* php_hashcontext_create(zend_class_entry *ce) {
1356 php_hashcontext_object *objval = zend_object_alloc(sizeof(php_hashcontext_object), ce);
1357 zend_object *zobj = &objval->std;
1358
1359 zend_object_std_init(zobj, ce);
1360 object_properties_init(zobj, ce);
1361 zobj->handlers = &php_hashcontext_handlers;
1362
1363 return zobj;
1364 }
1365 /* }}} */
1366
1367 /* {{{ php_hashcontext_dtor */
php_hashcontext_dtor(zend_object * obj)1368 static void php_hashcontext_dtor(zend_object *obj) {
1369 php_hashcontext_object *hash = php_hashcontext_from_object(obj);
1370
1371 if (hash->context) {
1372 efree(hash->context);
1373 hash->context = NULL;
1374 }
1375
1376 if (hash->key) {
1377 ZEND_SECURE_ZERO(hash->key, hash->ops->block_size);
1378 efree(hash->key);
1379 hash->key = NULL;
1380 }
1381 }
1382 /* }}} */
1383
1384 /* {{{ php_hashcontext_clone */
php_hashcontext_clone(zend_object * zobj)1385 static zend_object *php_hashcontext_clone(zend_object *zobj) {
1386 php_hashcontext_object *oldobj = php_hashcontext_from_object(zobj);
1387 zend_object *znew = php_hashcontext_create(zobj->ce);
1388 php_hashcontext_object *newobj = php_hashcontext_from_object(znew);
1389
1390 zend_objects_clone_members(znew, zobj);
1391
1392 newobj->ops = oldobj->ops;
1393 newobj->options = oldobj->options;
1394 newobj->context = php_hash_alloc_context(newobj->ops);
1395 newobj->ops->hash_init(newobj->context);
1396
1397 if (SUCCESS != newobj->ops->hash_copy(newobj->ops, oldobj->context, newobj->context)) {
1398 efree(newobj->context);
1399 newobj->context = NULL;
1400 return znew;
1401 }
1402
1403 newobj->key = ecalloc(1, newobj->ops->block_size);
1404 if (oldobj->key) {
1405 memcpy(newobj->key, oldobj->key, newobj->ops->block_size);
1406 }
1407
1408 return znew;
1409 }
1410 /* }}} */
1411
1412 /* Serialization format: 5-element array
1413 Index 0: hash algorithm (string)
1414 Index 1: options (long, 0)
1415 Index 2: hash-determined serialization of context state (usually array)
1416 Index 3: magic number defining layout of context state (long, usually 2)
1417 Index 4: properties (array)
1418
1419 HashContext serializations are not necessarily portable between architectures or
1420 PHP versions. If the format of a serialized hash context changes, that should
1421 be reflected in either a different value of `magic` or a different format of
1422 the serialized context state. Most context states are unparsed and parsed using
1423 a spec string, such as "llb128.", using the format defined by
1424 `php_hash_serialize_spec`/`php_hash_unserialize_spec`. Some hash algorithms must
1425 also check the unserialized state for validity, to ensure that using an
1426 unserialized context is safe from memory errors.
1427
1428 Currently HASH_HMAC contexts cannot be serialized, because serializing them
1429 would require serializing the HMAC key in plaintext. */
1430
1431 /* {{{ Serialize the object */
PHP_METHOD(HashContext,__serialize)1432 PHP_METHOD(HashContext, __serialize)
1433 {
1434 zval *object = ZEND_THIS;
1435 php_hashcontext_object *hash = php_hashcontext_from_object(Z_OBJ_P(object));
1436 zend_long magic = 0;
1437 zval tmp;
1438
1439 if (zend_parse_parameters_none() == FAILURE) {
1440 RETURN_THROWS();
1441 }
1442
1443 array_init(return_value);
1444
1445 if (!hash->ops->hash_serialize) {
1446 goto serialize_failure;
1447 } else if (hash->options & PHP_HASH_HMAC) {
1448 zend_throw_exception(NULL, "HashContext with HASH_HMAC option cannot be serialized", 0);
1449 RETURN_THROWS();
1450 }
1451
1452 ZVAL_STRING(&tmp, hash->ops->algo);
1453 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
1454
1455 ZVAL_LONG(&tmp, hash->options);
1456 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
1457
1458 if (hash->ops->hash_serialize(hash, &magic, &tmp) != SUCCESS) {
1459 goto serialize_failure;
1460 }
1461 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
1462
1463 ZVAL_LONG(&tmp, magic);
1464 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
1465
1466 /* members */
1467 ZVAL_ARR(&tmp, zend_std_get_properties(&hash->std));
1468 Z_TRY_ADDREF(tmp);
1469 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
1470
1471 return;
1472
1473 serialize_failure:
1474 zend_throw_exception_ex(NULL, 0, "HashContext for algorithm \"%s\" cannot be serialized", hash->ops->algo);
1475 RETURN_THROWS();
1476 }
1477 /* }}} */
1478
1479 /* {{{ unserialize the object */
PHP_METHOD(HashContext,__unserialize)1480 PHP_METHOD(HashContext, __unserialize)
1481 {
1482 zval *object = ZEND_THIS;
1483 php_hashcontext_object *hash = php_hashcontext_from_object(Z_OBJ_P(object));
1484 HashTable *data;
1485 zval *algo_zv, *magic_zv, *options_zv, *hash_zv, *members_zv;
1486 zend_long magic, options;
1487 int unserialize_result;
1488 const php_hash_ops *ops;
1489
1490 if (zend_parse_parameters(ZEND_NUM_ARGS(), "h", &data) == FAILURE) {
1491 RETURN_THROWS();
1492 }
1493
1494 if (hash->context) {
1495 zend_throw_exception(NULL, "HashContext::__unserialize called on initialized object", 0);
1496 RETURN_THROWS();
1497 }
1498
1499 algo_zv = zend_hash_index_find(data, 0);
1500 options_zv = zend_hash_index_find(data, 1);
1501 hash_zv = zend_hash_index_find(data, 2);
1502 magic_zv = zend_hash_index_find(data, 3);
1503 members_zv = zend_hash_index_find(data, 4);
1504
1505 if (!algo_zv || Z_TYPE_P(algo_zv) != IS_STRING
1506 || !magic_zv || Z_TYPE_P(magic_zv) != IS_LONG
1507 || !options_zv || Z_TYPE_P(options_zv) != IS_LONG
1508 || !hash_zv
1509 || !members_zv || Z_TYPE_P(members_zv) != IS_ARRAY) {
1510 zend_throw_exception(NULL, "Incomplete or ill-formed serialization data", 0);
1511 RETURN_THROWS();
1512 }
1513
1514 magic = Z_LVAL_P(magic_zv);
1515 options = Z_LVAL_P(options_zv);
1516 if (options & PHP_HASH_HMAC) {
1517 zend_throw_exception(NULL, "HashContext with HASH_HMAC option cannot be serialized", 0);
1518 RETURN_THROWS();
1519 }
1520
1521 ops = php_hash_fetch_ops(Z_STR_P(algo_zv));
1522 if (!ops) {
1523 zend_throw_exception(NULL, "Unknown hash algorithm", 0);
1524 RETURN_THROWS();
1525 } else if (!ops->hash_unserialize) {
1526 zend_throw_exception_ex(NULL, 0, "Hash algorithm \"%s\" cannot be unserialized", ops->algo);
1527 RETURN_THROWS();
1528 }
1529
1530 hash->ops = ops;
1531 hash->context = php_hash_alloc_context(ops);
1532 ops->hash_init(hash->context);
1533 hash->options = options;
1534
1535 unserialize_result = ops->hash_unserialize(hash, magic, hash_zv);
1536 if (unserialize_result != SUCCESS) {
1537 zend_throw_exception_ex(NULL, 0, "Incomplete or ill-formed serialization data (\"%s\" code %d)", ops->algo, unserialize_result);
1538 /* free context */
1539 php_hashcontext_dtor(Z_OBJ_P(object));
1540 RETURN_THROWS();
1541 }
1542
1543 object_properties_load(&hash->std, Z_ARRVAL_P(members_zv));
1544 }
1545 /* }}} */
1546
1547 /* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(hash)1548 PHP_MINIT_FUNCTION(hash)
1549 {
1550 zend_class_entry ce;
1551
1552 zend_hash_init(&php_hash_hashtable, 35, NULL, NULL, 1);
1553
1554 php_hash_register_algo("md2", &php_hash_md2_ops);
1555 php_hash_register_algo("md4", &php_hash_md4_ops);
1556 php_hash_register_algo("md5", &php_hash_md5_ops);
1557 php_hash_register_algo("sha1", &php_hash_sha1_ops);
1558 php_hash_register_algo("sha224", &php_hash_sha224_ops);
1559 php_hash_register_algo("sha256", &php_hash_sha256_ops);
1560 php_hash_register_algo("sha384", &php_hash_sha384_ops);
1561 php_hash_register_algo("sha512/224", &php_hash_sha512_224_ops);
1562 php_hash_register_algo("sha512/256", &php_hash_sha512_256_ops);
1563 php_hash_register_algo("sha512", &php_hash_sha512_ops);
1564 php_hash_register_algo("sha3-224", &php_hash_sha3_224_ops);
1565 php_hash_register_algo("sha3-256", &php_hash_sha3_256_ops);
1566 php_hash_register_algo("sha3-384", &php_hash_sha3_384_ops);
1567 php_hash_register_algo("sha3-512", &php_hash_sha3_512_ops);
1568 php_hash_register_algo("ripemd128", &php_hash_ripemd128_ops);
1569 php_hash_register_algo("ripemd160", &php_hash_ripemd160_ops);
1570 php_hash_register_algo("ripemd256", &php_hash_ripemd256_ops);
1571 php_hash_register_algo("ripemd320", &php_hash_ripemd320_ops);
1572 php_hash_register_algo("whirlpool", &php_hash_whirlpool_ops);
1573 php_hash_register_algo("tiger128,3", &php_hash_3tiger128_ops);
1574 php_hash_register_algo("tiger160,3", &php_hash_3tiger160_ops);
1575 php_hash_register_algo("tiger192,3", &php_hash_3tiger192_ops);
1576 php_hash_register_algo("tiger128,4", &php_hash_4tiger128_ops);
1577 php_hash_register_algo("tiger160,4", &php_hash_4tiger160_ops);
1578 php_hash_register_algo("tiger192,4", &php_hash_4tiger192_ops);
1579 php_hash_register_algo("snefru", &php_hash_snefru_ops);
1580 php_hash_register_algo("snefru256", &php_hash_snefru_ops);
1581 php_hash_register_algo("gost", &php_hash_gost_ops);
1582 php_hash_register_algo("gost-crypto", &php_hash_gost_crypto_ops);
1583 php_hash_register_algo("adler32", &php_hash_adler32_ops);
1584 php_hash_register_algo("crc32", &php_hash_crc32_ops);
1585 php_hash_register_algo("crc32b", &php_hash_crc32b_ops);
1586 php_hash_register_algo("crc32c", &php_hash_crc32c_ops);
1587 php_hash_register_algo("fnv132", &php_hash_fnv132_ops);
1588 php_hash_register_algo("fnv1a32", &php_hash_fnv1a32_ops);
1589 php_hash_register_algo("fnv164", &php_hash_fnv164_ops);
1590 php_hash_register_algo("fnv1a64", &php_hash_fnv1a64_ops);
1591 php_hash_register_algo("joaat", &php_hash_joaat_ops);
1592
1593 PHP_HASH_HAVAL_REGISTER(3,128);
1594 PHP_HASH_HAVAL_REGISTER(3,160);
1595 PHP_HASH_HAVAL_REGISTER(3,192);
1596 PHP_HASH_HAVAL_REGISTER(3,224);
1597 PHP_HASH_HAVAL_REGISTER(3,256);
1598
1599 PHP_HASH_HAVAL_REGISTER(4,128);
1600 PHP_HASH_HAVAL_REGISTER(4,160);
1601 PHP_HASH_HAVAL_REGISTER(4,192);
1602 PHP_HASH_HAVAL_REGISTER(4,224);
1603 PHP_HASH_HAVAL_REGISTER(4,256);
1604
1605 PHP_HASH_HAVAL_REGISTER(5,128);
1606 PHP_HASH_HAVAL_REGISTER(5,160);
1607 PHP_HASH_HAVAL_REGISTER(5,192);
1608 PHP_HASH_HAVAL_REGISTER(5,224);
1609 PHP_HASH_HAVAL_REGISTER(5,256);
1610
1611 REGISTER_LONG_CONSTANT("HASH_HMAC", PHP_HASH_HMAC, CONST_CS | CONST_PERSISTENT);
1612
1613 INIT_CLASS_ENTRY(ce, "HashContext", class_HashContext_methods);
1614 php_hashcontext_ce = zend_register_internal_class(&ce);
1615 php_hashcontext_ce->ce_flags |= ZEND_ACC_FINAL;
1616 php_hashcontext_ce->create_object = php_hashcontext_create;
1617
1618 memcpy(&php_hashcontext_handlers, &std_object_handlers,
1619 sizeof(zend_object_handlers));
1620 php_hashcontext_handlers.offset = XtOffsetOf(php_hashcontext_object, std);
1621 php_hashcontext_handlers.dtor_obj = php_hashcontext_dtor;
1622 php_hashcontext_handlers.clone_obj = php_hashcontext_clone;
1623
1624 #ifdef PHP_MHASH_BC
1625 mhash_init(INIT_FUNC_ARGS_PASSTHRU);
1626 #endif
1627
1628 return SUCCESS;
1629 }
1630 /* }}} */
1631
1632 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(hash)1633 PHP_MSHUTDOWN_FUNCTION(hash)
1634 {
1635 zend_hash_destroy(&php_hash_hashtable);
1636
1637 return SUCCESS;
1638 }
1639 /* }}} */
1640
1641 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(hash)1642 PHP_MINFO_FUNCTION(hash)
1643 {
1644 char buffer[2048];
1645 zend_string *str;
1646 char *s = buffer, *e = s + sizeof(buffer);
1647
1648 ZEND_HASH_FOREACH_STR_KEY(&php_hash_hashtable, str) {
1649 s += slprintf(s, e - s, "%s ", ZSTR_VAL(str));
1650 } ZEND_HASH_FOREACH_END();
1651 *s = 0;
1652
1653 php_info_print_table_start();
1654 php_info_print_table_row(2, "hash support", "enabled");
1655 php_info_print_table_row(2, "Hashing Engines", buffer);
1656 php_info_print_table_end();
1657
1658 #ifdef PHP_MHASH_BC
1659 php_info_print_table_start();
1660 php_info_print_table_row(2, "MHASH support", "Enabled");
1661 php_info_print_table_row(2, "MHASH API Version", "Emulated Support");
1662 php_info_print_table_end();
1663 #endif
1664
1665 }
1666 /* }}} */
1667
1668 /* {{{ hash_module_entry */
1669 zend_module_entry hash_module_entry = {
1670 STANDARD_MODULE_HEADER,
1671 PHP_HASH_EXTNAME,
1672 ext_functions,
1673 PHP_MINIT(hash),
1674 PHP_MSHUTDOWN(hash),
1675 NULL, /* RINIT */
1676 NULL, /* RSHUTDOWN */
1677 PHP_MINFO(hash),
1678 PHP_HASH_VERSION,
1679 STANDARD_MODULE_PROPERTIES
1680 };
1681 /* }}} */
1682