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