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