-
-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
_hashopenssl.c
2311 lines (1952 loc) · 60.4 KB
/
_hashopenssl.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
/* Module that wraps all OpenSSL hash algorithms */
/*
* Copyright (C) 2005-2010 Gregory P. Smith ([email protected])
* Licensed to PSF under a Contributor Agreement.
*
* Derived from a skeleton of shamodule.c containing work performed by:
*
* Andrew Kuchling ([email protected])
* Greg Stein ([email protected])
*
*/
/* Don't warn about deprecated functions, */
#ifndef OPENSSL_API_COMPAT
// 0x10101000L == 1.1.1, 30000 == 3.0.0
#define OPENSSL_API_COMPAT 0x10101000L
#endif
#define OPENSSL_NO_DEPRECATED 1
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include <stdbool.h>
#include "Python.h"
#include "pycore_hashtable.h"
#include "pycore_strhex.h" // _Py_strhex()
#include "hashlib.h"
/* EVP is the preferred interface to hashing in OpenSSL */
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/crypto.h> // FIPS_mode()
/* We use the object interface to discover what hashes OpenSSL supports. */
#include <openssl/objects.h>
#include <openssl/err.h>
#ifndef OPENSSL_THREADS
# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
#endif
#define MUNCH_SIZE INT_MAX
#define PY_OPENSSL_HAS_SCRYPT 1
#if defined(NID_sha3_224) && defined(NID_sha3_256) && defined(NID_sha3_384) && defined(NID_sha3_512)
#define PY_OPENSSL_HAS_SHA3 1
#endif
#if defined(NID_shake128) || defined(NID_shake256)
#define PY_OPENSSL_HAS_SHAKE 1
#endif
#if defined(NID_blake2s256) || defined(NID_blake2b512)
#define PY_OPENSSL_HAS_BLAKE2 1
#endif
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#define PY_EVP_MD EVP_MD
#define PY_EVP_MD_fetch(algorithm, properties) EVP_MD_fetch(NULL, algorithm, properties)
#define PY_EVP_MD_up_ref(md) EVP_MD_up_ref(md)
#define PY_EVP_MD_free(md) EVP_MD_free(md)
#else
#define PY_EVP_MD const EVP_MD
#define PY_EVP_MD_fetch(algorithm, properties) EVP_get_digestbyname(algorithm)
#define PY_EVP_MD_up_ref(md) do {} while(0)
#define PY_EVP_MD_free(md) do {} while(0)
#endif
/* hash alias map and fast lookup
*
* Map between Python's preferred names and OpenSSL internal names. Maintain
* cache of fetched EVP MD objects. The EVP_get_digestbyname() and
* EVP_MD_fetch() API calls have a performance impact.
*
* The py_hashentry_t items are stored in a _Py_hashtable_t with py_name and
* py_alias as keys.
*/
enum Py_hash_type {
Py_ht_evp, // usedforsecurity=True / default
Py_ht_evp_nosecurity, // usedforsecurity=False
Py_ht_mac, // HMAC
Py_ht_pbkdf2, // PKBDF2
};
typedef struct {
const char *py_name;
const char *py_alias;
const char *ossl_name;
int ossl_nid;
int refcnt;
PY_EVP_MD *evp;
PY_EVP_MD *evp_nosecurity;
} py_hashentry_t;
// Fundamental to TLS, assumed always present in any libcrypto:
#define Py_hash_md5 "md5"
#define Py_hash_sha1 "sha1"
#define Py_hash_sha224 "sha224"
#define Py_hash_sha256 "sha256"
#define Py_hash_sha384 "sha384"
#define Py_hash_sha512 "sha512"
// Not all OpenSSL-like libcrypto libraries provide these:
#if defined(NID_sha512_224)
# define Py_hash_sha512_224 "sha512_224"
#endif
#if defined(NID_sha512_256)
# define Py_hash_sha512_256 "sha512_256"
#endif
#if defined(NID_sha3_224)
# define Py_hash_sha3_224 "sha3_224"
#endif
#if defined(NID_sha3_256)
# define Py_hash_sha3_256 "sha3_256"
#endif
#if defined(NID_sha3_384)
# define Py_hash_sha3_384 "sha3_384"
#endif
#if defined(NID_sha3_512)
# define Py_hash_sha3_512 "sha3_512"
#endif
#if defined(NID_shake128)
# define Py_hash_shake_128 "shake_128"
#endif
#if defined(NID_shake256)
# define Py_hash_shake_256 "shake_256"
#endif
#if defined(NID_blake2s256)
# define Py_hash_blake2s "blake2s"
#endif
#if defined(NID_blake2b512)
# define Py_hash_blake2b "blake2b"
#endif
#define PY_HASH_ENTRY(py_name, py_alias, ossl_name, ossl_nid) \
{py_name, py_alias, ossl_name, ossl_nid, 0, NULL, NULL}
static const py_hashentry_t py_hashes[] = {
/* md5 */
PY_HASH_ENTRY(Py_hash_md5, "MD5", SN_md5, NID_md5),
/* sha1 */
PY_HASH_ENTRY(Py_hash_sha1, "SHA1", SN_sha1, NID_sha1),
/* sha2 family */
PY_HASH_ENTRY(Py_hash_sha224, "SHA224", SN_sha224, NID_sha224),
PY_HASH_ENTRY(Py_hash_sha256, "SHA256", SN_sha256, NID_sha256),
PY_HASH_ENTRY(Py_hash_sha384, "SHA384", SN_sha384, NID_sha384),
PY_HASH_ENTRY(Py_hash_sha512, "SHA512", SN_sha512, NID_sha512),
/* truncated sha2 */
#ifdef Py_hash_sha512_224
PY_HASH_ENTRY(Py_hash_sha512_224, "SHA512_224", SN_sha512_224, NID_sha512_224),
#endif
#ifdef Py_hash_sha512_256
PY_HASH_ENTRY(Py_hash_sha512_256, "SHA512_256", SN_sha512_256, NID_sha512_256),
#endif
/* sha3 */
#ifdef Py_hash_sha3_224
PY_HASH_ENTRY(Py_hash_sha3_224, NULL, SN_sha3_224, NID_sha3_224),
#endif
#ifdef Py_hash_sha3_256
PY_HASH_ENTRY(Py_hash_sha3_256, NULL, SN_sha3_256, NID_sha3_256),
#endif
#ifdef Py_hash_sha3_384
PY_HASH_ENTRY(Py_hash_sha3_384, NULL, SN_sha3_384, NID_sha3_384),
#endif
#ifdef Py_hash_sha3_512
PY_HASH_ENTRY(Py_hash_sha3_512, NULL, SN_sha3_512, NID_sha3_512),
#endif
/* sha3 shake */
#ifdef Py_hash_shake_128
PY_HASH_ENTRY(Py_hash_shake_128, NULL, SN_shake128, NID_shake128),
#endif
#ifdef Py_hash_shake_256
PY_HASH_ENTRY(Py_hash_shake_256, NULL, SN_shake256, NID_shake256),
#endif
/* blake2 digest */
#ifdef Py_hash_blake2s
PY_HASH_ENTRY(Py_hash_blake2s, "blake2s256", SN_blake2s256, NID_blake2s256),
#endif
#ifdef Py_hash_blake2b
PY_HASH_ENTRY(Py_hash_blake2b, "blake2b512", SN_blake2b512, NID_blake2b512),
#endif
PY_HASH_ENTRY(NULL, NULL, NULL, 0),
};
static Py_uhash_t
py_hashentry_t_hash_name(const void *key) {
return Py_HashBuffer(key, strlen((const char *)key));
}
static int
py_hashentry_t_compare_name(const void *key1, const void *key2) {
return strcmp((const char *)key1, (const char *)key2) == 0;
}
static void
py_hashentry_t_destroy_value(void *entry) {
py_hashentry_t *h = (py_hashentry_t *)entry;
if (--(h->refcnt) == 0) {
if (h->evp != NULL) {
PY_EVP_MD_free(h->evp);
h->evp = NULL;
}
if (h->evp_nosecurity != NULL) {
PY_EVP_MD_free(h->evp_nosecurity);
h->evp_nosecurity = NULL;
}
PyMem_Free(entry);
}
}
static _Py_hashtable_t *
py_hashentry_table_new(void) {
_Py_hashtable_t *ht = _Py_hashtable_new_full(
py_hashentry_t_hash_name,
py_hashentry_t_compare_name,
NULL,
py_hashentry_t_destroy_value,
NULL
);
if (ht == NULL) {
return NULL;
}
for (const py_hashentry_t *h = py_hashes; h->py_name != NULL; h++) {
py_hashentry_t *entry = (py_hashentry_t *)PyMem_Malloc(sizeof(py_hashentry_t));
if (entry == NULL) {
goto error;
}
memcpy(entry, h, sizeof(py_hashentry_t));
if (_Py_hashtable_set(ht, (const void*)entry->py_name, (void*)entry) < 0) {
PyMem_Free(entry);
goto error;
}
entry->refcnt = 1;
if (h->py_alias != NULL) {
if (_Py_hashtable_set(ht, (const void*)entry->py_alias, (void*)entry) < 0) {
PyMem_Free(entry);
goto error;
}
entry->refcnt++;
}
}
return ht;
error:
_Py_hashtable_destroy(ht);
return NULL;
}
/* Module state */
static PyModuleDef _hashlibmodule;
typedef struct {
PyTypeObject *EVPtype;
PyTypeObject *HMACtype;
#ifdef PY_OPENSSL_HAS_SHAKE
PyTypeObject *EVPXOFtype;
#endif
PyObject *constructs;
PyObject *unsupported_digestmod_error;
_Py_hashtable_t *hashtable;
} _hashlibstate;
static inline _hashlibstate*
get_hashlib_state(PyObject *module)
{
void *state = PyModule_GetState(module);
assert(state != NULL);
return (_hashlibstate *)state;
}
typedef struct {
PyObject_HEAD
EVP_MD_CTX *ctx; /* OpenSSL message digest context */
// Prevents undefined behavior via multiple threads entering the C API.
bool use_mutex;
PyMutex mutex; /* OpenSSL context lock */
} EVPobject;
typedef struct {
PyObject_HEAD
HMAC_CTX *ctx; /* OpenSSL hmac context */
// Prevents undefined behavior via multiple threads entering the C API.
bool use_mutex;
PyMutex mutex; /* HMAC context lock */
} HMACobject;
#include "clinic/_hashopenssl.c.h"
/*[clinic input]
module _hashlib
class _hashlib.HASH "EVPobject *" "((_hashlibstate *)PyModule_GetState(module))->EVPtype"
class _hashlib.HASHXOF "EVPobject *" "((_hashlibstate *)PyModule_GetState(module))->EVPXOFtype"
class _hashlib.HMAC "HMACobject *" "((_hashlibstate *)PyModule_GetState(module))->HMACtype"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7df1bcf6f75cb8ef]*/
/* LCOV_EXCL_START */
static PyObject *
_setException(PyObject *exc, const char* altmsg, ...)
{
unsigned long errcode = ERR_peek_last_error();
const char *lib, *func, *reason;
va_list vargs;
va_start(vargs, altmsg);
if (!errcode) {
if (altmsg == NULL) {
PyErr_SetString(exc, "no reason supplied");
} else {
PyErr_FormatV(exc, altmsg, vargs);
}
va_end(vargs);
return NULL;
}
va_end(vargs);
ERR_clear_error();
lib = ERR_lib_error_string(errcode);
func = ERR_func_error_string(errcode);
reason = ERR_reason_error_string(errcode);
if (lib && func) {
PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
}
else if (lib) {
PyErr_Format(exc, "[%s] %s", lib, reason);
}
else {
PyErr_SetString(exc, reason);
}
return NULL;
}
/* LCOV_EXCL_STOP */
static PyObject*
py_digest_name(const EVP_MD *md)
{
int nid = EVP_MD_nid(md);
const char *name = NULL;
const py_hashentry_t *h;
for (h = py_hashes; h->py_name != NULL; h++) {
if (h->ossl_nid == nid) {
name = h->py_name;
break;
}
}
if (name == NULL) {
/* Ignore aliased names and only use long, lowercase name. The aliases
* pollute the list and OpenSSL appears to have its own definition of
* alias as the resulting list still contains duplicate and alternate
* names for several algorithms.
*/
name = OBJ_nid2ln(nid);
if (name == NULL)
name = OBJ_nid2sn(nid);
}
return PyUnicode_FromString(name);
}
/* Get EVP_MD by HID and purpose */
static PY_EVP_MD*
py_digest_by_name(PyObject *module, const char *name, enum Py_hash_type py_ht)
{
PY_EVP_MD *digest = NULL;
_hashlibstate *state = get_hashlib_state(module);
py_hashentry_t *entry = (py_hashentry_t *)_Py_hashtable_get(
state->hashtable, (const void*)name
);
if (entry != NULL) {
switch (py_ht) {
case Py_ht_evp:
case Py_ht_mac:
case Py_ht_pbkdf2:
if (entry->evp == NULL) {
entry->evp = PY_EVP_MD_fetch(entry->ossl_name, NULL);
}
digest = entry->evp;
break;
case Py_ht_evp_nosecurity:
if (entry->evp_nosecurity == NULL) {
entry->evp_nosecurity = PY_EVP_MD_fetch(entry->ossl_name, "-fips");
}
digest = entry->evp_nosecurity;
break;
}
if (digest != NULL) {
PY_EVP_MD_up_ref(digest);
}
} else {
// Fall back for looking up an unindexed OpenSSL specific name.
switch (py_ht) {
case Py_ht_evp:
case Py_ht_mac:
case Py_ht_pbkdf2:
digest = PY_EVP_MD_fetch(name, NULL);
break;
case Py_ht_evp_nosecurity:
digest = PY_EVP_MD_fetch(name, "-fips");
break;
}
}
if (digest == NULL) {
_setException(state->unsupported_digestmod_error, "unsupported hash type %s", name);
return NULL;
}
return digest;
}
/* Get digest EVP from object
*
* * string
* * _hashopenssl builtin function
*
* on error returns NULL with exception set.
*/
static PY_EVP_MD*
py_digest_by_digestmod(PyObject *module, PyObject *digestmod, enum Py_hash_type py_ht) {
PY_EVP_MD* evp;
PyObject *name_obj = NULL;
const char *name;
if (PyUnicode_Check(digestmod)) {
name_obj = digestmod;
} else {
_hashlibstate *state = get_hashlib_state(module);
// borrowed ref
name_obj = PyDict_GetItemWithError(state->constructs, digestmod);
}
if (name_obj == NULL) {
if (!PyErr_Occurred()) {
_hashlibstate *state = get_hashlib_state(module);
PyErr_Format(
state->unsupported_digestmod_error,
"Unsupported digestmod %R", digestmod);
}
return NULL;
}
name = PyUnicode_AsUTF8(name_obj);
if (name == NULL) {
return NULL;
}
evp = py_digest_by_name(module, name, py_ht);
if (evp == NULL) {
return NULL;
}
return evp;
}
static EVPobject *
newEVPobject(PyTypeObject *type)
{
EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, type);
if (retval == NULL) {
return NULL;
}
HASHLIB_INIT_MUTEX(retval);
retval->ctx = EVP_MD_CTX_new();
if (retval->ctx == NULL) {
Py_DECREF(retval);
PyErr_NoMemory();
return NULL;
}
return retval;
}
static int
EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
{
unsigned int process;
const unsigned char *cp = (const unsigned char *)vp;
while (0 < len) {
if (len > (Py_ssize_t)MUNCH_SIZE)
process = MUNCH_SIZE;
else
process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
_setException(PyExc_ValueError, NULL);
return -1;
}
len -= process;
cp += process;
}
return 0;
}
/* Internal methods for a hash object */
static void
EVP_dealloc(EVPobject *self)
{
PyTypeObject *tp = Py_TYPE(self);
EVP_MD_CTX_free(self->ctx);
PyObject_Free(self);
Py_DECREF(tp);
}
static int
locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
{
int result;
ENTER_HASHLIB(self);
result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
LEAVE_HASHLIB(self);
return result;
}
/* External methods for a hash object */
/*[clinic input]
_hashlib.HASH.copy as EVP_copy
Return a copy of the hash object.
[clinic start generated code]*/
static PyObject *
EVP_copy_impl(EVPobject *self)
/*[clinic end generated code: output=b370c21cdb8ca0b4 input=31455b6a3e638069]*/
{
EVPobject *newobj;
if ((newobj = newEVPobject(Py_TYPE(self))) == NULL)
return NULL;
if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
Py_DECREF(newobj);
return _setException(PyExc_ValueError, NULL);
}
return (PyObject *)newobj;
}
/*[clinic input]
_hashlib.HASH.digest as EVP_digest
Return the digest value as a bytes object.
[clinic start generated code]*/
static PyObject *
EVP_digest_impl(EVPobject *self)
/*[clinic end generated code: output=0f6a3a0da46dc12d input=03561809a419bf00]*/
{
unsigned char digest[EVP_MAX_MD_SIZE];
EVP_MD_CTX *temp_ctx;
PyObject *retval;
unsigned int digest_size;
temp_ctx = EVP_MD_CTX_new();
if (temp_ctx == NULL) {
PyErr_NoMemory();
return NULL;
}
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
return _setException(PyExc_ValueError, NULL);
}
digest_size = EVP_MD_CTX_size(temp_ctx);
if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
_setException(PyExc_ValueError, NULL);
return NULL;
}
retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
EVP_MD_CTX_free(temp_ctx);
return retval;
}
/*[clinic input]
_hashlib.HASH.hexdigest as EVP_hexdigest
Return the digest value as a string of hexadecimal digits.
[clinic start generated code]*/
static PyObject *
EVP_hexdigest_impl(EVPobject *self)
/*[clinic end generated code: output=18e6decbaf197296 input=aff9cf0e4c741a9a]*/
{
unsigned char digest[EVP_MAX_MD_SIZE];
EVP_MD_CTX *temp_ctx;
unsigned int digest_size;
temp_ctx = EVP_MD_CTX_new();
if (temp_ctx == NULL) {
PyErr_NoMemory();
return NULL;
}
/* Get the raw (binary) digest value */
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
return _setException(PyExc_ValueError, NULL);
}
digest_size = EVP_MD_CTX_size(temp_ctx);
if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
_setException(PyExc_ValueError, NULL);
return NULL;
}
EVP_MD_CTX_free(temp_ctx);
return _Py_strhex((const char *)digest, (Py_ssize_t)digest_size);
}
/*[clinic input]
_hashlib.HASH.update as EVP_update
obj: object
/
Update this hash object's state with the provided string.
[clinic start generated code]*/
static PyObject *
EVP_update(EVPobject *self, PyObject *obj)
/*[clinic end generated code: output=ec1d55ed2432e966 input=9b30ec848f015501]*/
{
int result;
Py_buffer view;
GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
if (!self->use_mutex && view.len >= HASHLIB_GIL_MINSIZE) {
self->use_mutex = true;
}
if (self->use_mutex) {
Py_BEGIN_ALLOW_THREADS
PyMutex_Lock(&self->mutex);
result = EVP_hash(self, view.buf, view.len);
PyMutex_Unlock(&self->mutex);
Py_END_ALLOW_THREADS
} else {
result = EVP_hash(self, view.buf, view.len);
}
PyBuffer_Release(&view);
if (result == -1)
return NULL;
Py_RETURN_NONE;
}
static PyMethodDef EVP_methods[] = {
EVP_UPDATE_METHODDEF
EVP_DIGEST_METHODDEF
EVP_HEXDIGEST_METHODDEF
EVP_COPY_METHODDEF
{NULL, NULL} /* sentinel */
};
static PyObject *
EVP_get_block_size(EVPobject *self, void *closure)
{
long block_size;
block_size = EVP_MD_CTX_block_size(self->ctx);
return PyLong_FromLong(block_size);
}
static PyObject *
EVP_get_digest_size(EVPobject *self, void *closure)
{
long size;
size = EVP_MD_CTX_size(self->ctx);
return PyLong_FromLong(size);
}
static PyObject *
EVP_get_name(EVPobject *self, void *closure)
{
return py_digest_name(EVP_MD_CTX_md(self->ctx));
}
static PyGetSetDef EVP_getseters[] = {
{"digest_size",
(getter)EVP_get_digest_size, NULL,
NULL,
NULL},
{"block_size",
(getter)EVP_get_block_size, NULL,
NULL,
NULL},
{"name",
(getter)EVP_get_name, NULL,
NULL,
PyDoc_STR("algorithm name.")},
{NULL} /* Sentinel */
};
static PyObject *
EVP_repr(EVPobject *self)
{
PyObject *name_obj, *repr;
name_obj = py_digest_name(EVP_MD_CTX_md(self->ctx));
if (!name_obj) {
return NULL;
}
repr = PyUnicode_FromFormat("<%U %s object @ %p>",
name_obj, Py_TYPE(self)->tp_name, self);
Py_DECREF(name_obj);
return repr;
}
PyDoc_STRVAR(hashtype_doc,
"HASH(name, string=b\'\')\n"
"--\n"
"\n"
"A hash is an object used to calculate a checksum of a string of information.\n"
"\n"
"Methods:\n"
"\n"
"update() -- updates the current digest with an additional string\n"
"digest() -- return the current digest value\n"
"hexdigest() -- return the current digest as a string of hexadecimal digits\n"
"copy() -- return a copy of the current hash object\n"
"\n"
"Attributes:\n"
"\n"
"name -- the hash algorithm being used by this object\n"
"digest_size -- number of bytes in this hashes output");
static PyType_Slot EVPtype_slots[] = {
{Py_tp_dealloc, EVP_dealloc},
{Py_tp_repr, EVP_repr},
{Py_tp_doc, (char *)hashtype_doc},
{Py_tp_methods, EVP_methods},
{Py_tp_getset, EVP_getseters},
{0, 0},
};
static PyType_Spec EVPtype_spec = {
"_hashlib.HASH", /*tp_name*/
sizeof(EVPobject), /*tp_basicsize*/
0, /*tp_itemsize*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
EVPtype_slots
};
#ifdef PY_OPENSSL_HAS_SHAKE
/*[clinic input]
_hashlib.HASHXOF.digest as EVPXOF_digest
length: Py_ssize_t
Return the digest value as a bytes object.
[clinic start generated code]*/
static PyObject *
EVPXOF_digest_impl(EVPobject *self, Py_ssize_t length)
/*[clinic end generated code: output=ef9320c23280efad input=816a6537cea3d1db]*/
{
EVP_MD_CTX *temp_ctx;
PyObject *retval = PyBytes_FromStringAndSize(NULL, length);
if (retval == NULL) {
return NULL;
}
temp_ctx = EVP_MD_CTX_new();
if (temp_ctx == NULL) {
Py_DECREF(retval);
PyErr_NoMemory();
return NULL;
}
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
Py_DECREF(retval);
EVP_MD_CTX_free(temp_ctx);
return _setException(PyExc_ValueError, NULL);
}
if (!EVP_DigestFinalXOF(temp_ctx,
(unsigned char*)PyBytes_AS_STRING(retval),
length)) {
Py_DECREF(retval);
EVP_MD_CTX_free(temp_ctx);
_setException(PyExc_ValueError, NULL);
return NULL;
}
EVP_MD_CTX_free(temp_ctx);
return retval;
}
/*[clinic input]
_hashlib.HASHXOF.hexdigest as EVPXOF_hexdigest
length: Py_ssize_t
Return the digest value as a string of hexadecimal digits.
[clinic start generated code]*/
static PyObject *
EVPXOF_hexdigest_impl(EVPobject *self, Py_ssize_t length)
/*[clinic end generated code: output=eb3e6ee7788bf5b2 input=5f9d6a8f269e34df]*/
{
unsigned char *digest;
EVP_MD_CTX *temp_ctx;
PyObject *retval;
digest = (unsigned char*)PyMem_Malloc(length);
if (digest == NULL) {
PyErr_NoMemory();
return NULL;
}
temp_ctx = EVP_MD_CTX_new();
if (temp_ctx == NULL) {
PyMem_Free(digest);
PyErr_NoMemory();
return NULL;
}
/* Get the raw (binary) digest value */
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
PyMem_Free(digest);
EVP_MD_CTX_free(temp_ctx);
return _setException(PyExc_ValueError, NULL);
}
if (!EVP_DigestFinalXOF(temp_ctx, digest, length)) {
PyMem_Free(digest);
EVP_MD_CTX_free(temp_ctx);
_setException(PyExc_ValueError, NULL);
return NULL;
}
EVP_MD_CTX_free(temp_ctx);
retval = _Py_strhex((const char *)digest, length);
PyMem_Free(digest);
return retval;
}
static PyMethodDef EVPXOF_methods[] = {
EVPXOF_DIGEST_METHODDEF
EVPXOF_HEXDIGEST_METHODDEF
{NULL, NULL} /* sentinel */
};
static PyObject *
EVPXOF_get_digest_size(EVPobject *self, void *closure)
{
return PyLong_FromLong(0);
}
static PyGetSetDef EVPXOF_getseters[] = {
{"digest_size",
(getter)EVPXOF_get_digest_size, NULL,
NULL,
NULL},
{NULL} /* Sentinel */
};
PyDoc_STRVAR(hashxoftype_doc,
"HASHXOF(name, string=b\'\')\n"
"--\n"
"\n"
"A hash is an object used to calculate a checksum of a string of information.\n"
"\n"
"Methods:\n"
"\n"
"update() -- updates the current digest with an additional string\n"
"digest(length) -- return the current digest value\n"
"hexdigest(length) -- return the current digest as a string of hexadecimal digits\n"
"copy() -- return a copy of the current hash object\n"
"\n"
"Attributes:\n"
"\n"
"name -- the hash algorithm being used by this object\n"
"digest_size -- number of bytes in this hashes output");
static PyType_Slot EVPXOFtype_slots[] = {
{Py_tp_doc, (char *)hashxoftype_doc},
{Py_tp_methods, EVPXOF_methods},
{Py_tp_getset, EVPXOF_getseters},
{0, 0},
};
static PyType_Spec EVPXOFtype_spec = {
"_hashlib.HASHXOF", /*tp_name*/
sizeof(EVPobject), /*tp_basicsize*/
0, /*tp_itemsize*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
EVPXOFtype_slots
};
#endif
static PyObject*
py_evp_fromname(PyObject *module, const char *digestname, PyObject *data_obj,
int usedforsecurity)
{
Py_buffer view = { 0 };
PY_EVP_MD *digest = NULL;
PyTypeObject *type;
EVPobject *self = NULL;
if (data_obj != NULL) {
GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
}
digest = py_digest_by_name(
module, digestname, usedforsecurity ? Py_ht_evp : Py_ht_evp_nosecurity
);
if (digest == NULL) {
goto exit;
}
if ((EVP_MD_flags(digest) & EVP_MD_FLAG_XOF) == EVP_MD_FLAG_XOF) {
type = get_hashlib_state(module)->EVPXOFtype;
} else {
type = get_hashlib_state(module)->EVPtype;
}
self = newEVPobject(type);
if (self == NULL) {
goto exit;
}
#if defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW) && OPENSSL_VERSION_NUMBER < 0x30000000L
// In OpenSSL 1.1.1 the non FIPS allowed flag is context specific while
// in 3.0.0 it is a different EVP_MD provider.
if (!usedforsecurity) {
EVP_MD_CTX_set_flags(self->ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
}
#endif
int result = EVP_DigestInit_ex(self->ctx, digest, NULL);
if (!result) {
_setException(PyExc_ValueError, NULL);
Py_CLEAR(self);
goto exit;
}
if (view.buf && view.len) {
if (view.len >= HASHLIB_GIL_MINSIZE) {
/* We do not initialize self->lock here as this is the constructor
* where it is not yet possible to have concurrent access. */
Py_BEGIN_ALLOW_THREADS
result = EVP_hash(self, view.buf, view.len);
Py_END_ALLOW_THREADS
} else {
result = EVP_hash(self, view.buf, view.len);
}
if (result == -1) {
Py_CLEAR(self);
goto exit;
}
}
exit:
if (data_obj != NULL) {
PyBuffer_Release(&view);
}
if (digest != NULL) {
PY_EVP_MD_free(digest);
}
return (PyObject *)self;
}
/* The module-level function: new() */
/*[clinic input]
_hashlib.new as EVP_new
name as name_obj: object
string as data_obj: object(c_default="NULL") = b''
*
usedforsecurity: bool = True
Return a new hash object using the named algorithm.
An optional string argument may be provided and will be
automatically hashed.
The MD5 and SHA1 algorithms are always supported.
[clinic start generated code]*/
static PyObject *
EVP_new_impl(PyObject *module, PyObject *name_obj, PyObject *data_obj,
int usedforsecurity)
/*[clinic end generated code: output=ddd5053f92dffe90 input=c24554d0337be1b0]*/
{
char *name;
if (!PyArg_Parse(name_obj, "s", &name)) {
PyErr_SetString(PyExc_TypeError, "name must be a string");
return NULL;
}