-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
Copy pathhash.c
1719 lines (1465 loc) · 48.5 KB
/
hash.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sara Golemon <[email protected]> |
| Scott MacVicar <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <math.h>
#include "php_hash.h"
#include "ext/standard/info.h"
#include "ext/standard/file.h"
#include "ext/standard/php_var.h"
#include "zend_attributes.h"
#include "zend_exceptions.h"
#include "zend_interfaces.h"
#include "zend_smart_str.h"
#include "hash_arginfo.h"
#ifdef PHP_WIN32
# define __alignof__ __alignof
#else
# ifndef HAVE_ALIGNOF
# include <stddef.h>
# define __alignof__(type) offsetof (struct { char c; type member;}, member)
# endif
#endif
static HashTable php_hash_hashtable;
zend_class_entry *php_hashcontext_ce;
static zend_object_handlers php_hashcontext_handlers;
#ifdef PHP_MHASH_BC
struct mhash_bc_entry {
char *mhash_name;
char *hash_name;
int value;
};
#define MHASH_NUM_ALGOS 42
static struct mhash_bc_entry mhash_to_hash[MHASH_NUM_ALGOS] = {
{"CRC32", "crc32", 0}, /* used by bzip */
{"MD5", "md5", 1},
{"SHA1", "sha1", 2},
{"HAVAL256", "haval256,3", 3},
{NULL, NULL, 4},
{"RIPEMD160", "ripemd160", 5},
{NULL, NULL, 6},
{"TIGER", "tiger192,3", 7},
{"GOST", "gost", 8},
{"CRC32B", "crc32b", 9}, /* used by ethernet (IEEE 802.3), gzip, zip, png, etc */
{"HAVAL224", "haval224,3", 10},
{"HAVAL192", "haval192,3", 11},
{"HAVAL160", "haval160,3", 12},
{"HAVAL128", "haval128,3", 13},
{"TIGER128", "tiger128,3", 14},
{"TIGER160", "tiger160,3", 15},
{"MD4", "md4", 16},
{"SHA256", "sha256", 17},
{"ADLER32", "adler32", 18},
{"SHA224", "sha224", 19},
{"SHA512", "sha512", 20},
{"SHA384", "sha384", 21},
{"WHIRLPOOL", "whirlpool", 22},
{"RIPEMD128", "ripemd128", 23},
{"RIPEMD256", "ripemd256", 24},
{"RIPEMD320", "ripemd320", 25},
{NULL, NULL, 26}, /* support needs to be added for snefru 128 */
{"SNEFRU256", "snefru256", 27},
{"MD2", "md2", 28},
{"FNV132", "fnv132", 29},
{"FNV1A32", "fnv1a32", 30},
{"FNV164", "fnv164", 31},
{"FNV1A64", "fnv1a64", 32},
{"JOAAT", "joaat", 33},
{"CRC32C", "crc32c", 34}, /* Castagnoli's CRC, used by iSCSI, SCTP, Btrfs, ext4, etc */
{"MURMUR3A", "murmur3a", 35},
{"MURMUR3C", "murmur3c", 36},
{"MURMUR3F", "murmur3f", 37},
{"XXH32", "xxh32", 38},
{"XXH64", "xxh64", 39},
{"XXH3", "xxh3", 40},
{"XXH128", "xxh128", 41},
};
#endif
/* Hash Registry Access */
PHP_HASH_API const php_hash_ops *php_hash_fetch_ops(zend_string *algo) /* {{{ */
{
zend_string *lower = zend_string_tolower(algo);
const php_hash_ops *ops = zend_hash_find_ptr(&php_hash_hashtable, lower);
zend_string_release(lower);
return ops;
}
/* }}} */
PHP_HASH_API void php_hash_register_algo(const char *algo, const php_hash_ops *ops) /* {{{ */
{
size_t algo_len = strlen(algo);
char *lower = zend_str_tolower_dup(algo, algo_len);
zend_hash_add_ptr(&php_hash_hashtable, zend_string_init_interned(lower, algo_len, 1), (void *) ops);
efree(lower);
}
/* }}} */
PHP_HASH_API zend_result php_hash_copy(const void *ops, const void *orig_context, void *dest_context) /* {{{ */
{
php_hash_ops *hash_ops = (php_hash_ops *)ops;
memcpy(dest_context, orig_context, hash_ops->context_size);
return SUCCESS;
}
/* }}} */
static inline size_t align_to(size_t pos, size_t alignment) {
size_t offset = pos & (alignment - 1);
return pos + (offset ? alignment - offset : 0);
}
static size_t parse_serialize_spec(
const char **specp, size_t *pos, size_t *sz, size_t *max_alignment) {
size_t count, alignment;
const char *spec = *specp;
/* parse size */
if (*spec == 's' || *spec == 'S') {
*sz = 2;
alignment = __alignof__(uint16_t); /* usually 2 */
} else if (*spec == 'l' || *spec == 'L') {
*sz = 4;
alignment = __alignof__(uint32_t); /* usually 4 */
} else if (*spec == 'q' || *spec == 'Q') {
*sz = 8;
alignment = __alignof__(uint64_t); /* usually 8 */
} else if (*spec == 'i' || *spec == 'I') {
*sz = sizeof(int);
alignment = __alignof__(int); /* usually 4 */
} else {
ZEND_ASSERT(*spec == 'b' || *spec == 'B');
*sz = 1;
alignment = 1;
}
/* process alignment */
*pos = align_to(*pos, alignment);
*max_alignment = *max_alignment < alignment ? alignment : *max_alignment;
/* parse count */
++spec;
if (isdigit((unsigned char) *spec)) {
count = 0;
while (isdigit((unsigned char) *spec)) {
count = 10 * count + *spec - '0';
++spec;
}
} else {
count = 1;
}
*specp = spec;
return count;
}
static uint64_t one_from_buffer(size_t sz, const unsigned char *buf) {
if (sz == 2) {
const uint16_t *x = (const uint16_t *) buf;
return *x;
} else if (sz == 4) {
const uint32_t *x = (const uint32_t *) buf;
return *x;
} else if (sz == 8) {
const uint64_t *x = (const uint64_t *) buf;
return *x;
} else {
ZEND_ASSERT(sz == 1);
return *buf;
}
}
static void one_to_buffer(size_t sz, unsigned char *buf, uint64_t val) {
if (sz == 2) {
uint16_t *x = (uint16_t *) buf;
*x = val;
} else if (sz == 4) {
uint32_t *x = (uint32_t *) buf;
*x = val;
} else if (sz == 8) {
uint64_t *x = (uint64_t *) buf;
*x = val;
} else {
ZEND_ASSERT(sz == 1);
*buf = val;
}
}
/* Serialize a hash context according to a `spec` string.
Spec contents:
b[COUNT] -- serialize COUNT bytes
s[COUNT] -- serialize COUNT 16-bit integers
l[COUNT] -- serialize COUNT 32-bit integers
q[COUNT] -- serialize COUNT 64-bit integers
i[COUNT] -- serialize COUNT `int`s
B[COUNT] -- skip COUNT bytes
S[COUNT], L[COUNT], etc. -- uppercase versions skip instead of read
. (must be last character) -- assert that the hash context has exactly
this size
Example: "llllllb64l16." is the spec for an MD5 context: 6 32-bit
integers, followed by 64 bytes, then 16 32-bit integers, and that's
exactly the size of the context.
The serialization result is an array. Each integer is serialized as a
32-bit integer, except that a run of 2 or more bytes is encoded as a
string, and each 64-bit integer is serialized as two 32-bit integers, least
significant bits first. This allows 32-bit and 64-bit architectures to
interchange serialized HashContexts. */
PHP_HASH_API zend_result php_hash_serialize_spec(const php_hashcontext_object *hash, zval *zv, const char *spec) /* {{{ */
{
size_t pos = 0, max_alignment = 1;
unsigned char *buf = (unsigned char *) hash->context;
zval tmp;
if (buf == NULL) {
return FAILURE;
}
array_init(zv);
while (*spec != '\0' && *spec != '.') {
char spec_ch = *spec;
size_t sz, count = parse_serialize_spec(&spec, &pos, &sz, &max_alignment);
if (pos + count * sz > hash->ops->context_size) {
return FAILURE;
}
if (isupper((unsigned char) spec_ch)) {
pos += count * sz;
} else if (sz == 1 && count > 1) {
ZVAL_STRINGL(&tmp, (char *) buf + pos, count);
zend_hash_next_index_insert(Z_ARRVAL_P(zv), &tmp);
pos += count;
} else {
while (count > 0) {
uint64_t val = one_from_buffer(sz, buf + pos);
pos += sz;
ZVAL_LONG(&tmp, (int32_t) val);
zend_hash_next_index_insert(Z_ARRVAL_P(zv), &tmp);
if (sz == 8) {
ZVAL_LONG(&tmp, (int32_t) (val >> 32));
zend_hash_next_index_insert(Z_ARRVAL_P(zv), &tmp);
}
--count;
}
}
}
if (*spec == '.' && align_to(pos, max_alignment) != hash->ops->context_size) {
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* Unserialize a hash context serialized by `php_hash_serialize_spec` with `spec`.
Returns SUCCESS on success and a negative error code on failure.
Codes: FAILURE (-1) == generic failure
-999 == spec wrong size for context
-1000 - POS == problem at byte offset POS */
PHP_HASH_API int php_hash_unserialize_spec(php_hashcontext_object *hash, const zval *zv, const char *spec) /* {{{ */
{
size_t pos = 0, max_alignment = 1, j = 0;
unsigned char *buf = (unsigned char *) hash->context;
zval *elt;
if (Z_TYPE_P(zv) != IS_ARRAY) {
return FAILURE;
}
while (*spec != '\0' && *spec != '.') {
char spec_ch = *spec;
size_t sz, count = parse_serialize_spec(&spec, &pos, &sz, &max_alignment);
if (pos + count * sz > hash->ops->context_size) {
return -999;
}
if (isupper((unsigned char) spec_ch)) {
pos += count * sz;
} else if (sz == 1 && count > 1) {
elt = zend_hash_index_find(Z_ARRVAL_P(zv), j);
if (!elt || Z_TYPE_P(elt) != IS_STRING || Z_STRLEN_P(elt) != count) {
return -1000 - pos;
}
++j;
memcpy(buf + pos, Z_STRVAL_P(elt), count);
pos += count;
} else {
while (count > 0) {
uint64_t val;
elt = zend_hash_index_find(Z_ARRVAL_P(zv), j);
if (!elt || Z_TYPE_P(elt) != IS_LONG) {
return -1000 - pos;
}
++j;
val = (uint32_t) Z_LVAL_P(elt);
if (sz == 8) {
elt = zend_hash_index_find(Z_ARRVAL_P(zv), j);
if (!elt || Z_TYPE_P(elt) != IS_LONG) {
return -1000 - pos;
}
++j;
val += ((uint64_t) Z_LVAL_P(elt)) << 32;
}
one_to_buffer(sz, buf + pos, val);
pos += sz;
--count;
}
}
}
if (*spec == '.' && align_to(pos, max_alignment) != hash->ops->context_size) {
return -999;
}
return SUCCESS;
}
/* }}} */
PHP_HASH_API zend_result php_hash_serialize(const php_hashcontext_object *hash, zend_long *magic, zval *zv) /* {{{ */
{
if (hash->ops->serialize_spec) {
*magic = PHP_HASH_SERIALIZE_MAGIC_SPEC;
return php_hash_serialize_spec(hash, zv, hash->ops->serialize_spec);
} else {
return FAILURE;
}
}
/* }}} */
PHP_HASH_API int php_hash_unserialize(php_hashcontext_object *hash, zend_long magic, const zval *zv) /* {{{ */
{
if (hash->ops->serialize_spec
&& magic == PHP_HASH_SERIALIZE_MAGIC_SPEC) {
return php_hash_unserialize_spec(hash, zv, hash->ops->serialize_spec);
} else {
return FAILURE;
}
}
/* }}} */
/* Userspace */
static void php_hash_do_hash(
zval *return_value, zend_string *algo, char *data, size_t data_len, bool raw_output, bool isfilename, HashTable *args
) /* {{{ */ {
zend_string *digest;
const php_hash_ops *ops;
void *context;
php_stream *stream = NULL;
ops = php_hash_fetch_ops(algo);
if (!ops) {
zend_argument_value_error(1, "must be a valid hashing algorithm");
RETURN_THROWS();
}
if (isfilename) {
if (CHECK_NULL_PATH(data, data_len)) {
zend_argument_value_error(1, "must not contain any null bytes");
RETURN_THROWS();
}
stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, FG(default_context));
if (!stream) {
/* Stream will report errors opening file */
RETURN_FALSE;
}
}
context = php_hash_alloc_context(ops);
ops->hash_init(context, args);
if (isfilename) {
char buf[1024];
ssize_t n;
while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
ops->hash_update(context, (unsigned char *) buf, n);
}
php_stream_close(stream);
if (n < 0) {
efree(context);
RETURN_FALSE;
}
} else {
ops->hash_update(context, (unsigned char *) data, data_len);
}
digest = zend_string_alloc(ops->digest_size, 0);
ops->hash_final((unsigned char *) ZSTR_VAL(digest), context);
efree(context);
if (raw_output) {
ZSTR_VAL(digest)[ops->digest_size] = 0;
RETURN_NEW_STR(digest);
} else {
zend_string *hex_digest = zend_string_safe_alloc(ops->digest_size, 2, 0, 0);
php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
ZSTR_VAL(hex_digest)[2 * ops->digest_size] = 0;
zend_string_release_ex(digest, 0);
RETURN_NEW_STR(hex_digest);
}
}
/* }}} */
/* {{{ Generate a hash of a given input string
Returns lowercase hexits by default */
PHP_FUNCTION(hash)
{
zend_string *algo;
char *data;
size_t data_len;
bool raw_output = 0;
HashTable *args = NULL;
ZEND_PARSE_PARAMETERS_START(2, 4)
Z_PARAM_STR(algo)
Z_PARAM_STRING(data, data_len)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(raw_output)
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
php_hash_do_hash(return_value, algo, data, data_len, raw_output, 0, args);
}
/* }}} */
/* {{{ Generate a hash of a given file
Returns lowercase hexits by default */
PHP_FUNCTION(hash_file)
{
zend_string *algo;
char *data;
size_t data_len;
bool raw_output = 0;
HashTable *args = NULL;
ZEND_PARSE_PARAMETERS_START(2, 4)
Z_PARAM_STR(algo)
Z_PARAM_STRING(data, data_len)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(raw_output)
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
php_hash_do_hash(return_value, algo, data, data_len, raw_output, 1, args);
}
/* }}} */
static inline void php_hash_string_xor_char(unsigned char *out, const unsigned char *in, const unsigned char xor_with, const size_t length) {
size_t i;
for (i=0; i < length; i++) {
out[i] = in[i] ^ xor_with;
}
}
static inline void php_hash_string_xor(unsigned char *out, const unsigned char *in, const unsigned char *xor_with, const size_t length) {
size_t i;
for (i=0; i < length; i++) {
out[i] = in[i] ^ xor_with[i];
}
}
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) {
memset(K, 0, ops->block_size);
if (key_len > ops->block_size) {
/* Reduce the key first */
ops->hash_init(context, NULL);
ops->hash_update(context, key, key_len);
ops->hash_final(K, context);
} else {
memcpy(K, key, key_len);
}
/* XOR the key with 0x36 to get the ipad) */
php_hash_string_xor_char(K, K, 0x36, ops->block_size);
}
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) {
ops->hash_init(context, NULL);
ops->hash_update(context, key, ops->block_size);
ops->hash_update(context, data, data_size);
ops->hash_final(final, context);
}
static void 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
) /* {{{ */ {
zend_string *digest;
unsigned char *K;
const php_hash_ops *ops;
void *context;
php_stream *stream = NULL;
ops = php_hash_fetch_ops(algo);
if (!ops || !ops->is_crypto) {
zend_argument_value_error(1, "must be a valid cryptographic hashing algorithm");
RETURN_THROWS();
}
if (isfilename) {
if (CHECK_NULL_PATH(data, data_len)) {
zend_argument_value_error(2, "must not contain any null bytes");
RETURN_THROWS();
}
stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, FG(default_context));
if (!stream) {
/* Stream will report errors opening file */
RETURN_FALSE;
}
}
context = php_hash_alloc_context(ops);
K = emalloc(ops->block_size);
digest = zend_string_alloc(ops->digest_size, 0);
php_hash_hmac_prep_key(K, ops, context, (unsigned char *) key, key_len);
if (isfilename) {
char buf[1024];
ssize_t n;
ops->hash_init(context, NULL);
ops->hash_update(context, K, ops->block_size);
while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
ops->hash_update(context, (unsigned char *) buf, n);
}
php_stream_close(stream);
if (n < 0) {
efree(context);
efree(K);
zend_string_release(digest);
RETURN_FALSE;
}
ops->hash_final((unsigned char *) ZSTR_VAL(digest), context);
} else {
php_hash_hmac_round((unsigned char *) ZSTR_VAL(digest), ops, context, K, (unsigned char *) data, data_len);
}
php_hash_string_xor_char(K, K, 0x6A, ops->block_size);
php_hash_hmac_round((unsigned char *) ZSTR_VAL(digest), ops, context, K, (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
/* Zero the key */
ZEND_SECURE_ZERO(K, ops->block_size);
efree(K);
efree(context);
if (raw_output) {
ZSTR_VAL(digest)[ops->digest_size] = 0;
RETURN_NEW_STR(digest);
} else {
zend_string *hex_digest = zend_string_safe_alloc(ops->digest_size, 2, 0, 0);
php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
ZSTR_VAL(hex_digest)[2 * ops->digest_size] = 0;
zend_string_release_ex(digest, 0);
RETURN_NEW_STR(hex_digest);
}
}
/* }}} */
/* {{{ Generate a hash of a given input string with a key using HMAC
Returns lowercase hexits by default */
PHP_FUNCTION(hash_hmac)
{
zend_string *algo;
char *data, *key;
size_t data_len, key_len;
bool raw_output = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sss|b", &algo, &data, &data_len, &key, &key_len, &raw_output) == FAILURE) {
RETURN_THROWS();
}
php_hash_do_hash_hmac(return_value, algo, data, data_len, key, key_len, raw_output, 0);
}
/* }}} */
/* {{{ Generate a hash of a given file with a key using HMAC
Returns lowercase hexits by default */
PHP_FUNCTION(hash_hmac_file)
{
zend_string *algo;
char *data, *key;
size_t data_len, key_len;
bool raw_output = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sss|b", &algo, &data, &data_len, &key, &key_len, &raw_output) == FAILURE) {
RETURN_THROWS();
}
php_hash_do_hash_hmac(return_value, algo, data, data_len, key, key_len, raw_output, 1);
}
/* }}} */
/* {{{ Initialize a hashing context */
PHP_FUNCTION(hash_init)
{
zend_string *algo, *key = NULL;
zend_long options = 0;
void *context;
const php_hash_ops *ops;
php_hashcontext_object *hash;
HashTable *args = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|lSh", &algo, &options, &key, &args) == FAILURE) {
RETURN_THROWS();
}
ops = php_hash_fetch_ops(algo);
if (!ops) {
zend_argument_value_error(1, "must be a valid hashing algorithm");
RETURN_THROWS();
}
if (options & PHP_HASH_HMAC) {
if (!ops->is_crypto) {
zend_argument_value_error(1, "must be a cryptographic hashing algorithm if HMAC is requested");
RETURN_THROWS();
}
if (!key || (ZSTR_LEN(key) == 0)) {
/* Note: a zero length key is no key at all */
zend_argument_value_error(3, "must not be empty when HMAC is requested");
RETURN_THROWS();
}
}
object_init_ex(return_value, php_hashcontext_ce);
hash = php_hashcontext_from_object(Z_OBJ_P(return_value));
context = php_hash_alloc_context(ops);
ops->hash_init(context, args);
hash->ops = ops;
hash->context = context;
hash->options = options;
hash->key = NULL;
if (options & PHP_HASH_HMAC) {
char *K = emalloc(ops->block_size);
size_t i, block_size;
memset(K, 0, ops->block_size);
if (ZSTR_LEN(key) > ops->block_size) {
/* Reduce the key first */
ops->hash_update(context, (unsigned char *) ZSTR_VAL(key), ZSTR_LEN(key));
ops->hash_final((unsigned char *) K, context);
/* Make the context ready to start over */
ops->hash_init(context, args);
} else {
memcpy(K, ZSTR_VAL(key), ZSTR_LEN(key));
}
/* XOR ipad */
block_size = ops->block_size;
for(i = 0; i < block_size; i++) {
K[i] ^= 0x36;
}
ops->hash_update(context, (unsigned char *) K, ops->block_size);
hash->key = (unsigned char *) K;
}
}
/* }}} */
#define PHP_HASHCONTEXT_VERIFY(hash) { \
if (!hash->context) { \
zend_argument_type_error(1, "must be a valid, non-finalized HashContext"); \
RETURN_THROWS(); \
} \
}
/* {{{ Pump data into the hashing algorithm */
PHP_FUNCTION(hash_update)
{
zval *zhash;
php_hashcontext_object *hash;
zend_string *data;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "OS", &zhash, php_hashcontext_ce, &data) == FAILURE) {
RETURN_THROWS();
}
hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
PHP_HASHCONTEXT_VERIFY(hash);
hash->ops->hash_update(hash->context, (unsigned char *) ZSTR_VAL(data), ZSTR_LEN(data));
RETURN_TRUE;
}
/* }}} */
/* {{{ Pump data into the hashing algorithm from an open stream */
PHP_FUNCTION(hash_update_stream)
{
zval *zhash, *zstream;
php_hashcontext_object *hash;
php_stream *stream = NULL;
zend_long length = -1, didread = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "Or|l", &zhash, php_hashcontext_ce, &zstream, &length) == FAILURE) {
RETURN_THROWS();
}
hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
PHP_HASHCONTEXT_VERIFY(hash);
php_stream_from_zval(stream, zstream);
while (length) {
char buf[1024];
zend_long toread = 1024;
ssize_t n;
if (length > 0 && toread > length) {
toread = length;
}
if ((n = php_stream_read(stream, buf, toread)) <= 0) {
RETURN_LONG(didread);
}
hash->ops->hash_update(hash->context, (unsigned char *) buf, n);
length -= n;
didread += n;
}
RETURN_LONG(didread);
}
/* }}} */
/* {{{ Pump data into the hashing algorithm from a file */
PHP_FUNCTION(hash_update_file)
{
zval *zhash, *zcontext = NULL;
php_hashcontext_object *hash;
php_stream_context *context = NULL;
php_stream *stream;
zend_string *filename;
char buf[1024];
ssize_t n;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "OP|r!", &zhash, php_hashcontext_ce, &filename, &zcontext) == FAILURE) {
RETURN_THROWS();
}
hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
PHP_HASHCONTEXT_VERIFY(hash);
context = php_stream_context_from_zval(zcontext, 0);
stream = php_stream_open_wrapper_ex(ZSTR_VAL(filename), "rb", REPORT_ERRORS, NULL, context);
if (!stream) {
/* Stream will report errors opening file */
RETURN_FALSE;
}
while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
hash->ops->hash_update(hash->context, (unsigned char *) buf, n);
}
php_stream_close(stream);
RETURN_BOOL(n >= 0);
}
/* }}} */
/* {{{ Output resulting digest */
PHP_FUNCTION(hash_final)
{
zval *zhash;
php_hashcontext_object *hash;
bool raw_output = 0;
zend_string *digest;
size_t digest_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|b", &zhash, php_hashcontext_ce, &raw_output) == FAILURE) {
RETURN_THROWS();
}
hash = php_hashcontext_from_object(Z_OBJ_P(zhash));
PHP_HASHCONTEXT_VERIFY(hash);
digest_len = hash->ops->digest_size;
digest = zend_string_alloc(digest_len, 0);
hash->ops->hash_final((unsigned char *) ZSTR_VAL(digest), hash->context);
if (hash->options & PHP_HASH_HMAC) {
size_t i, block_size;
/* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
block_size = hash->ops->block_size;
for(i = 0; i < block_size; i++) {
hash->key[i] ^= 0x6A;
}
/* Feed this result into the outer hash */
hash->ops->hash_init(hash->context, NULL);
hash->ops->hash_update(hash->context, hash->key, hash->ops->block_size);
hash->ops->hash_update(hash->context, (unsigned char *) ZSTR_VAL(digest), hash->ops->digest_size);
hash->ops->hash_final((unsigned char *) ZSTR_VAL(digest), hash->context);
/* Zero the key */
ZEND_SECURE_ZERO(hash->key, hash->ops->block_size);
efree(hash->key);
hash->key = NULL;
}
ZSTR_VAL(digest)[digest_len] = 0;
/* Invalidate the object from further use */
efree(hash->context);
hash->context = NULL;
if (raw_output) {
RETURN_NEW_STR(digest);
} else {
zend_string *hex_digest = zend_string_safe_alloc(digest_len, 2, 0, 0);
php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), digest_len);
ZSTR_VAL(hex_digest)[2 * digest_len] = 0;
zend_string_release_ex(digest, 0);
RETURN_NEW_STR(hex_digest);
}
}
/* }}} */
/* {{{ Copy hash object */
PHP_FUNCTION(hash_copy)
{
zval *zhash;
php_hashcontext_object *context;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &zhash, php_hashcontext_ce) == FAILURE) {
RETURN_THROWS();
}
context = php_hashcontext_from_object(Z_OBJ_P(zhash));
PHP_HASHCONTEXT_VERIFY(context);
RETVAL_OBJ(Z_OBJ_HANDLER_P(zhash, clone_obj)(Z_OBJ_P(zhash)));
if (php_hashcontext_from_object(Z_OBJ_P(return_value))->context == NULL) {
zval_ptr_dtor(return_value);
zend_throw_error(NULL, "Cannot copy hash");
RETURN_THROWS();
}
}
/* }}} */
/* {{{ Return a list of registered hashing algorithms */
PHP_FUNCTION(hash_algos)
{
zend_string *str;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
array_init(return_value);
ZEND_HASH_MAP_FOREACH_STR_KEY(&php_hash_hashtable, str) {
add_next_index_str(return_value, zend_string_copy(str));
} ZEND_HASH_FOREACH_END();
}
/* }}} */
/* {{{ Return a list of registered hashing algorithms suitable for hash_hmac() */
PHP_FUNCTION(hash_hmac_algos)
{
zend_string *str;
const php_hash_ops *ops;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
array_init(return_value);
ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&php_hash_hashtable, str, ops) {
if (ops->is_crypto) {
add_next_index_str(return_value, zend_string_copy(str));
}
} ZEND_HASH_FOREACH_END();
}
/* }}} */
/* {{{ RFC5869 HMAC-based key derivation function */
PHP_FUNCTION(hash_hkdf)
{
zend_string *returnval, *ikm, *algo, *info = NULL, *salt = NULL;
zend_long length = 0;
unsigned char *prk, *digest, *K;
size_t i;
size_t rounds;
const php_hash_ops *ops;
void *context;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "SS|lSS", &algo, &ikm, &length, &info, &salt) == FAILURE) {
RETURN_THROWS();
}
ops = php_hash_fetch_ops(algo);
if (!ops || !ops->is_crypto) {
zend_argument_value_error(1, "must be a valid cryptographic hashing algorithm");
RETURN_THROWS();
}
if (ZSTR_LEN(ikm) == 0) {
zend_argument_must_not_be_empty_error(2);
RETURN_THROWS();
}
if (length < 0) {
zend_argument_value_error(3, "must be greater than or equal to 0");
RETURN_THROWS();
} else if (length == 0) {
length = ops->digest_size;
} else if (length > (zend_long) (ops->digest_size * 255)) {
zend_argument_value_error(3, "must be less than or equal to %zd", ops->digest_size * 255);
RETURN_THROWS();
}
context = php_hash_alloc_context(ops);
// Extract
ops->hash_init(context, NULL);
K = emalloc(ops->block_size);
php_hash_hmac_prep_key(K, ops, context,
(unsigned char *) (salt ? ZSTR_VAL(salt) : ""), salt ? ZSTR_LEN(salt) : 0);
prk = emalloc(ops->digest_size);
php_hash_hmac_round(prk, ops, context, K, (unsigned char *) ZSTR_VAL(ikm), ZSTR_LEN(ikm));
php_hash_string_xor_char(K, K, 0x6A, ops->block_size);
php_hash_hmac_round(prk, ops, context, K, prk, ops->digest_size);
ZEND_SECURE_ZERO(K, ops->block_size);
// Expand
returnval = zend_string_alloc(length, 0);
digest = emalloc(ops->digest_size);
for (i = 1, rounds = (length - 1) / ops->digest_size + 1; i <= rounds; i++) {
// chr(i)
unsigned char c[1];
c[0] = (i & 0xFF);
php_hash_hmac_prep_key(K, ops, context, prk, ops->digest_size);
ops->hash_init(context, NULL);
ops->hash_update(context, K, ops->block_size);
if (i > 1) {
ops->hash_update(context, digest, ops->digest_size);
}
if (info != NULL && ZSTR_LEN(info) > 0) {
ops->hash_update(context, (unsigned char *) ZSTR_VAL(info), ZSTR_LEN(info));
}
ops->hash_update(context, c, 1);
ops->hash_final(digest, context);
php_hash_string_xor_char(K, K, 0x6A, ops->block_size);
php_hash_hmac_round(digest, ops, context, K, digest, ops->digest_size);
memcpy(
ZSTR_VAL(returnval) + ((i - 1) * ops->digest_size),
digest,
(i == rounds ? length - ((i - 1) * ops->digest_size) : ops->digest_size)
);
}
ZEND_SECURE_ZERO(K, ops->block_size);
ZEND_SECURE_ZERO(digest, ops->digest_size);
ZEND_SECURE_ZERO(prk, ops->digest_size);
efree(K);
efree(context);
efree(prk);
efree(digest);
ZSTR_VAL(returnval)[length] = 0;
RETURN_STR(returnval);
}
/* {{{ Generate a PBKDF2 hash of the given password and salt
Returns lowercase hexits by default */
PHP_FUNCTION(hash_pbkdf2)
{
zend_string *returnval, *algo;
char *salt, *pass = NULL;
unsigned char *computed_salt, *digest, *temp, *result, *K1, *K2 = NULL;
zend_long loops, i, j, iterations, digest_length = 0, length = 0;
size_t pass_len, salt_len = 0;
bool raw_output = 0;
const php_hash_ops *ops;
void *context;
HashTable *args = NULL;