-
-
Notifications
You must be signed in to change notification settings - Fork 34.2k
Expand file tree
/
Copy pathhmacmodule.c
More file actions
1714 lines (1495 loc) · 49.5 KB
/
hmacmodule.c
File metadata and controls
1714 lines (1495 loc) · 49.5 KB
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
/*
* @author Bénédikt Tran
*
* Implement the HMAC algorithm as described by RFC 2104 using HACL*.
*
* Using HACL* implementation implicitly assumes that the caller wants
* a formally verified implementation. In particular, only algorithms
* given by their names will be recognized.
*
* Some algorithms exposed by `_hashlib` such as truncated SHA-2-512-224/256
* are not yet implemented by the HACL* project. Nonetheless, the supported
* HMAC algorithms form a subset of those supported by '_hashlib'.
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include "pycore_hashtable.h"
#include "pycore_strhex.h" // _Py_strhex()
/*
* Taken from blake2module.c. In the future, detection of SIMD support
* should be delegated to https://github.com/python/cpython/pull/125011.
*/
#if defined(__x86_64__) && defined(__GNUC__)
# include <cpuid.h>
#elif defined(_M_X64)
# include <intrin.h>
#endif
#if defined(__APPLE__) && defined(__arm64__)
# undef _Py_HACL_CAN_COMPILE_VEC128
# undef _Py_HACL_CAN_COMPILE_VEC256
#endif
// HACL* expects HACL_CAN_COMPILE_VEC* macros to be set in order to enable
// the corresponding SIMD instructions so we need to "forward" the values
// we just deduced above.
#define HACL_CAN_COMPILE_VEC128 _Py_HACL_CAN_COMPILE_VEC128
#define HACL_CAN_COMPILE_VEC256 _Py_HACL_CAN_COMPILE_VEC256
#include "_hacl/Hacl_HMAC.h"
#include "_hacl/Hacl_Streaming_HMAC.h" // Hacl_Agile_Hash_* identifiers
#include "_hacl/Hacl_Streaming_Types.h" // Hacl_Streaming_Types_error_code
#include <stdbool.h>
#include "hashlib.h"
// --- Reusable error messages ------------------------------------------------
static inline void
set_invalid_key_length_error(void)
{
(void)PyErr_Format(PyExc_OverflowError,
"key length exceeds %u",
UINT32_MAX);
}
static inline void
set_invalid_msg_length_error(void)
{
(void)PyErr_Format(PyExc_OverflowError,
"message length exceeds %u",
UINT32_MAX);
}
// --- HMAC underlying hash function static information -----------------------
#define UINT32_MAX_AS_SSIZE_T ((Py_ssize_t)UINT32_MAX)
#define Py_hmac_hash_max_block_size 144
#define Py_hmac_hash_max_digest_size 64
/* MD-5 */
// HACL_HID = md5
#define Py_hmac_md5_block_size 64
#define Py_hmac_md5_digest_size 16
#define Py_hmac_md5_compute_func Hacl_HMAC_compute_md5
/* SHA-1 family */
// HACL_HID = sha1
#define Py_hmac_sha1_block_size 64
#define Py_hmac_sha1_digest_size 20
#define Py_hmac_sha1_compute_func Hacl_HMAC_compute_sha1
/* SHA-2 family */
// HACL_HID = sha2_224
#define Py_hmac_sha2_224_block_size 64
#define Py_hmac_sha2_224_digest_size 28
#define Py_hmac_sha2_224_compute_func Hacl_HMAC_compute_sha2_224
// HACL_HID = sha2_256
#define Py_hmac_sha2_256_block_size 64
#define Py_hmac_sha2_256_digest_size 32
#define Py_hmac_sha2_256_compute_func Hacl_HMAC_compute_sha2_256
// HACL_HID = sha2_384
#define Py_hmac_sha2_384_block_size 128
#define Py_hmac_sha2_384_digest_size 48
#define Py_hmac_sha2_384_compute_func Hacl_HMAC_compute_sha2_384
// HACL_HID = sha2_512
#define Py_hmac_sha2_512_block_size 128
#define Py_hmac_sha2_512_digest_size 64
#define Py_hmac_sha2_512_compute_func Hacl_HMAC_compute_sha2_512
/* SHA-3 family */
// HACL_HID = sha3_224
#define Py_hmac_sha3_224_block_size 144
#define Py_hmac_sha3_224_digest_size 28
#define Py_hmac_sha3_224_compute_func Hacl_HMAC_compute_sha3_224
// HACL_HID = sha3_256
#define Py_hmac_sha3_256_block_size 136
#define Py_hmac_sha3_256_digest_size 32
#define Py_hmac_sha3_256_compute_func Hacl_HMAC_compute_sha3_256
// HACL_HID = sha3_384
#define Py_hmac_sha3_384_block_size 104
#define Py_hmac_sha3_384_digest_size 48
#define Py_hmac_sha3_384_compute_func Hacl_HMAC_compute_sha3_384
// HACL_HID = sha3_512
#define Py_hmac_sha3_512_block_size 72
#define Py_hmac_sha3_512_digest_size 64
#define Py_hmac_sha3_512_compute_func Hacl_HMAC_compute_sha3_512
/* Blake2 family */
// HACL_HID = blake2s_32
#define Py_hmac_blake2s_32_block_size 64
#define Py_hmac_blake2s_32_digest_size 32
#define Py_hmac_blake2s_32_compute_func Hacl_HMAC_compute_blake2s_32
// HACL_HID = blake2b_32
#define Py_hmac_blake2b_32_block_size 128
#define Py_hmac_blake2b_32_digest_size 64
#define Py_hmac_blake2b_32_compute_func Hacl_HMAC_compute_blake2b_32
/* Enumeration indicating the underlying hash function used by HMAC. */
typedef enum HMAC_Hash_Kind {
Py_hmac_kind_hash_unknown = -1,
#define DECL_HACL_HMAC_HASH_KIND(NAME, HACL_NAME) \
Py_hmac_kind_hmac_ ## NAME = Hacl_Agile_Hash_ ## HACL_NAME,
/* MD5 */
DECL_HACL_HMAC_HASH_KIND(md5, MD5)
/* SHA-1 */
DECL_HACL_HMAC_HASH_KIND(sha1, SHA1)
/* SHA-2 family */
DECL_HACL_HMAC_HASH_KIND(sha2_224, SHA2_224)
DECL_HACL_HMAC_HASH_KIND(sha2_256, SHA2_256)
DECL_HACL_HMAC_HASH_KIND(sha2_384, SHA2_384)
DECL_HACL_HMAC_HASH_KIND(sha2_512, SHA2_512)
/* SHA-3 family */
DECL_HACL_HMAC_HASH_KIND(sha3_224, SHA3_224)
DECL_HACL_HMAC_HASH_KIND(sha3_256, SHA3_256)
DECL_HACL_HMAC_HASH_KIND(sha3_384, SHA3_384)
DECL_HACL_HMAC_HASH_KIND(sha3_512, SHA3_512)
/* Blake family */
DECL_HACL_HMAC_HASH_KIND(blake2s_32, Blake2S_32)
DECL_HACL_HMAC_HASH_KIND(blake2b_32, Blake2B_32)
/* Blake runtime family (should not be used statically) */
DECL_HACL_HMAC_HASH_KIND(vectorized_blake2s_32, Blake2S_128)
DECL_HACL_HMAC_HASH_KIND(vectorized_blake2b_32, Blake2B_256)
#undef DECL_HACL_HMAC_HASH_KIND
} HMAC_Hash_Kind;
typedef Hacl_Streaming_Types_error_code hacl_errno_t;
/* Function pointer type for 1-shot HACL* HMAC functions. */
typedef void
(*HACL_HMAC_compute_func)(uint8_t *out,
uint8_t *key, uint32_t keylen,
uint8_t *msg, uint32_t msglen);
/* Function pointer type for 1-shot HACL* HMAC CPython AC functions. */
typedef PyObject *
(*PyAC_HMAC_compute_func)(PyObject *module, PyObject *key, PyObject *msg);
/*
* HACL* HMAC minimal interface.
*/
typedef struct py_hmac_hacl_api {
HACL_HMAC_compute_func compute;
PyAC_HMAC_compute_func compute_py;
} py_hmac_hacl_api;
#if PY_SSIZE_T_MAX > UINT32_MAX
#define Py_HMAC_SSIZE_LARGER_THAN_UINT32
#endif
/*
* Assert that 'LEN' can be safely casted to uint32_t.
*
* The 'LEN' parameter should be convertible to Py_ssize_t.
*/
#ifdef Py_HMAC_SSIZE_LARGER_THAN_UINT32
#define Py_CHECK_HACL_UINT32_T_LENGTH(LEN) \
do { \
assert((Py_ssize_t)(LEN) <= UINT32_MAX_AS_SSIZE_T); \
} while (0)
#else
#define Py_CHECK_HACL_UINT32_T_LENGTH(LEN)
#endif
/*
* HMAC underlying hash function static information.
*/
typedef struct py_hmac_hinfo {
/*
* Name of the hash function used by the HACL* HMAC module.
*
* This name may differ from the hashlib names. For instance,
* SHA-2/224 is named "sha2_224" instead of "sha224" as it is
* done by 'hashlib'.
*/
const char *name;
/* hash function information */
HMAC_Hash_Kind kind;
uint32_t block_size;
uint32_t digest_size;
/* HACL* HMAC API */
py_hmac_hacl_api api;
/*
* Cached field storing the 'hashlib_name' field as a Python string.
*
* This field is NULL by default in the items of "py_hmac_static_hinfo"
* but will be populated when creating the module's state "hinfo_table".
*/
PyObject *display_name;
const char *hashlib_name; /* hashlib preferred name (default: name) */
Py_ssize_t refcnt;
} py_hmac_hinfo;
// --- HMAC module state ------------------------------------------------------
typedef struct hmacmodule_state {
_Py_hashtable_t *hinfo_table;
PyObject *unknown_hash_error;
/* HMAC object type */
PyTypeObject *hmac_type;
/* interned strings */
PyObject *str_lower;
bool can_run_simd128;
bool can_run_simd256;
} hmacmodule_state;
static inline hmacmodule_state *
get_hmacmodule_state(PyObject *module)
{
void *state = PyModule_GetState(module);
assert(state != NULL);
return (hmacmodule_state *)state;
}
static inline hmacmodule_state *
get_hmacmodule_state_by_cls(PyTypeObject *cls)
{
void *state = PyType_GetModuleState(cls);
assert(state != NULL);
return (hmacmodule_state *)state;
}
// --- HMAC Object ------------------------------------------------------------
typedef Hacl_Streaming_HMAC_agile_state HACL_HMAC_state;
typedef struct HMACObject {
HASHLIB_OBJECT_HEAD
// Hash function information
PyObject *name; // rendered name (exact unicode object)
HMAC_Hash_Kind kind; // can be used for runtime dispatch (must be known)
uint32_t block_size;
uint32_t digest_size;
py_hmac_hacl_api api;
// HMAC HACL* internal state.
HACL_HMAC_state *state;
} HMACObject;
#define HMACObject_CAST(op) ((HMACObject *)(op))
// --- HMAC module clinic configuration ---------------------------------------
/*[clinic input]
module _hmac
class _hmac.HMAC "HMACObject *" "clinic_state()->hmac_type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c8bab73fde49ba8a]*/
#define clinic_state() (get_hmacmodule_state_by_cls(Py_TYPE(self)))
#include "clinic/hmacmodule.c.h"
#undef clinic_state
// --- Helpers ----------------------------------------------------------------
//
// The helpers have the following naming conventions:
//
// - Helpers with the "_hacl" prefix are thin wrappers around HACL* functions.
// Buffer lengths given as inputs should fit on 32-bit integers.
//
// - Helpers with the "hmac_" prefix act on HMAC objects and accept buffers
// whose length fits on 32-bit or 64-bit integers (depending on the host
// machine).
/*
* Assert that a HMAC hash kind is a static kind.
*
* A "static" kind is specified in the 'py_hmac_static_hinfo'
* table and is always independent of the host CPUID features.
*/
#ifndef NDEBUG
static void
assert_is_static_hmac_hash_kind(HMAC_Hash_Kind kind)
{
switch (kind) {
case Py_hmac_kind_hash_unknown: {
Py_FatalError("HMAC hash kind must be a known kind");
return;
}
case Py_hmac_kind_hmac_vectorized_blake2s_32:
case Py_hmac_kind_hmac_vectorized_blake2b_32: {
Py_FatalError("HMAC hash kind must not be a vectorized kind");
return;
}
default:
return;
}
}
#else
static inline void
assert_is_static_hmac_hash_kind(HMAC_Hash_Kind Py_UNUSED(kind)) {}
#endif
/*
* Convert a HMAC hash static kind into a runtime kind.
*
* A "runtime" kind is derived from a static kind and depends
* on the host CPUID features. In particular, this is the kind
* that a HMAC object internally stores.
*/
static HMAC_Hash_Kind
narrow_hmac_hash_kind(hmacmodule_state *state, HMAC_Hash_Kind kind)
{
switch (kind) {
case Py_hmac_kind_hmac_blake2s_32: {
#if _Py_HACL_CAN_COMPILE_VEC128
if (state->can_run_simd128) {
return Py_hmac_kind_hmac_vectorized_blake2s_32;
}
#endif
return kind;
}
case Py_hmac_kind_hmac_blake2b_32: {
#if _Py_HACL_CAN_COMPILE_VEC256
if (state->can_run_simd256) {
return Py_hmac_kind_hmac_vectorized_blake2b_32;
}
#endif
return kind;
}
default:
return kind;
}
}
/*
* Handle the HACL* exit code.
*
* If 'code' represents a successful operation, this returns 0.
* Otherwise, this sets an appropriate exception and returns -1.
*/
static int
_hacl_convert_errno(hacl_errno_t code)
{
assert(PyGILState_GetThisThreadState() != NULL);
if (code == Hacl_Streaming_Types_Success) {
return 0;
}
PyGILState_STATE gstate = PyGILState_Ensure();
switch (code) {
case Hacl_Streaming_Types_InvalidAlgorithm: {
PyErr_SetString(PyExc_ValueError, "invalid HACL* algorithm");
break;
}
case Hacl_Streaming_Types_InvalidLength: {
PyErr_SetString(PyExc_ValueError, "invalid length");
break;
}
case Hacl_Streaming_Types_MaximumLengthExceeded: {
PyErr_SetString(PyExc_OverflowError, "maximum length exceeded");
break;
}
case Hacl_Streaming_Types_OutOfMemory: {
PyErr_NoMemory();
break;
}
default: {
PyErr_Format(PyExc_RuntimeError,
"HACL* internal routine failed with error code: %u",
code);
break;
}
}
PyGILState_Release(gstate);
return -1;
}
/*
* Return a new HACL* internal state or return NULL on failure.
*
* An appropriate exception is set if the state cannot be created.
*/
static HACL_HMAC_state *
_hacl_hmac_state_new(HMAC_Hash_Kind kind, uint8_t *key, uint32_t len)
{
assert(kind != Py_hmac_kind_hash_unknown);
HACL_HMAC_state *state = NULL;
hacl_errno_t retcode = Hacl_Streaming_HMAC_malloc_(kind, key, len, &state);
if (_hacl_convert_errno(retcode) < 0) {
assert(state == NULL);
return NULL;
}
return state;
}
/*
* Free the HACL* internal state.
*/
static inline void
_hacl_hmac_state_free(HACL_HMAC_state *state)
{
if (state != NULL) {
Hacl_Streaming_HMAC_free(state);
}
}
/*
* Call the HACL* HMAC-HASH update function on the given data.
*
* On DEBUG builds, the update() call is verified.
*
* Return 0 on success; otherwise, set an exception and return -1 on failure.
*/
static int
_hacl_hmac_state_update_once(HACL_HMAC_state *state,
uint8_t *buf, uint32_t len)
{
#ifndef NDEBUG
hacl_errno_t code = Hacl_Streaming_HMAC_update(state, buf, len);
return _hacl_convert_errno(code);
#else
(void)Hacl_Streaming_HMAC_update(state, buf, len);
return 0;
#endif
}
/*
* Perform the HMAC-HASH update() operation in a streaming fashion.
*
* On DEBUG builds, each update() call is verified.
*
* Return 0 on success; otherwise, set an exception and return -1 on failure.
*/
static int
_hacl_hmac_state_update(HACL_HMAC_state *state, uint8_t *buf, Py_ssize_t len)
{
assert(len >= 0);
#ifdef Py_HMAC_SSIZE_LARGER_THAN_UINT32
while (len > UINT32_MAX_AS_SSIZE_T) {
if (_hacl_hmac_state_update_once(state, buf, UINT32_MAX) < 0) {
assert(PyErr_Occurred());
return -1;
}
buf += UINT32_MAX;
len -= UINT32_MAX;
}
#endif
Py_CHECK_HACL_UINT32_T_LENGTH(len);
return _hacl_hmac_state_update_once(state, buf, (uint32_t)len);
}
/* Static information used to construct the hash table. */
static const py_hmac_hinfo py_hmac_static_hinfo[] = {
#define Py_HMAC_HINFO_HACL_API(HACL_HID) \
{ \
/* one-shot helpers */ \
.compute = &Py_hmac_## HACL_HID ##_compute_func, \
.compute_py = &_hmac_compute_## HACL_HID ##_impl, \
}
#define Py_HMAC_HINFO_ENTRY(HACL_HID, HLIB_NAME) \
{ \
.name = Py_STRINGIFY(HACL_HID), \
.kind = Py_hmac_kind_hmac_ ## HACL_HID, \
.block_size = Py_hmac_## HACL_HID ##_block_size, \
.digest_size = Py_hmac_## HACL_HID ##_digest_size, \
.api = Py_HMAC_HINFO_HACL_API(HACL_HID), \
.display_name = NULL, \
.hashlib_name = HLIB_NAME, \
.refcnt = 0, \
}
/* MD5 */
Py_HMAC_HINFO_ENTRY(md5, NULL),
/* SHA-1 */
Py_HMAC_HINFO_ENTRY(sha1, NULL),
/* SHA-2 family */
Py_HMAC_HINFO_ENTRY(sha2_224, "sha224"),
Py_HMAC_HINFO_ENTRY(sha2_256, "sha256"),
Py_HMAC_HINFO_ENTRY(sha2_384, "sha384"),
Py_HMAC_HINFO_ENTRY(sha2_512, "sha512"),
/* SHA-3 family */
Py_HMAC_HINFO_ENTRY(sha3_224, NULL),
Py_HMAC_HINFO_ENTRY(sha3_256, NULL),
Py_HMAC_HINFO_ENTRY(sha3_384, NULL),
Py_HMAC_HINFO_ENTRY(sha3_512, NULL),
/* Blake family */
Py_HMAC_HINFO_ENTRY(blake2s_32, "blake2s"),
Py_HMAC_HINFO_ENTRY(blake2b_32, "blake2b"),
#undef Py_HMAC_HINFO_ENTRY
#undef Py_HMAC_HINFO_HACL_API
/* sentinel */
{
NULL, Py_hmac_kind_hash_unknown, 0, 0,
{NULL, NULL},
NULL, NULL,
0,
},
};
/*
* Check whether 'name' is a known HMAC hash function name,
* storing the corresponding static information in 'info'.
*
* This function always succeeds and never set an exception.
*/
static inline bool
find_hash_info_by_utf8name(hmacmodule_state *state,
const char *name,
const py_hmac_hinfo **info)
{
assert(name != NULL);
*info = _Py_hashtable_get(state->hinfo_table, name);
return *info != NULL;
}
/*
* Find the corresponding HMAC hash function static information by its name.
*
* On error, propagate the exception, set 'info' to NULL and return -1.
*
* If no correspondence exists, set 'info' to NULL and return 0.
* Otherwise, set 'info' to the deduced information and return 1.
*
* Parameters
*
* state The HMAC module state.
* name The hash function name.
* info The deduced information, if any.
*/
static int
find_hash_info_by_name(hmacmodule_state *state,
PyObject *name,
const py_hmac_hinfo **info)
{
const char *utf8name = PyUnicode_AsUTF8(name);
if (utf8name == NULL) {
goto error;
}
if (find_hash_info_by_utf8name(state, utf8name, info)) {
return 1;
}
// try to find an alternative using the lowercase name
PyObject *lower = PyObject_CallMethodNoArgs(name, state->str_lower);
if (lower == NULL) {
goto error;
}
const char *utf8lower = PyUnicode_AsUTF8(lower);
if (utf8lower == NULL) {
Py_DECREF(lower);
goto error;
}
int found = find_hash_info_by_utf8name(state, utf8lower, info);
Py_DECREF(lower);
return found;
error:
*info = NULL;
return -1;
}
/*
* Find the corresponding HMAC hash function static information.
*
* On error, propagate the exception, set 'info' to NULL and return -1.
*
* If no correspondence exists, set 'info' to NULL and return 0.
* Otherwise, set 'info' to the deduced information and return 1.
*
* Parameters
*
* state The HMAC module state.
* hash_info_ref An input to hashlib.new().
* info The deduced information, if any.
*/
static int
find_hash_info_impl(hmacmodule_state *state,
PyObject *hash_info_ref,
const py_hmac_hinfo **info)
{
if (PyUnicode_Check(hash_info_ref)) {
return find_hash_info_by_name(state, hash_info_ref, info);
}
// NOTE(picnixz): For now, we only support named algorithms.
// In the future, we need to decide whether 'hashlib.openssl_md5'
// would make sense as an alias to 'md5' and how to remove OpenSSL.
*info = NULL;
return 0;
}
/*
* Find the corresponding HMAC hash function static information.
*
* If nothing can be found or if an error occurred, return NULL
* with an exception set. Otherwise return a non-NULL object.
*/
static const py_hmac_hinfo *
find_hash_info(hmacmodule_state *state, PyObject *hash_info_ref)
{
const py_hmac_hinfo *info = NULL;
int rc = find_hash_info_impl(state, hash_info_ref, &info);
// The code below could be simplfied with only 'rc == 0' case,
// but we are deliberately verbose to ease future improvements.
if (rc < 0) {
return NULL;
}
if (rc == 0) {
PyErr_Format(state->unknown_hash_error,
HASHLIB_UNSUPPORTED_ALGORITHM, hash_info_ref);
return NULL;
}
assert(info != NULL);
return info;
}
/* Check that the buffer length fits on a uint32_t. */
static inline int
has_uint32_t_buffer_length(const Py_buffer *buffer)
{
#ifdef Py_HMAC_SSIZE_LARGER_THAN_UINT32
return buffer->len <= UINT32_MAX_AS_SSIZE_T;
#else
return 1;
#endif
}
// --- HMAC object ------------------------------------------------------------
/*
* Use the HMAC information 'info' to populate the corresponding fields.
*
* The real 'kind' for BLAKE-2 is obtained once and depends on both static
* capabilities (supported compiler flags) and runtime CPUID features.
*/
static void
hmac_set_hinfo(hmacmodule_state *state,
HMACObject *self, const py_hmac_hinfo *info)
{
assert(info->display_name != NULL);
self->name = Py_NewRef(info->display_name);
assert_is_static_hmac_hash_kind(info->kind);
self->kind = narrow_hmac_hash_kind(state, info->kind);
assert(info->block_size <= Py_hmac_hash_max_block_size);
self->block_size = info->block_size;
assert(info->digest_size <= Py_hmac_hash_max_digest_size);
self->digest_size = info->digest_size;
assert(info->api.compute != NULL);
assert(info->api.compute_py != NULL);
self->api = info->api;
}
/*
* Create initial HACL* internal state with the given key.
*
* This function MUST only be called by the HMAC object constructor
* and after hmac_set_hinfo() has been called, lest the behaviour is
* undefined.
*
* Return 0 on success; otherwise, set an exception and return -1 on failure.
*/
static int
hmac_new_initial_state(HMACObject *self, uint8_t *key, Py_ssize_t len)
{
assert(key != NULL);
#ifdef Py_HMAC_SSIZE_LARGER_THAN_UINT32
// Technically speaking, we could hash the key to make it small
// but it would require to call the hash functions ourselves and
// not rely on HACL* implementation anymore. As such, we explicitly
// reject keys that do not fit on 32 bits until HACL* handles them.
if (len > UINT32_MAX_AS_SSIZE_T) {
set_invalid_key_length_error();
return -1;
}
#endif
assert(self->kind != Py_hmac_kind_hash_unknown);
// cast to uint32_t is now safe even on 32-bit platforms
self->state = _hacl_hmac_state_new(self->kind, key, (uint32_t)len);
// _hacl_hmac_state_new() may set an exception on error
return self->state == NULL ? -1 : 0;
}
/*[clinic input]
_hmac.new
key as keyobj: object
msg as msgobj: object(c_default="NULL") = None
digestmod as hash_info_ref: object(c_default="NULL") = None
Return a new HMAC object.
[clinic start generated code]*/
static PyObject *
_hmac_new_impl(PyObject *module, PyObject *keyobj, PyObject *msgobj,
PyObject *hash_info_ref)
/*[clinic end generated code: output=7c7573a427d58758 input=92fc7c0a00707d42]*/
{
hmacmodule_state *state = get_hmacmodule_state(module);
if (hash_info_ref == NULL) {
PyErr_SetString(PyExc_TypeError,
"new() missing 1 required argument 'digestmod'");
return NULL;
}
const py_hmac_hinfo *info = find_hash_info(state, hash_info_ref);
if (info == NULL) {
return NULL;
}
HMACObject *self = PyObject_New(HMACObject, state->hmac_type);
if (self == NULL) {
return NULL;
}
HASHLIB_INIT_MUTEX(self);
hmac_set_hinfo(state, self, info);
int rc;
// Create the HACL* internal state with the given key.
Py_buffer key;
GET_BUFFER_VIEW_OR_ERROR(keyobj, &key, goto error_on_key);
rc = hmac_new_initial_state(self, key.buf, key.len);
PyBuffer_Release(&key);
if (rc < 0) {
goto error;
}
// Feed the internal state the initial message if any.
if (msgobj != NULL && msgobj != Py_None) {
Py_buffer msg;
GET_BUFFER_VIEW_OR_ERROR(msgobj, &msg, goto error);
/* Do not use self->mutex here as this is the constructor
* where it is not yet possible to have concurrent access. */
HASHLIB_EXTERNAL_INSTRUCTIONS_UNLOCKED(
msg.len,
rc = _hacl_hmac_state_update(self->state, msg.buf, msg.len)
);
PyBuffer_Release(&msg);
#ifndef NDEBUG
if (rc < 0) {
goto error;
}
#else
(void)rc;
#endif
}
assert(rc == 0);
return (PyObject *)self;
error_on_key:
self->state = NULL;
error:
Py_DECREF(self);
return NULL;
}
/*
* Copy HMAC hash information from 'src' to 'out'.
*/
static void
hmac_copy_hinfo(HMACObject *out, const HMACObject *src)
{
assert(src->name != NULL);
out->name = Py_NewRef(src->name);
assert(src->kind != Py_hmac_kind_hash_unknown);
out->kind = src->kind;
assert(src->block_size <= Py_hmac_hash_max_block_size);
out->block_size = src->block_size;
assert(src->digest_size <= Py_hmac_hash_max_digest_size);
out->digest_size = src->digest_size;
assert(src->api.compute != NULL);
assert(src->api.compute_py != NULL);
out->api = src->api;
}
/*
* Copy the HMAC internal state from 'src' to 'out'.
*
* The internal state of 'out' must not already exist.
*
* Return 0 on success; otherwise, set an exception and return -1 on failure.
*/
static int
hmac_copy_state(HMACObject *out, const HMACObject *src)
{
assert(src->state != NULL);
out->state = Hacl_Streaming_HMAC_copy(src->state);
if (out->state == NULL) {
PyErr_NoMemory();
return -1;
}
return 0;
}
/*[clinic input]
_hmac.HMAC.copy
cls: defining_class
Return a copy ("clone") of the HMAC object.
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_copy_impl(HMACObject *self, PyTypeObject *cls)
/*[clinic end generated code: output=a955bfa55b65b215 input=17b2c0ad0b147e36]*/
{
hmacmodule_state *state = get_hmacmodule_state_by_cls(cls);
HMACObject *copy = PyObject_New(HMACObject, state->hmac_type);
if (copy == NULL) {
return NULL;
}
HASHLIB_ACQUIRE_LOCK(self);
/* copy hash information */
hmac_copy_hinfo(copy, self);
/* copy internal state */
int rc = hmac_copy_state(copy, self);
HASHLIB_RELEASE_LOCK(self);
if (rc < 0) {
Py_DECREF(copy);
return NULL;
}
HASHLIB_INIT_MUTEX(copy);
return (PyObject *)copy;
}
/*[clinic input]
_hmac.HMAC.update
msg as msgobj: object
Update the HMAC object with the given message.
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_update_impl(HMACObject *self, PyObject *msgobj)
/*[clinic end generated code: output=962134ada5e55985 input=7c0ea830efb03367]*/
{
int rc = 0;
Py_buffer msg;
GET_BUFFER_VIEW_OR_ERROUT(msgobj, &msg);
HASHLIB_EXTERNAL_INSTRUCTIONS_LOCKED(
self, msg.len,
rc = _hacl_hmac_state_update(self->state, msg.buf, msg.len)
);
PyBuffer_Release(&msg);
return rc < 0 ? NULL : Py_None;
}
/*
* Compute the HMAC-HASH digest from the internal HACL* state.
*
* At least 'self->digest_size' bytes should be available
* in the 'digest' pointed memory area.
*
* Return 0 on success; otherwise, set an exception and return -1 on failure.
*
* Note: this function may raise a MemoryError.
*/
static int
hmac_digest_compute_locked(HMACObject *self, uint8_t *digest)
{
assert(digest != NULL);
hacl_errno_t rc;
HASHLIB_ACQUIRE_LOCK(self);
rc = Hacl_Streaming_HMAC_digest(self->state, digest, self->digest_size);
HASHLIB_RELEASE_LOCK(self);
assert(
rc == Hacl_Streaming_Types_Success ||
rc == Hacl_Streaming_Types_OutOfMemory
);
return _hacl_convert_errno(rc);
}
/*[clinic input]
_hmac.HMAC.digest
Return the digest of the bytes passed to the update() method so far.
This method may raise a MemoryError.
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_digest_impl(HMACObject *self)
/*[clinic end generated code: output=5bf3cc5862d26ada input=a70feb0b8e2bbe7d]*/
{
assert(self->digest_size <= Py_hmac_hash_max_digest_size);
uint8_t digest[Py_hmac_hash_max_digest_size];
if (hmac_digest_compute_locked(self, digest) < 0) {
return NULL;
}
return PyBytes_FromStringAndSize((const char *)digest, self->digest_size);
}
/*[clinic input]
@permit_long_summary
@permit_long_docstring_body
_hmac.HMAC.hexdigest
Return hexadecimal digest of the bytes passed to the update() method so far.
This may be used to exchange the value safely in email or other non-binary
environments.
This method may raise a MemoryError.
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_hexdigest_impl(HMACObject *self)
/*[clinic end generated code: output=6659807a09ae14ec input=6e0e796e38d82fc8]*/
{
assert(self->digest_size <= Py_hmac_hash_max_digest_size);
uint8_t digest[Py_hmac_hash_max_digest_size];
if (hmac_digest_compute_locked(self, digest) < 0) {
return NULL;
}
return _Py_strhex((const char *)digest, self->digest_size);
}
/*[clinic input]
@getter
_hmac.HMAC.name
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_name_get_impl(HMACObject *self)
/*[clinic end generated code: output=ae693f09778d96d9 input=41c2c5dd1cf47fbc]*/
{
assert(self->name != NULL);
return PyUnicode_FromFormat("hmac-%U", self->name);
}
/*[clinic input]
@getter
_hmac.HMAC.block_size
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_block_size_get_impl(HMACObject *self)
/*[clinic end generated code: output=52cb11dee4e80cae input=9dda6b8d43e995b4]*/
{
return PyLong_FromUInt32(self->block_size);
}
/*[clinic input]
@getter
_hmac.HMAC.digest_size
[clinic start generated code]*/
static PyObject *
_hmac_HMAC_digest_size_get_impl(HMACObject *self)
/*[clinic end generated code: output=22eeca1010ac6255 input=5622bb2840025b5a]*/