Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Modules/_hashopenssl.c
12 views
1
/* Module that wraps all OpenSSL hash algorithms */
2
3
/*
4
* Copyright (C) 2005-2010 Gregory P. Smith ([email protected])
5
* Licensed to PSF under a Contributor Agreement.
6
*
7
* Derived from a skeleton of shamodule.c containing work performed by:
8
*
9
* Andrew Kuchling ([email protected])
10
* Greg Stein ([email protected])
11
*
12
*/
13
14
/* Don't warn about deprecated functions, */
15
#ifndef OPENSSL_API_COMPAT
16
// 0x10101000L == 1.1.1, 30000 == 3.0.0
17
#define OPENSSL_API_COMPAT 0x10101000L
18
#endif
19
#define OPENSSL_NO_DEPRECATED 1
20
21
#ifndef Py_BUILD_CORE_BUILTIN
22
# define Py_BUILD_CORE_MODULE 1
23
#endif
24
25
#include "Python.h"
26
#include "pycore_hashtable.h"
27
#include "hashlib.h"
28
#include "pycore_strhex.h" // _Py_strhex()
29
30
/* EVP is the preferred interface to hashing in OpenSSL */
31
#include <openssl/evp.h>
32
#include <openssl/hmac.h>
33
#include <openssl/crypto.h> // FIPS_mode()
34
/* We use the object interface to discover what hashes OpenSSL supports. */
35
#include <openssl/objects.h>
36
#include <openssl/err.h>
37
38
39
#ifndef OPENSSL_THREADS
40
# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
41
#endif
42
43
#define MUNCH_SIZE INT_MAX
44
45
#define PY_OPENSSL_HAS_SCRYPT 1
46
#define PY_OPENSSL_HAS_SHA3 1
47
#define PY_OPENSSL_HAS_SHAKE 1
48
#define PY_OPENSSL_HAS_BLAKE2 1
49
50
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
51
#define PY_EVP_MD EVP_MD
52
#define PY_EVP_MD_fetch(algorithm, properties) EVP_MD_fetch(NULL, algorithm, properties)
53
#define PY_EVP_MD_up_ref(md) EVP_MD_up_ref(md)
54
#define PY_EVP_MD_free(md) EVP_MD_free(md)
55
#else
56
#define PY_EVP_MD const EVP_MD
57
#define PY_EVP_MD_fetch(algorithm, properties) EVP_get_digestbyname(algorithm)
58
#define PY_EVP_MD_up_ref(md) do {} while(0)
59
#define PY_EVP_MD_free(md) do {} while(0)
60
#endif
61
62
/* hash alias map and fast lookup
63
*
64
* Map between Python's preferred names and OpenSSL internal names. Maintain
65
* cache of fetched EVP MD objects. The EVP_get_digestbyname() and
66
* EVP_MD_fetch() API calls have a performance impact.
67
*
68
* The py_hashentry_t items are stored in a _Py_hashtable_t with py_name and
69
* py_alias as keys.
70
*/
71
72
enum Py_hash_type {
73
Py_ht_evp, // usedforsecurity=True / default
74
Py_ht_evp_nosecurity, // usedforsecurity=False
75
Py_ht_mac, // HMAC
76
Py_ht_pbkdf2, // PKBDF2
77
};
78
79
typedef struct {
80
const char *py_name;
81
const char *py_alias;
82
const char *ossl_name;
83
int ossl_nid;
84
int refcnt;
85
PY_EVP_MD *evp;
86
PY_EVP_MD *evp_nosecurity;
87
} py_hashentry_t;
88
89
#define Py_hash_md5 "md5"
90
#define Py_hash_sha1 "sha1"
91
#define Py_hash_sha224 "sha224"
92
#define Py_hash_sha256 "sha256"
93
#define Py_hash_sha384 "sha384"
94
#define Py_hash_sha512 "sha512"
95
#define Py_hash_sha512_224 "sha512_224"
96
#define Py_hash_sha512_256 "sha512_256"
97
#define Py_hash_sha3_224 "sha3_224"
98
#define Py_hash_sha3_256 "sha3_256"
99
#define Py_hash_sha3_384 "sha3_384"
100
#define Py_hash_sha3_512 "sha3_512"
101
#define Py_hash_shake_128 "shake_128"
102
#define Py_hash_shake_256 "shake_256"
103
#define Py_hash_blake2s "blake2s"
104
#define Py_hash_blake2b "blake2b"
105
106
#define PY_HASH_ENTRY(py_name, py_alias, ossl_name, ossl_nid) \
107
{py_name, py_alias, ossl_name, ossl_nid, 0, NULL, NULL}
108
109
static const py_hashentry_t py_hashes[] = {
110
/* md5 */
111
PY_HASH_ENTRY(Py_hash_md5, "MD5", SN_md5, NID_md5),
112
/* sha1 */
113
PY_HASH_ENTRY(Py_hash_sha1, "SHA1", SN_sha1, NID_sha1),
114
/* sha2 family */
115
PY_HASH_ENTRY(Py_hash_sha224, "SHA224", SN_sha224, NID_sha224),
116
PY_HASH_ENTRY(Py_hash_sha256, "SHA256", SN_sha256, NID_sha256),
117
PY_HASH_ENTRY(Py_hash_sha384, "SHA384", SN_sha384, NID_sha384),
118
PY_HASH_ENTRY(Py_hash_sha512, "SHA512", SN_sha512, NID_sha512),
119
/* truncated sha2 */
120
PY_HASH_ENTRY(Py_hash_sha512_224, "SHA512_224", SN_sha512_224, NID_sha512_224),
121
PY_HASH_ENTRY(Py_hash_sha512_256, "SHA512_256", SN_sha512_256, NID_sha512_256),
122
/* sha3 */
123
PY_HASH_ENTRY(Py_hash_sha3_224, NULL, SN_sha3_224, NID_sha3_224),
124
PY_HASH_ENTRY(Py_hash_sha3_256, NULL, SN_sha3_256, NID_sha3_256),
125
PY_HASH_ENTRY(Py_hash_sha3_384, NULL, SN_sha3_384, NID_sha3_384),
126
PY_HASH_ENTRY(Py_hash_sha3_512, NULL, SN_sha3_512, NID_sha3_512),
127
/* sha3 shake */
128
PY_HASH_ENTRY(Py_hash_shake_128, NULL, SN_shake128, NID_shake128),
129
PY_HASH_ENTRY(Py_hash_shake_256, NULL, SN_shake256, NID_shake256),
130
/* blake2 digest */
131
PY_HASH_ENTRY(Py_hash_blake2s, "blake2s256", SN_blake2s256, NID_blake2s256),
132
PY_HASH_ENTRY(Py_hash_blake2b, "blake2b512", SN_blake2b512, NID_blake2b512),
133
PY_HASH_ENTRY(NULL, NULL, NULL, 0),
134
};
135
136
static Py_uhash_t
137
py_hashentry_t_hash_name(const void *key) {
138
return _Py_HashBytes(key, strlen((const char *)key));
139
}
140
141
static int
142
py_hashentry_t_compare_name(const void *key1, const void *key2) {
143
return strcmp((const char *)key1, (const char *)key2) == 0;
144
}
145
146
static void
147
py_hashentry_t_destroy_value(void *entry) {
148
py_hashentry_t *h = (py_hashentry_t *)entry;
149
if (--(h->refcnt) == 0) {
150
if (h->evp != NULL) {
151
PY_EVP_MD_free(h->evp);
152
h->evp = NULL;
153
}
154
if (h->evp_nosecurity != NULL) {
155
PY_EVP_MD_free(h->evp_nosecurity);
156
h->evp_nosecurity = NULL;
157
}
158
PyMem_Free(entry);
159
}
160
}
161
162
static _Py_hashtable_t *
163
py_hashentry_table_new(void) {
164
_Py_hashtable_t *ht = _Py_hashtable_new_full(
165
py_hashentry_t_hash_name,
166
py_hashentry_t_compare_name,
167
NULL,
168
py_hashentry_t_destroy_value,
169
NULL
170
);
171
if (ht == NULL) {
172
return NULL;
173
}
174
175
for (const py_hashentry_t *h = py_hashes; h->py_name != NULL; h++) {
176
py_hashentry_t *entry = (py_hashentry_t *)PyMem_Malloc(sizeof(py_hashentry_t));
177
if (entry == NULL) {
178
goto error;
179
}
180
memcpy(entry, h, sizeof(py_hashentry_t));
181
182
if (_Py_hashtable_set(ht, (const void*)entry->py_name, (void*)entry) < 0) {
183
PyMem_Free(entry);
184
goto error;
185
}
186
entry->refcnt = 1;
187
188
if (h->py_alias != NULL) {
189
if (_Py_hashtable_set(ht, (const void*)entry->py_alias, (void*)entry) < 0) {
190
PyMem_Free(entry);
191
goto error;
192
}
193
entry->refcnt++;
194
}
195
}
196
197
return ht;
198
error:
199
_Py_hashtable_destroy(ht);
200
return NULL;
201
}
202
203
/* Module state */
204
static PyModuleDef _hashlibmodule;
205
206
typedef struct {
207
PyTypeObject *EVPtype;
208
PyTypeObject *HMACtype;
209
#ifdef PY_OPENSSL_HAS_SHAKE
210
PyTypeObject *EVPXOFtype;
211
#endif
212
PyObject *constructs;
213
PyObject *unsupported_digestmod_error;
214
_Py_hashtable_t *hashtable;
215
} _hashlibstate;
216
217
static inline _hashlibstate*
218
get_hashlib_state(PyObject *module)
219
{
220
void *state = PyModule_GetState(module);
221
assert(state != NULL);
222
return (_hashlibstate *)state;
223
}
224
225
typedef struct {
226
PyObject_HEAD
227
EVP_MD_CTX *ctx; /* OpenSSL message digest context */
228
// Prevents undefined behavior via multiple threads entering the C API.
229
// The lock will be NULL before threaded access has been enabled.
230
PyThread_type_lock lock; /* OpenSSL context lock */
231
} EVPobject;
232
233
typedef struct {
234
PyObject_HEAD
235
HMAC_CTX *ctx; /* OpenSSL hmac context */
236
// Prevents undefined behavior via multiple threads entering the C API.
237
// The lock will be NULL before threaded access has been enabled.
238
PyThread_type_lock lock; /* HMAC context lock */
239
} HMACobject;
240
241
#include "clinic/_hashopenssl.c.h"
242
/*[clinic input]
243
module _hashlib
244
class _hashlib.HASH "EVPobject *" "((_hashlibstate *)PyModule_GetState(module))->EVPtype"
245
class _hashlib.HASHXOF "EVPobject *" "((_hashlibstate *)PyModule_GetState(module))->EVPXOFtype"
246
class _hashlib.HMAC "HMACobject *" "((_hashlibstate *)PyModule_GetState(module))->HMACtype"
247
[clinic start generated code]*/
248
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7df1bcf6f75cb8ef]*/
249
250
251
/* LCOV_EXCL_START */
252
static PyObject *
253
_setException(PyObject *exc, const char* altmsg, ...)
254
{
255
unsigned long errcode = ERR_peek_last_error();
256
const char *lib, *func, *reason;
257
va_list vargs;
258
259
va_start(vargs, altmsg);
260
if (!errcode) {
261
if (altmsg == NULL) {
262
PyErr_SetString(exc, "no reason supplied");
263
} else {
264
PyErr_FormatV(exc, altmsg, vargs);
265
}
266
va_end(vargs);
267
return NULL;
268
}
269
va_end(vargs);
270
ERR_clear_error();
271
272
lib = ERR_lib_error_string(errcode);
273
func = ERR_func_error_string(errcode);
274
reason = ERR_reason_error_string(errcode);
275
276
if (lib && func) {
277
PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
278
}
279
else if (lib) {
280
PyErr_Format(exc, "[%s] %s", lib, reason);
281
}
282
else {
283
PyErr_SetString(exc, reason);
284
}
285
return NULL;
286
}
287
/* LCOV_EXCL_STOP */
288
289
static PyObject*
290
py_digest_name(const EVP_MD *md)
291
{
292
int nid = EVP_MD_nid(md);
293
const char *name = NULL;
294
const py_hashentry_t *h;
295
296
for (h = py_hashes; h->py_name != NULL; h++) {
297
if (h->ossl_nid == nid) {
298
name = h->py_name;
299
break;
300
}
301
}
302
if (name == NULL) {
303
/* Ignore aliased names and only use long, lowercase name. The aliases
304
* pollute the list and OpenSSL appears to have its own definition of
305
* alias as the resulting list still contains duplicate and alternate
306
* names for several algorithms.
307
*/
308
name = OBJ_nid2ln(nid);
309
if (name == NULL)
310
name = OBJ_nid2sn(nid);
311
}
312
313
return PyUnicode_FromString(name);
314
}
315
316
/* Get EVP_MD by HID and purpose */
317
static PY_EVP_MD*
318
py_digest_by_name(PyObject *module, const char *name, enum Py_hash_type py_ht)
319
{
320
PY_EVP_MD *digest = NULL;
321
_hashlibstate *state = get_hashlib_state(module);
322
py_hashentry_t *entry = (py_hashentry_t *)_Py_hashtable_get(
323
state->hashtable, (const void*)name
324
);
325
326
if (entry != NULL) {
327
switch (py_ht) {
328
case Py_ht_evp:
329
case Py_ht_mac:
330
case Py_ht_pbkdf2:
331
if (entry->evp == NULL) {
332
entry->evp = PY_EVP_MD_fetch(entry->ossl_name, NULL);
333
}
334
digest = entry->evp;
335
break;
336
case Py_ht_evp_nosecurity:
337
if (entry->evp_nosecurity == NULL) {
338
entry->evp_nosecurity = PY_EVP_MD_fetch(entry->ossl_name, "-fips");
339
}
340
digest = entry->evp_nosecurity;
341
break;
342
}
343
if (digest != NULL) {
344
PY_EVP_MD_up_ref(digest);
345
}
346
} else {
347
// Fall back for looking up an unindexed OpenSSL specific name.
348
switch (py_ht) {
349
case Py_ht_evp:
350
case Py_ht_mac:
351
case Py_ht_pbkdf2:
352
digest = PY_EVP_MD_fetch(name, NULL);
353
break;
354
case Py_ht_evp_nosecurity:
355
digest = PY_EVP_MD_fetch(name, "-fips");
356
break;
357
}
358
}
359
if (digest == NULL) {
360
_setException(state->unsupported_digestmod_error, "unsupported hash type %s", name);
361
return NULL;
362
}
363
return digest;
364
}
365
366
/* Get digest EVP from object
367
*
368
* * string
369
* * _hashopenssl builtin function
370
*
371
* on error returns NULL with exception set.
372
*/
373
static PY_EVP_MD*
374
py_digest_by_digestmod(PyObject *module, PyObject *digestmod, enum Py_hash_type py_ht) {
375
PY_EVP_MD* evp;
376
PyObject *name_obj = NULL;
377
const char *name;
378
379
if (PyUnicode_Check(digestmod)) {
380
name_obj = digestmod;
381
} else {
382
_hashlibstate *state = get_hashlib_state(module);
383
// borrowed ref
384
name_obj = PyDict_GetItemWithError(state->constructs, digestmod);
385
}
386
if (name_obj == NULL) {
387
if (!PyErr_Occurred()) {
388
_hashlibstate *state = get_hashlib_state(module);
389
PyErr_Format(
390
state->unsupported_digestmod_error,
391
"Unsupported digestmod %R", digestmod);
392
}
393
return NULL;
394
}
395
396
name = PyUnicode_AsUTF8(name_obj);
397
if (name == NULL) {
398
return NULL;
399
}
400
401
evp = py_digest_by_name(module, name, py_ht);
402
if (evp == NULL) {
403
return NULL;
404
}
405
406
return evp;
407
}
408
409
static EVPobject *
410
newEVPobject(PyTypeObject *type)
411
{
412
EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, type);
413
if (retval == NULL) {
414
return NULL;
415
}
416
417
retval->lock = NULL;
418
419
retval->ctx = EVP_MD_CTX_new();
420
if (retval->ctx == NULL) {
421
Py_DECREF(retval);
422
PyErr_NoMemory();
423
return NULL;
424
}
425
426
return retval;
427
}
428
429
static int
430
EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
431
{
432
unsigned int process;
433
const unsigned char *cp = (const unsigned char *)vp;
434
while (0 < len) {
435
if (len > (Py_ssize_t)MUNCH_SIZE)
436
process = MUNCH_SIZE;
437
else
438
process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
439
if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
440
_setException(PyExc_ValueError, NULL);
441
return -1;
442
}
443
len -= process;
444
cp += process;
445
}
446
return 0;
447
}
448
449
/* Internal methods for a hash object */
450
451
static void
452
EVP_dealloc(EVPobject *self)
453
{
454
PyTypeObject *tp = Py_TYPE(self);
455
if (self->lock != NULL)
456
PyThread_free_lock(self->lock);
457
EVP_MD_CTX_free(self->ctx);
458
PyObject_Free(self);
459
Py_DECREF(tp);
460
}
461
462
static int
463
locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
464
{
465
int result;
466
ENTER_HASHLIB(self);
467
result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
468
LEAVE_HASHLIB(self);
469
return result;
470
}
471
472
/* External methods for a hash object */
473
474
/*[clinic input]
475
_hashlib.HASH.copy as EVP_copy
476
477
Return a copy of the hash object.
478
[clinic start generated code]*/
479
480
static PyObject *
481
EVP_copy_impl(EVPobject *self)
482
/*[clinic end generated code: output=b370c21cdb8ca0b4 input=31455b6a3e638069]*/
483
{
484
EVPobject *newobj;
485
486
if ((newobj = newEVPobject(Py_TYPE(self))) == NULL)
487
return NULL;
488
489
if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
490
Py_DECREF(newobj);
491
return _setException(PyExc_ValueError, NULL);
492
}
493
return (PyObject *)newobj;
494
}
495
496
/*[clinic input]
497
_hashlib.HASH.digest as EVP_digest
498
499
Return the digest value as a bytes object.
500
[clinic start generated code]*/
501
502
static PyObject *
503
EVP_digest_impl(EVPobject *self)
504
/*[clinic end generated code: output=0f6a3a0da46dc12d input=03561809a419bf00]*/
505
{
506
unsigned char digest[EVP_MAX_MD_SIZE];
507
EVP_MD_CTX *temp_ctx;
508
PyObject *retval;
509
unsigned int digest_size;
510
511
temp_ctx = EVP_MD_CTX_new();
512
if (temp_ctx == NULL) {
513
PyErr_NoMemory();
514
return NULL;
515
}
516
517
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
518
return _setException(PyExc_ValueError, NULL);
519
}
520
digest_size = EVP_MD_CTX_size(temp_ctx);
521
if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
522
_setException(PyExc_ValueError, NULL);
523
return NULL;
524
}
525
526
retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
527
EVP_MD_CTX_free(temp_ctx);
528
return retval;
529
}
530
531
/*[clinic input]
532
_hashlib.HASH.hexdigest as EVP_hexdigest
533
534
Return the digest value as a string of hexadecimal digits.
535
[clinic start generated code]*/
536
537
static PyObject *
538
EVP_hexdigest_impl(EVPobject *self)
539
/*[clinic end generated code: output=18e6decbaf197296 input=aff9cf0e4c741a9a]*/
540
{
541
unsigned char digest[EVP_MAX_MD_SIZE];
542
EVP_MD_CTX *temp_ctx;
543
unsigned int digest_size;
544
545
temp_ctx = EVP_MD_CTX_new();
546
if (temp_ctx == NULL) {
547
PyErr_NoMemory();
548
return NULL;
549
}
550
551
/* Get the raw (binary) digest value */
552
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
553
return _setException(PyExc_ValueError, NULL);
554
}
555
digest_size = EVP_MD_CTX_size(temp_ctx);
556
if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
557
_setException(PyExc_ValueError, NULL);
558
return NULL;
559
}
560
561
EVP_MD_CTX_free(temp_ctx);
562
563
return _Py_strhex((const char *)digest, (Py_ssize_t)digest_size);
564
}
565
566
/*[clinic input]
567
_hashlib.HASH.update as EVP_update
568
569
obj: object
570
/
571
572
Update this hash object's state with the provided string.
573
[clinic start generated code]*/
574
575
static PyObject *
576
EVP_update(EVPobject *self, PyObject *obj)
577
/*[clinic end generated code: output=ec1d55ed2432e966 input=9b30ec848f015501]*/
578
{
579
int result;
580
Py_buffer view;
581
582
GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
583
584
if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
585
self->lock = PyThread_allocate_lock();
586
/* fail? lock = NULL and we fail over to non-threaded code. */
587
}
588
589
if (self->lock != NULL) {
590
Py_BEGIN_ALLOW_THREADS
591
PyThread_acquire_lock(self->lock, 1);
592
result = EVP_hash(self, view.buf, view.len);
593
PyThread_release_lock(self->lock);
594
Py_END_ALLOW_THREADS
595
} else {
596
result = EVP_hash(self, view.buf, view.len);
597
}
598
599
PyBuffer_Release(&view);
600
601
if (result == -1)
602
return NULL;
603
Py_RETURN_NONE;
604
}
605
606
static PyMethodDef EVP_methods[] = {
607
EVP_UPDATE_METHODDEF
608
EVP_DIGEST_METHODDEF
609
EVP_HEXDIGEST_METHODDEF
610
EVP_COPY_METHODDEF
611
{NULL, NULL} /* sentinel */
612
};
613
614
static PyObject *
615
EVP_get_block_size(EVPobject *self, void *closure)
616
{
617
long block_size;
618
block_size = EVP_MD_CTX_block_size(self->ctx);
619
return PyLong_FromLong(block_size);
620
}
621
622
static PyObject *
623
EVP_get_digest_size(EVPobject *self, void *closure)
624
{
625
long size;
626
size = EVP_MD_CTX_size(self->ctx);
627
return PyLong_FromLong(size);
628
}
629
630
static PyObject *
631
EVP_get_name(EVPobject *self, void *closure)
632
{
633
return py_digest_name(EVP_MD_CTX_md(self->ctx));
634
}
635
636
static PyGetSetDef EVP_getseters[] = {
637
{"digest_size",
638
(getter)EVP_get_digest_size, NULL,
639
NULL,
640
NULL},
641
{"block_size",
642
(getter)EVP_get_block_size, NULL,
643
NULL,
644
NULL},
645
{"name",
646
(getter)EVP_get_name, NULL,
647
NULL,
648
PyDoc_STR("algorithm name.")},
649
{NULL} /* Sentinel */
650
};
651
652
653
static PyObject *
654
EVP_repr(EVPobject *self)
655
{
656
PyObject *name_obj, *repr;
657
name_obj = py_digest_name(EVP_MD_CTX_md(self->ctx));
658
if (!name_obj) {
659
return NULL;
660
}
661
repr = PyUnicode_FromFormat("<%U %s object @ %p>",
662
name_obj, Py_TYPE(self)->tp_name, self);
663
Py_DECREF(name_obj);
664
return repr;
665
}
666
667
PyDoc_STRVAR(hashtype_doc,
668
"HASH(name, string=b\'\')\n"
669
"--\n"
670
"\n"
671
"A hash is an object used to calculate a checksum of a string of information.\n"
672
"\n"
673
"Methods:\n"
674
"\n"
675
"update() -- updates the current digest with an additional string\n"
676
"digest() -- return the current digest value\n"
677
"hexdigest() -- return the current digest as a string of hexadecimal digits\n"
678
"copy() -- return a copy of the current hash object\n"
679
"\n"
680
"Attributes:\n"
681
"\n"
682
"name -- the hash algorithm being used by this object\n"
683
"digest_size -- number of bytes in this hashes output");
684
685
static PyType_Slot EVPtype_slots[] = {
686
{Py_tp_dealloc, EVP_dealloc},
687
{Py_tp_repr, EVP_repr},
688
{Py_tp_doc, (char *)hashtype_doc},
689
{Py_tp_methods, EVP_methods},
690
{Py_tp_getset, EVP_getseters},
691
{0, 0},
692
};
693
694
static PyType_Spec EVPtype_spec = {
695
"_hashlib.HASH", /*tp_name*/
696
sizeof(EVPobject), /*tp_basicsize*/
697
0, /*tp_itemsize*/
698
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
699
EVPtype_slots
700
};
701
702
#ifdef PY_OPENSSL_HAS_SHAKE
703
704
/*[clinic input]
705
_hashlib.HASHXOF.digest as EVPXOF_digest
706
707
length: Py_ssize_t
708
709
Return the digest value as a bytes object.
710
[clinic start generated code]*/
711
712
static PyObject *
713
EVPXOF_digest_impl(EVPobject *self, Py_ssize_t length)
714
/*[clinic end generated code: output=ef9320c23280efad input=816a6537cea3d1db]*/
715
{
716
EVP_MD_CTX *temp_ctx;
717
PyObject *retval = PyBytes_FromStringAndSize(NULL, length);
718
719
if (retval == NULL) {
720
return NULL;
721
}
722
723
temp_ctx = EVP_MD_CTX_new();
724
if (temp_ctx == NULL) {
725
Py_DECREF(retval);
726
PyErr_NoMemory();
727
return NULL;
728
}
729
730
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
731
Py_DECREF(retval);
732
EVP_MD_CTX_free(temp_ctx);
733
return _setException(PyExc_ValueError, NULL);
734
}
735
if (!EVP_DigestFinalXOF(temp_ctx,
736
(unsigned char*)PyBytes_AS_STRING(retval),
737
length)) {
738
Py_DECREF(retval);
739
EVP_MD_CTX_free(temp_ctx);
740
_setException(PyExc_ValueError, NULL);
741
return NULL;
742
}
743
744
EVP_MD_CTX_free(temp_ctx);
745
return retval;
746
}
747
748
/*[clinic input]
749
_hashlib.HASHXOF.hexdigest as EVPXOF_hexdigest
750
751
length: Py_ssize_t
752
753
Return the digest value as a string of hexadecimal digits.
754
[clinic start generated code]*/
755
756
static PyObject *
757
EVPXOF_hexdigest_impl(EVPobject *self, Py_ssize_t length)
758
/*[clinic end generated code: output=eb3e6ee7788bf5b2 input=5f9d6a8f269e34df]*/
759
{
760
unsigned char *digest;
761
EVP_MD_CTX *temp_ctx;
762
PyObject *retval;
763
764
digest = (unsigned char*)PyMem_Malloc(length);
765
if (digest == NULL) {
766
PyErr_NoMemory();
767
return NULL;
768
}
769
770
temp_ctx = EVP_MD_CTX_new();
771
if (temp_ctx == NULL) {
772
PyMem_Free(digest);
773
PyErr_NoMemory();
774
return NULL;
775
}
776
777
/* Get the raw (binary) digest value */
778
if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
779
PyMem_Free(digest);
780
EVP_MD_CTX_free(temp_ctx);
781
return _setException(PyExc_ValueError, NULL);
782
}
783
if (!EVP_DigestFinalXOF(temp_ctx, digest, length)) {
784
PyMem_Free(digest);
785
EVP_MD_CTX_free(temp_ctx);
786
_setException(PyExc_ValueError, NULL);
787
return NULL;
788
}
789
790
EVP_MD_CTX_free(temp_ctx);
791
792
retval = _Py_strhex((const char *)digest, length);
793
PyMem_Free(digest);
794
return retval;
795
}
796
797
static PyMethodDef EVPXOF_methods[] = {
798
EVPXOF_DIGEST_METHODDEF
799
EVPXOF_HEXDIGEST_METHODDEF
800
{NULL, NULL} /* sentinel */
801
};
802
803
804
static PyObject *
805
EVPXOF_get_digest_size(EVPobject *self, void *closure)
806
{
807
return PyLong_FromLong(0);
808
}
809
810
static PyGetSetDef EVPXOF_getseters[] = {
811
{"digest_size",
812
(getter)EVPXOF_get_digest_size, NULL,
813
NULL,
814
NULL},
815
{NULL} /* Sentinel */
816
};
817
818
PyDoc_STRVAR(hashxoftype_doc,
819
"HASHXOF(name, string=b\'\')\n"
820
"--\n"
821
"\n"
822
"A hash is an object used to calculate a checksum of a string of information.\n"
823
"\n"
824
"Methods:\n"
825
"\n"
826
"update() -- updates the current digest with an additional string\n"
827
"digest(length) -- return the current digest value\n"
828
"hexdigest(length) -- return the current digest as a string of hexadecimal digits\n"
829
"copy() -- return a copy of the current hash object\n"
830
"\n"
831
"Attributes:\n"
832
"\n"
833
"name -- the hash algorithm being used by this object\n"
834
"digest_size -- number of bytes in this hashes output");
835
836
static PyType_Slot EVPXOFtype_slots[] = {
837
{Py_tp_doc, (char *)hashxoftype_doc},
838
{Py_tp_methods, EVPXOF_methods},
839
{Py_tp_getset, EVPXOF_getseters},
840
{0, 0},
841
};
842
843
static PyType_Spec EVPXOFtype_spec = {
844
"_hashlib.HASHXOF", /*tp_name*/
845
sizeof(EVPobject), /*tp_basicsize*/
846
0, /*tp_itemsize*/
847
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
848
EVPXOFtype_slots
849
};
850
851
852
#endif
853
854
static PyObject*
855
py_evp_fromname(PyObject *module, const char *digestname, PyObject *data_obj,
856
int usedforsecurity)
857
{
858
Py_buffer view = { 0 };
859
PY_EVP_MD *digest = NULL;
860
PyTypeObject *type;
861
EVPobject *self = NULL;
862
863
if (data_obj != NULL) {
864
GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
865
}
866
867
digest = py_digest_by_name(
868
module, digestname, usedforsecurity ? Py_ht_evp : Py_ht_evp_nosecurity
869
);
870
if (digest == NULL) {
871
goto exit;
872
}
873
874
if ((EVP_MD_flags(digest) & EVP_MD_FLAG_XOF) == EVP_MD_FLAG_XOF) {
875
type = get_hashlib_state(module)->EVPXOFtype;
876
} else {
877
type = get_hashlib_state(module)->EVPtype;
878
}
879
880
self = newEVPobject(type);
881
if (self == NULL) {
882
goto exit;
883
}
884
885
#if defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW) && OPENSSL_VERSION_NUMBER < 0x30000000L
886
// In OpenSSL 1.1.1 the non FIPS allowed flag is context specific while
887
// in 3.0.0 it is a different EVP_MD provider.
888
if (!usedforsecurity) {
889
EVP_MD_CTX_set_flags(self->ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
890
}
891
#endif
892
893
int result = EVP_DigestInit_ex(self->ctx, digest, NULL);
894
if (!result) {
895
_setException(PyExc_ValueError, NULL);
896
Py_CLEAR(self);
897
goto exit;
898
}
899
900
if (view.buf && view.len) {
901
if (view.len >= HASHLIB_GIL_MINSIZE) {
902
/* We do not initialize self->lock here as this is the constructor
903
* where it is not yet possible to have concurrent access. */
904
Py_BEGIN_ALLOW_THREADS
905
result = EVP_hash(self, view.buf, view.len);
906
Py_END_ALLOW_THREADS
907
} else {
908
result = EVP_hash(self, view.buf, view.len);
909
}
910
if (result == -1) {
911
Py_CLEAR(self);
912
goto exit;
913
}
914
}
915
916
exit:
917
if (data_obj != NULL) {
918
PyBuffer_Release(&view);
919
}
920
if (digest != NULL) {
921
PY_EVP_MD_free(digest);
922
}
923
924
return (PyObject *)self;
925
}
926
927
928
/* The module-level function: new() */
929
930
/*[clinic input]
931
_hashlib.new as EVP_new
932
933
name as name_obj: object
934
string as data_obj: object(c_default="NULL") = b''
935
*
936
usedforsecurity: bool = True
937
938
Return a new hash object using the named algorithm.
939
940
An optional string argument may be provided and will be
941
automatically hashed.
942
943
The MD5 and SHA1 algorithms are always supported.
944
[clinic start generated code]*/
945
946
static PyObject *
947
EVP_new_impl(PyObject *module, PyObject *name_obj, PyObject *data_obj,
948
int usedforsecurity)
949
/*[clinic end generated code: output=ddd5053f92dffe90 input=c24554d0337be1b0]*/
950
{
951
char *name;
952
if (!PyArg_Parse(name_obj, "s", &name)) {
953
PyErr_SetString(PyExc_TypeError, "name must be a string");
954
return NULL;
955
}
956
return py_evp_fromname(module, name, data_obj, usedforsecurity);
957
}
958
959
960
/*[clinic input]
961
_hashlib.openssl_md5
962
963
string as data_obj: object(py_default="b''") = NULL
964
*
965
usedforsecurity: bool = True
966
967
Returns a md5 hash object; optionally initialized with a string
968
969
[clinic start generated code]*/
970
971
static PyObject *
972
_hashlib_openssl_md5_impl(PyObject *module, PyObject *data_obj,
973
int usedforsecurity)
974
/*[clinic end generated code: output=87b0186440a44f8c input=990e36d5e689b16e]*/
975
{
976
return py_evp_fromname(module, Py_hash_md5, data_obj, usedforsecurity);
977
}
978
979
980
/*[clinic input]
981
_hashlib.openssl_sha1
982
983
string as data_obj: object(py_default="b''") = NULL
984
*
985
usedforsecurity: bool = True
986
987
Returns a sha1 hash object; optionally initialized with a string
988
989
[clinic start generated code]*/
990
991
static PyObject *
992
_hashlib_openssl_sha1_impl(PyObject *module, PyObject *data_obj,
993
int usedforsecurity)
994
/*[clinic end generated code: output=6813024cf690670d input=948f2f4b6deabc10]*/
995
{
996
return py_evp_fromname(module, Py_hash_sha1, data_obj, usedforsecurity);
997
}
998
999
1000
/*[clinic input]
1001
_hashlib.openssl_sha224
1002
1003
string as data_obj: object(py_default="b''") = NULL
1004
*
1005
usedforsecurity: bool = True
1006
1007
Returns a sha224 hash object; optionally initialized with a string
1008
1009
[clinic start generated code]*/
1010
1011
static PyObject *
1012
_hashlib_openssl_sha224_impl(PyObject *module, PyObject *data_obj,
1013
int usedforsecurity)
1014
/*[clinic end generated code: output=a2dfe7cc4eb14ebb input=f9272821fadca505]*/
1015
{
1016
return py_evp_fromname(module, Py_hash_sha224, data_obj, usedforsecurity);
1017
}
1018
1019
1020
/*[clinic input]
1021
_hashlib.openssl_sha256
1022
1023
string as data_obj: object(py_default="b''") = NULL
1024
*
1025
usedforsecurity: bool = True
1026
1027
Returns a sha256 hash object; optionally initialized with a string
1028
1029
[clinic start generated code]*/
1030
1031
static PyObject *
1032
_hashlib_openssl_sha256_impl(PyObject *module, PyObject *data_obj,
1033
int usedforsecurity)
1034
/*[clinic end generated code: output=1f874a34870f0a68 input=549fad9d2930d4c5]*/
1035
{
1036
return py_evp_fromname(module, Py_hash_sha256, data_obj, usedforsecurity);
1037
}
1038
1039
1040
/*[clinic input]
1041
_hashlib.openssl_sha384
1042
1043
string as data_obj: object(py_default="b''") = NULL
1044
*
1045
usedforsecurity: bool = True
1046
1047
Returns a sha384 hash object; optionally initialized with a string
1048
1049
[clinic start generated code]*/
1050
1051
static PyObject *
1052
_hashlib_openssl_sha384_impl(PyObject *module, PyObject *data_obj,
1053
int usedforsecurity)
1054
/*[clinic end generated code: output=58529eff9ca457b2 input=48601a6e3bf14ad7]*/
1055
{
1056
return py_evp_fromname(module, Py_hash_sha384, data_obj, usedforsecurity);
1057
}
1058
1059
1060
/*[clinic input]
1061
_hashlib.openssl_sha512
1062
1063
string as data_obj: object(py_default="b''") = NULL
1064
*
1065
usedforsecurity: bool = True
1066
1067
Returns a sha512 hash object; optionally initialized with a string
1068
1069
[clinic start generated code]*/
1070
1071
static PyObject *
1072
_hashlib_openssl_sha512_impl(PyObject *module, PyObject *data_obj,
1073
int usedforsecurity)
1074
/*[clinic end generated code: output=2c744c9e4a40d5f6 input=c5c46a2a817aa98f]*/
1075
{
1076
return py_evp_fromname(module, Py_hash_sha512, data_obj, usedforsecurity);
1077
}
1078
1079
1080
#ifdef PY_OPENSSL_HAS_SHA3
1081
1082
/*[clinic input]
1083
_hashlib.openssl_sha3_224
1084
1085
string as data_obj: object(py_default="b''") = NULL
1086
*
1087
usedforsecurity: bool = True
1088
1089
Returns a sha3-224 hash object; optionally initialized with a string
1090
1091
[clinic start generated code]*/
1092
1093
static PyObject *
1094
_hashlib_openssl_sha3_224_impl(PyObject *module, PyObject *data_obj,
1095
int usedforsecurity)
1096
/*[clinic end generated code: output=144641c1d144b974 input=e3a01b2888916157]*/
1097
{
1098
return py_evp_fromname(module, Py_hash_sha3_224, data_obj, usedforsecurity);
1099
}
1100
1101
/*[clinic input]
1102
_hashlib.openssl_sha3_256
1103
1104
string as data_obj: object(py_default="b''") = NULL
1105
*
1106
usedforsecurity: bool = True
1107
1108
Returns a sha3-256 hash object; optionally initialized with a string
1109
1110
[clinic start generated code]*/
1111
1112
static PyObject *
1113
_hashlib_openssl_sha3_256_impl(PyObject *module, PyObject *data_obj,
1114
int usedforsecurity)
1115
/*[clinic end generated code: output=c61f1ab772d06668 input=e2908126c1b6deed]*/
1116
{
1117
return py_evp_fromname(module, Py_hash_sha3_256, data_obj , usedforsecurity);
1118
}
1119
1120
/*[clinic input]
1121
_hashlib.openssl_sha3_384
1122
1123
string as data_obj: object(py_default="b''") = NULL
1124
*
1125
usedforsecurity: bool = True
1126
1127
Returns a sha3-384 hash object; optionally initialized with a string
1128
1129
[clinic start generated code]*/
1130
1131
static PyObject *
1132
_hashlib_openssl_sha3_384_impl(PyObject *module, PyObject *data_obj,
1133
int usedforsecurity)
1134
/*[clinic end generated code: output=f68e4846858cf0ee input=ec0edf5c792f8252]*/
1135
{
1136
return py_evp_fromname(module, Py_hash_sha3_384, data_obj , usedforsecurity);
1137
}
1138
1139
/*[clinic input]
1140
_hashlib.openssl_sha3_512
1141
1142
string as data_obj: object(py_default="b''") = NULL
1143
*
1144
usedforsecurity: bool = True
1145
1146
Returns a sha3-512 hash object; optionally initialized with a string
1147
1148
[clinic start generated code]*/
1149
1150
static PyObject *
1151
_hashlib_openssl_sha3_512_impl(PyObject *module, PyObject *data_obj,
1152
int usedforsecurity)
1153
/*[clinic end generated code: output=2eede478c159354a input=64e2cc0c094d56f4]*/
1154
{
1155
return py_evp_fromname(module, Py_hash_sha3_512, data_obj , usedforsecurity);
1156
}
1157
#endif /* PY_OPENSSL_HAS_SHA3 */
1158
1159
#ifdef PY_OPENSSL_HAS_SHAKE
1160
/*[clinic input]
1161
_hashlib.openssl_shake_128
1162
1163
string as data_obj: object(py_default="b''") = NULL
1164
*
1165
usedforsecurity: bool = True
1166
1167
Returns a shake-128 variable hash object; optionally initialized with a string
1168
1169
[clinic start generated code]*/
1170
1171
static PyObject *
1172
_hashlib_openssl_shake_128_impl(PyObject *module, PyObject *data_obj,
1173
int usedforsecurity)
1174
/*[clinic end generated code: output=bc49cdd8ada1fa97 input=6c9d67440eb33ec8]*/
1175
{
1176
return py_evp_fromname(module, Py_hash_shake_128, data_obj , usedforsecurity);
1177
}
1178
1179
/*[clinic input]
1180
_hashlib.openssl_shake_256
1181
1182
string as data_obj: object(py_default="b''") = NULL
1183
*
1184
usedforsecurity: bool = True
1185
1186
Returns a shake-256 variable hash object; optionally initialized with a string
1187
1188
[clinic start generated code]*/
1189
1190
static PyObject *
1191
_hashlib_openssl_shake_256_impl(PyObject *module, PyObject *data_obj,
1192
int usedforsecurity)
1193
/*[clinic end generated code: output=358d213be8852df7 input=479cbe9fefd4a9f8]*/
1194
{
1195
return py_evp_fromname(module, Py_hash_shake_256, data_obj , usedforsecurity);
1196
}
1197
#endif /* PY_OPENSSL_HAS_SHAKE */
1198
1199
/*[clinic input]
1200
_hashlib.pbkdf2_hmac as pbkdf2_hmac
1201
1202
hash_name: str
1203
password: Py_buffer
1204
salt: Py_buffer
1205
iterations: long
1206
dklen as dklen_obj: object = None
1207
1208
Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function.
1209
[clinic start generated code]*/
1210
1211
static PyObject *
1212
pbkdf2_hmac_impl(PyObject *module, const char *hash_name,
1213
Py_buffer *password, Py_buffer *salt, long iterations,
1214
PyObject *dklen_obj)
1215
/*[clinic end generated code: output=144b76005416599b input=ed3ab0d2d28b5d5c]*/
1216
{
1217
PyObject *key_obj = NULL;
1218
char *key;
1219
long dklen;
1220
int retval;
1221
1222
PY_EVP_MD *digest = py_digest_by_name(module, hash_name, Py_ht_pbkdf2);
1223
if (digest == NULL) {
1224
goto end;
1225
}
1226
1227
if (password->len > INT_MAX) {
1228
PyErr_SetString(PyExc_OverflowError,
1229
"password is too long.");
1230
goto end;
1231
}
1232
1233
if (salt->len > INT_MAX) {
1234
PyErr_SetString(PyExc_OverflowError,
1235
"salt is too long.");
1236
goto end;
1237
}
1238
1239
if (iterations < 1) {
1240
PyErr_SetString(PyExc_ValueError,
1241
"iteration value must be greater than 0.");
1242
goto end;
1243
}
1244
if (iterations > INT_MAX) {
1245
PyErr_SetString(PyExc_OverflowError,
1246
"iteration value is too great.");
1247
goto end;
1248
}
1249
1250
if (dklen_obj == Py_None) {
1251
dklen = EVP_MD_size(digest);
1252
} else {
1253
dklen = PyLong_AsLong(dklen_obj);
1254
if ((dklen == -1) && PyErr_Occurred()) {
1255
goto end;
1256
}
1257
}
1258
if (dklen < 1) {
1259
PyErr_SetString(PyExc_ValueError,
1260
"key length must be greater than 0.");
1261
goto end;
1262
}
1263
if (dklen > INT_MAX) {
1264
/* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
1265
PyErr_SetString(PyExc_OverflowError,
1266
"key length is too great.");
1267
goto end;
1268
}
1269
1270
key_obj = PyBytes_FromStringAndSize(NULL, dklen);
1271
if (key_obj == NULL) {
1272
goto end;
1273
}
1274
key = PyBytes_AS_STRING(key_obj);
1275
1276
Py_BEGIN_ALLOW_THREADS
1277
retval = PKCS5_PBKDF2_HMAC((char*)password->buf, (int)password->len,
1278
(unsigned char *)salt->buf, (int)salt->len,
1279
iterations, digest, dklen,
1280
(unsigned char *)key);
1281
Py_END_ALLOW_THREADS
1282
1283
if (!retval) {
1284
Py_CLEAR(key_obj);
1285
_setException(PyExc_ValueError, NULL);
1286
goto end;
1287
}
1288
1289
end:
1290
if (digest != NULL) {
1291
PY_EVP_MD_free(digest);
1292
}
1293
return key_obj;
1294
}
1295
1296
#ifdef PY_OPENSSL_HAS_SCRYPT
1297
1298
/* XXX: Parameters salt, n, r and p should be required keyword-only parameters.
1299
They are optional in the Argument Clinic declaration only due to a
1300
limitation of PyArg_ParseTupleAndKeywords. */
1301
1302
/*[clinic input]
1303
_hashlib.scrypt
1304
1305
password: Py_buffer
1306
*
1307
salt: Py_buffer = None
1308
n as n_obj: object(subclass_of='&PyLong_Type') = None
1309
r as r_obj: object(subclass_of='&PyLong_Type') = None
1310
p as p_obj: object(subclass_of='&PyLong_Type') = None
1311
maxmem: long = 0
1312
dklen: long = 64
1313
1314
1315
scrypt password-based key derivation function.
1316
[clinic start generated code]*/
1317
1318
static PyObject *
1319
_hashlib_scrypt_impl(PyObject *module, Py_buffer *password, Py_buffer *salt,
1320
PyObject *n_obj, PyObject *r_obj, PyObject *p_obj,
1321
long maxmem, long dklen)
1322
/*[clinic end generated code: output=14849e2aa2b7b46c input=48a7d63bf3f75c42]*/
1323
{
1324
PyObject *key_obj = NULL;
1325
char *key;
1326
int retval;
1327
unsigned long n, r, p;
1328
1329
if (password->len > INT_MAX) {
1330
PyErr_SetString(PyExc_OverflowError,
1331
"password is too long.");
1332
return NULL;
1333
}
1334
1335
if (salt->buf == NULL) {
1336
PyErr_SetString(PyExc_TypeError,
1337
"salt is required");
1338
return NULL;
1339
}
1340
if (salt->len > INT_MAX) {
1341
PyErr_SetString(PyExc_OverflowError,
1342
"salt is too long.");
1343
return NULL;
1344
}
1345
1346
n = PyLong_AsUnsignedLong(n_obj);
1347
if (n == (unsigned long) -1 && PyErr_Occurred()) {
1348
PyErr_SetString(PyExc_TypeError,
1349
"n is required and must be an unsigned int");
1350
return NULL;
1351
}
1352
if (n < 2 || n & (n - 1)) {
1353
PyErr_SetString(PyExc_ValueError,
1354
"n must be a power of 2.");
1355
return NULL;
1356
}
1357
1358
r = PyLong_AsUnsignedLong(r_obj);
1359
if (r == (unsigned long) -1 && PyErr_Occurred()) {
1360
PyErr_SetString(PyExc_TypeError,
1361
"r is required and must be an unsigned int");
1362
return NULL;
1363
}
1364
1365
p = PyLong_AsUnsignedLong(p_obj);
1366
if (p == (unsigned long) -1 && PyErr_Occurred()) {
1367
PyErr_SetString(PyExc_TypeError,
1368
"p is required and must be an unsigned int");
1369
return NULL;
1370
}
1371
1372
if (maxmem < 0 || maxmem > INT_MAX) {
1373
/* OpenSSL 1.1.0 restricts maxmem to 32 MiB. It may change in the
1374
future. The maxmem constant is private to OpenSSL. */
1375
PyErr_Format(PyExc_ValueError,
1376
"maxmem must be positive and smaller than %d",
1377
INT_MAX);
1378
return NULL;
1379
}
1380
1381
if (dklen < 1 || dklen > INT_MAX) {
1382
PyErr_Format(PyExc_ValueError,
1383
"dklen must be greater than 0 and smaller than %d",
1384
INT_MAX);
1385
return NULL;
1386
}
1387
1388
/* let OpenSSL validate the rest */
1389
retval = EVP_PBE_scrypt(NULL, 0, NULL, 0, n, r, p, maxmem, NULL, 0);
1390
if (!retval) {
1391
_setException(PyExc_ValueError, "Invalid parameter combination for n, r, p, maxmem.");
1392
return NULL;
1393
}
1394
1395
key_obj = PyBytes_FromStringAndSize(NULL, dklen);
1396
if (key_obj == NULL) {
1397
return NULL;
1398
}
1399
key = PyBytes_AS_STRING(key_obj);
1400
1401
Py_BEGIN_ALLOW_THREADS
1402
retval = EVP_PBE_scrypt(
1403
(const char*)password->buf, (size_t)password->len,
1404
(const unsigned char *)salt->buf, (size_t)salt->len,
1405
n, r, p, maxmem,
1406
(unsigned char *)key, (size_t)dklen
1407
);
1408
Py_END_ALLOW_THREADS
1409
1410
if (!retval) {
1411
Py_CLEAR(key_obj);
1412
_setException(PyExc_ValueError, NULL);
1413
return NULL;
1414
}
1415
return key_obj;
1416
}
1417
#endif /* PY_OPENSSL_HAS_SCRYPT */
1418
1419
/* Fast HMAC for hmac.digest()
1420
*/
1421
1422
/*[clinic input]
1423
_hashlib.hmac_digest as _hashlib_hmac_singleshot
1424
1425
key: Py_buffer
1426
msg: Py_buffer
1427
digest: object
1428
1429
Single-shot HMAC.
1430
[clinic start generated code]*/
1431
1432
static PyObject *
1433
_hashlib_hmac_singleshot_impl(PyObject *module, Py_buffer *key,
1434
Py_buffer *msg, PyObject *digest)
1435
/*[clinic end generated code: output=82f19965d12706ac input=0a0790cc3db45c2e]*/
1436
{
1437
unsigned char md[EVP_MAX_MD_SIZE] = {0};
1438
unsigned int md_len = 0;
1439
unsigned char *result;
1440
PY_EVP_MD *evp;
1441
1442
if (key->len > INT_MAX) {
1443
PyErr_SetString(PyExc_OverflowError,
1444
"key is too long.");
1445
return NULL;
1446
}
1447
if (msg->len > INT_MAX) {
1448
PyErr_SetString(PyExc_OverflowError,
1449
"msg is too long.");
1450
return NULL;
1451
}
1452
1453
evp = py_digest_by_digestmod(module, digest, Py_ht_mac);
1454
if (evp == NULL) {
1455
return NULL;
1456
}
1457
1458
Py_BEGIN_ALLOW_THREADS
1459
result = HMAC(
1460
evp,
1461
(const void*)key->buf, (int)key->len,
1462
(const unsigned char*)msg->buf, (int)msg->len,
1463
md, &md_len
1464
);
1465
Py_END_ALLOW_THREADS
1466
PY_EVP_MD_free(evp);
1467
1468
if (result == NULL) {
1469
_setException(PyExc_ValueError, NULL);
1470
return NULL;
1471
}
1472
return PyBytes_FromStringAndSize((const char*)md, md_len);
1473
}
1474
1475
/* OpenSSL-based HMAC implementation
1476
*/
1477
1478
static int _hmac_update(HMACobject*, PyObject*);
1479
1480
/*[clinic input]
1481
_hashlib.hmac_new
1482
1483
key: Py_buffer
1484
msg as msg_obj: object(c_default="NULL") = b''
1485
digestmod: object(c_default="NULL") = None
1486
1487
Return a new hmac object.
1488
[clinic start generated code]*/
1489
1490
static PyObject *
1491
_hashlib_hmac_new_impl(PyObject *module, Py_buffer *key, PyObject *msg_obj,
1492
PyObject *digestmod)
1493
/*[clinic end generated code: output=c20d9e4d9ed6d219 input=5f4071dcc7f34362]*/
1494
{
1495
PyTypeObject *type = get_hashlib_state(module)->HMACtype;
1496
PY_EVP_MD *digest;
1497
HMAC_CTX *ctx = NULL;
1498
HMACobject *self = NULL;
1499
int r;
1500
1501
if (key->len > INT_MAX) {
1502
PyErr_SetString(PyExc_OverflowError,
1503
"key is too long.");
1504
return NULL;
1505
}
1506
1507
if (digestmod == NULL) {
1508
PyErr_SetString(
1509
PyExc_TypeError, "Missing required parameter 'digestmod'.");
1510
return NULL;
1511
}
1512
1513
digest = py_digest_by_digestmod(module, digestmod, Py_ht_mac);
1514
if (digest == NULL) {
1515
return NULL;
1516
}
1517
1518
ctx = HMAC_CTX_new();
1519
if (ctx == NULL) {
1520
_setException(PyExc_ValueError, NULL);
1521
goto error;
1522
}
1523
1524
r = HMAC_Init_ex(
1525
ctx,
1526
(const char*)key->buf,
1527
(int)key->len,
1528
digest,
1529
NULL /*impl*/);
1530
PY_EVP_MD_free(digest);
1531
if (r == 0) {
1532
_setException(PyExc_ValueError, NULL);
1533
goto error;
1534
}
1535
1536
self = (HMACobject *)PyObject_New(HMACobject, type);
1537
if (self == NULL) {
1538
goto error;
1539
}
1540
1541
self->ctx = ctx;
1542
self->lock = NULL;
1543
1544
if ((msg_obj != NULL) && (msg_obj != Py_None)) {
1545
if (!_hmac_update(self, msg_obj))
1546
goto error;
1547
}
1548
1549
return (PyObject*)self;
1550
1551
error:
1552
if (ctx) HMAC_CTX_free(ctx);
1553
if (self) PyObject_Free(self);
1554
return NULL;
1555
}
1556
1557
/* helper functions */
1558
static int
1559
locked_HMAC_CTX_copy(HMAC_CTX *new_ctx_p, HMACobject *self)
1560
{
1561
int result;
1562
ENTER_HASHLIB(self);
1563
result = HMAC_CTX_copy(new_ctx_p, self->ctx);
1564
LEAVE_HASHLIB(self);
1565
return result;
1566
}
1567
1568
static unsigned int
1569
_hmac_digest_size(HMACobject *self)
1570
{
1571
unsigned int digest_size = EVP_MD_size(HMAC_CTX_get_md(self->ctx));
1572
assert(digest_size <= EVP_MAX_MD_SIZE);
1573
return digest_size;
1574
}
1575
1576
static int
1577
_hmac_update(HMACobject *self, PyObject *obj)
1578
{
1579
int r;
1580
Py_buffer view = {0};
1581
1582
GET_BUFFER_VIEW_OR_ERROR(obj, &view, return 0);
1583
1584
if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
1585
self->lock = PyThread_allocate_lock();
1586
/* fail? lock = NULL and we fail over to non-threaded code. */
1587
}
1588
1589
if (self->lock != NULL) {
1590
Py_BEGIN_ALLOW_THREADS
1591
PyThread_acquire_lock(self->lock, 1);
1592
r = HMAC_Update(self->ctx, (const unsigned char*)view.buf, view.len);
1593
PyThread_release_lock(self->lock);
1594
Py_END_ALLOW_THREADS
1595
} else {
1596
r = HMAC_Update(self->ctx, (const unsigned char*)view.buf, view.len);
1597
}
1598
1599
PyBuffer_Release(&view);
1600
1601
if (r == 0) {
1602
_setException(PyExc_ValueError, NULL);
1603
return 0;
1604
}
1605
return 1;
1606
}
1607
1608
/*[clinic input]
1609
_hashlib.HMAC.copy
1610
1611
Return a copy ("clone") of the HMAC object.
1612
[clinic start generated code]*/
1613
1614
static PyObject *
1615
_hashlib_HMAC_copy_impl(HMACobject *self)
1616
/*[clinic end generated code: output=29aa28b452833127 input=e2fa6a05db61a4d6]*/
1617
{
1618
HMACobject *retval;
1619
1620
HMAC_CTX *ctx = HMAC_CTX_new();
1621
if (ctx == NULL) {
1622
return _setException(PyExc_ValueError, NULL);
1623
}
1624
if (!locked_HMAC_CTX_copy(ctx, self)) {
1625
HMAC_CTX_free(ctx);
1626
return _setException(PyExc_ValueError, NULL);
1627
}
1628
1629
retval = (HMACobject *)PyObject_New(HMACobject, Py_TYPE(self));
1630
if (retval == NULL) {
1631
HMAC_CTX_free(ctx);
1632
return NULL;
1633
}
1634
retval->ctx = ctx;
1635
retval->lock = NULL;
1636
1637
return (PyObject *)retval;
1638
}
1639
1640
static void
1641
_hmac_dealloc(HMACobject *self)
1642
{
1643
PyTypeObject *tp = Py_TYPE(self);
1644
if (self->lock != NULL) {
1645
PyThread_free_lock(self->lock);
1646
}
1647
HMAC_CTX_free(self->ctx);
1648
PyObject_Free(self);
1649
Py_DECREF(tp);
1650
}
1651
1652
static PyObject *
1653
_hmac_repr(HMACobject *self)
1654
{
1655
PyObject *digest_name = py_digest_name(HMAC_CTX_get_md(self->ctx));
1656
if (digest_name == NULL) {
1657
return NULL;
1658
}
1659
PyObject *repr = PyUnicode_FromFormat(
1660
"<%U HMAC object @ %p>", digest_name, self
1661
);
1662
Py_DECREF(digest_name);
1663
return repr;
1664
}
1665
1666
/*[clinic input]
1667
_hashlib.HMAC.update
1668
msg: object
1669
1670
Update the HMAC object with msg.
1671
[clinic start generated code]*/
1672
1673
static PyObject *
1674
_hashlib_HMAC_update_impl(HMACobject *self, PyObject *msg)
1675
/*[clinic end generated code: output=f31f0ace8c625b00 input=1829173bb3cfd4e6]*/
1676
{
1677
if (!_hmac_update(self, msg)) {
1678
return NULL;
1679
}
1680
Py_RETURN_NONE;
1681
}
1682
1683
static int
1684
_hmac_digest(HMACobject *self, unsigned char *buf, unsigned int len)
1685
{
1686
HMAC_CTX *temp_ctx = HMAC_CTX_new();
1687
if (temp_ctx == NULL) {
1688
PyErr_NoMemory();
1689
return 0;
1690
}
1691
if (!locked_HMAC_CTX_copy(temp_ctx, self)) {
1692
_setException(PyExc_ValueError, NULL);
1693
return 0;
1694
}
1695
int r = HMAC_Final(temp_ctx, buf, &len);
1696
HMAC_CTX_free(temp_ctx);
1697
if (r == 0) {
1698
_setException(PyExc_ValueError, NULL);
1699
return 0;
1700
}
1701
return 1;
1702
}
1703
1704
/*[clinic input]
1705
_hashlib.HMAC.digest
1706
Return the digest of the bytes passed to the update() method so far.
1707
[clinic start generated code]*/
1708
1709
static PyObject *
1710
_hashlib_HMAC_digest_impl(HMACobject *self)
1711
/*[clinic end generated code: output=1b1424355af7a41e input=bff07f74da318fb4]*/
1712
{
1713
unsigned char digest[EVP_MAX_MD_SIZE];
1714
unsigned int digest_size = _hmac_digest_size(self);
1715
if (digest_size == 0) {
1716
return _setException(PyExc_ValueError, NULL);
1717
}
1718
int r = _hmac_digest(self, digest, digest_size);
1719
if (r == 0) {
1720
return NULL;
1721
}
1722
return PyBytes_FromStringAndSize((const char *)digest, digest_size);
1723
}
1724
1725
/*[clinic input]
1726
_hashlib.HMAC.hexdigest
1727
1728
Return hexadecimal digest of the bytes passed to the update() method so far.
1729
1730
This may be used to exchange the value safely in email or other non-binary
1731
environments.
1732
[clinic start generated code]*/
1733
1734
static PyObject *
1735
_hashlib_HMAC_hexdigest_impl(HMACobject *self)
1736
/*[clinic end generated code: output=80d825be1eaae6a7 input=5abc42702874ddcf]*/
1737
{
1738
unsigned char digest[EVP_MAX_MD_SIZE];
1739
unsigned int digest_size = _hmac_digest_size(self);
1740
if (digest_size == 0) {
1741
return _setException(PyExc_ValueError, NULL);
1742
}
1743
int r = _hmac_digest(self, digest, digest_size);
1744
if (r == 0) {
1745
return NULL;
1746
}
1747
return _Py_strhex((const char *)digest, digest_size);
1748
}
1749
1750
static PyObject *
1751
_hashlib_hmac_get_digest_size(HMACobject *self, void *closure)
1752
{
1753
unsigned int digest_size = _hmac_digest_size(self);
1754
if (digest_size == 0) {
1755
return _setException(PyExc_ValueError, NULL);
1756
}
1757
return PyLong_FromLong(digest_size);
1758
}
1759
1760
static PyObject *
1761
_hashlib_hmac_get_block_size(HMACobject *self, void *closure)
1762
{
1763
const EVP_MD *md = HMAC_CTX_get_md(self->ctx);
1764
if (md == NULL) {
1765
return _setException(PyExc_ValueError, NULL);
1766
}
1767
return PyLong_FromLong(EVP_MD_block_size(md));
1768
}
1769
1770
static PyObject *
1771
_hashlib_hmac_get_name(HMACobject *self, void *closure)
1772
{
1773
PyObject *digest_name = py_digest_name(HMAC_CTX_get_md(self->ctx));
1774
if (digest_name == NULL) {
1775
return NULL;
1776
}
1777
PyObject *name = PyUnicode_FromFormat("hmac-%U", digest_name);
1778
Py_DECREF(digest_name);
1779
return name;
1780
}
1781
1782
static PyMethodDef HMAC_methods[] = {
1783
_HASHLIB_HMAC_UPDATE_METHODDEF
1784
_HASHLIB_HMAC_DIGEST_METHODDEF
1785
_HASHLIB_HMAC_HEXDIGEST_METHODDEF
1786
_HASHLIB_HMAC_COPY_METHODDEF
1787
{NULL, NULL} /* sentinel */
1788
};
1789
1790
static PyGetSetDef HMAC_getset[] = {
1791
{"digest_size", (getter)_hashlib_hmac_get_digest_size, NULL, NULL, NULL},
1792
{"block_size", (getter)_hashlib_hmac_get_block_size, NULL, NULL, NULL},
1793
{"name", (getter)_hashlib_hmac_get_name, NULL, NULL, NULL},
1794
{NULL} /* Sentinel */
1795
};
1796
1797
1798
PyDoc_STRVAR(hmactype_doc,
1799
"The object used to calculate HMAC of a message.\n\
1800
\n\
1801
Methods:\n\
1802
\n\
1803
update() -- updates the current digest with an additional string\n\
1804
digest() -- return the current digest value\n\
1805
hexdigest() -- return the current digest as a string of hexadecimal digits\n\
1806
copy() -- return a copy of the current hash object\n\
1807
\n\
1808
Attributes:\n\
1809
\n\
1810
name -- the name, including the hash algorithm used by this object\n\
1811
digest_size -- number of bytes in digest() output\n");
1812
1813
static PyType_Slot HMACtype_slots[] = {
1814
{Py_tp_doc, (char *)hmactype_doc},
1815
{Py_tp_repr, (reprfunc)_hmac_repr},
1816
{Py_tp_dealloc,(destructor)_hmac_dealloc},
1817
{Py_tp_methods, HMAC_methods},
1818
{Py_tp_getset, HMAC_getset},
1819
{0, NULL}
1820
};
1821
1822
PyType_Spec HMACtype_spec = {
1823
"_hashlib.HMAC", /* name */
1824
sizeof(HMACobject), /* basicsize */
1825
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
1826
.slots = HMACtype_slots,
1827
};
1828
1829
1830
/* State for our callback function so that it can accumulate a result. */
1831
typedef struct _internal_name_mapper_state {
1832
PyObject *set;
1833
int error;
1834
} _InternalNameMapperState;
1835
1836
1837
/* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
1838
static void
1839
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1840
_openssl_hash_name_mapper(EVP_MD *md, void *arg)
1841
#else
1842
_openssl_hash_name_mapper(const EVP_MD *md, const char *from,
1843
const char *to, void *arg)
1844
#endif
1845
{
1846
_InternalNameMapperState *state = (_InternalNameMapperState *)arg;
1847
PyObject *py_name;
1848
1849
assert(state != NULL);
1850
// ignore all undefined providers
1851
if ((md == NULL) || (EVP_MD_nid(md) == NID_undef)) {
1852
return;
1853
}
1854
1855
py_name = py_digest_name(md);
1856
if (py_name == NULL) {
1857
state->error = 1;
1858
} else {
1859
if (PySet_Add(state->set, py_name) != 0) {
1860
state->error = 1;
1861
}
1862
Py_DECREF(py_name);
1863
}
1864
}
1865
1866
1867
/* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
1868
static int
1869
hashlib_md_meth_names(PyObject *module)
1870
{
1871
_InternalNameMapperState state = {
1872
.set = PyFrozenSet_New(NULL),
1873
.error = 0
1874
};
1875
if (state.set == NULL) {
1876
return -1;
1877
}
1878
1879
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1880
// get algorithms from all activated providers in default context
1881
EVP_MD_do_all_provided(NULL, &_openssl_hash_name_mapper, &state);
1882
#else
1883
EVP_MD_do_all(&_openssl_hash_name_mapper, &state);
1884
#endif
1885
1886
if (state.error) {
1887
Py_DECREF(state.set);
1888
return -1;
1889
}
1890
1891
if (PyModule_AddObject(module, "openssl_md_meth_names", state.set) < 0) {
1892
Py_DECREF(state.set);
1893
return -1;
1894
}
1895
1896
return 0;
1897
}
1898
1899
/*[clinic input]
1900
_hashlib.get_fips_mode -> int
1901
1902
Determine the OpenSSL FIPS mode of operation.
1903
1904
For OpenSSL 3.0.0 and newer it returns the state of the default provider
1905
in the default OSSL context. It's not quite the same as FIPS_mode() but good
1906
enough for unittests.
1907
1908
Effectively any non-zero return value indicates FIPS mode;
1909
values other than 1 may have additional significance.
1910
[clinic start generated code]*/
1911
1912
static int
1913
_hashlib_get_fips_mode_impl(PyObject *module)
1914
/*[clinic end generated code: output=87eece1bab4d3fa9 input=2db61538c41c6fef]*/
1915
1916
{
1917
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1918
return EVP_default_properties_is_fips_enabled(NULL);
1919
#else
1920
ERR_clear_error();
1921
int result = FIPS_mode();
1922
if (result == 0) {
1923
// "If the library was built without support of the FIPS Object Module,
1924
// then the function will return 0 with an error code of
1925
// CRYPTO_R_FIPS_MODE_NOT_SUPPORTED (0x0f06d065)."
1926
// But 0 is also a valid result value.
1927
unsigned long errcode = ERR_peek_last_error();
1928
if (errcode) {
1929
_setException(PyExc_ValueError, NULL);
1930
return -1;
1931
}
1932
}
1933
return result;
1934
#endif
1935
}
1936
1937
1938
static int
1939
_tscmp(const unsigned char *a, const unsigned char *b,
1940
Py_ssize_t len_a, Py_ssize_t len_b)
1941
{
1942
/* loop count depends on length of b. Might leak very little timing
1943
* information if sizes are different.
1944
*/
1945
Py_ssize_t length = len_b;
1946
const void *left = a;
1947
const void *right = b;
1948
int result = 0;
1949
1950
if (len_a != length) {
1951
left = b;
1952
result = 1;
1953
}
1954
1955
result |= CRYPTO_memcmp(left, right, length);
1956
1957
return (result == 0);
1958
}
1959
1960
/* NOTE: Keep in sync with _operator.c implementation. */
1961
1962
/*[clinic input]
1963
_hashlib.compare_digest
1964
1965
a: object
1966
b: object
1967
/
1968
1969
Return 'a == b'.
1970
1971
This function uses an approach designed to prevent
1972
timing analysis, making it appropriate for cryptography.
1973
1974
a and b must both be of the same type: either str (ASCII only),
1975
or any bytes-like object.
1976
1977
Note: If a and b are of different lengths, or if an error occurs,
1978
a timing attack could theoretically reveal information about the
1979
types and lengths of a and b--but not their values.
1980
[clinic start generated code]*/
1981
1982
static PyObject *
1983
_hashlib_compare_digest_impl(PyObject *module, PyObject *a, PyObject *b)
1984
/*[clinic end generated code: output=6f1c13927480aed9 input=9c40c6e566ca12f5]*/
1985
{
1986
int rc;
1987
1988
/* ASCII unicode string */
1989
if(PyUnicode_Check(a) && PyUnicode_Check(b)) {
1990
if (!PyUnicode_IS_ASCII(a) || !PyUnicode_IS_ASCII(b)) {
1991
PyErr_SetString(PyExc_TypeError,
1992
"comparing strings with non-ASCII characters is "
1993
"not supported");
1994
return NULL;
1995
}
1996
1997
rc = _tscmp(PyUnicode_DATA(a),
1998
PyUnicode_DATA(b),
1999
PyUnicode_GET_LENGTH(a),
2000
PyUnicode_GET_LENGTH(b));
2001
}
2002
/* fallback to buffer interface for bytes, bytearray and other */
2003
else {
2004
Py_buffer view_a;
2005
Py_buffer view_b;
2006
2007
if (PyObject_CheckBuffer(a) == 0 && PyObject_CheckBuffer(b) == 0) {
2008
PyErr_Format(PyExc_TypeError,
2009
"unsupported operand types(s) or combination of types: "
2010
"'%.100s' and '%.100s'",
2011
Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
2012
return NULL;
2013
}
2014
2015
if (PyObject_GetBuffer(a, &view_a, PyBUF_SIMPLE) == -1) {
2016
return NULL;
2017
}
2018
if (view_a.ndim > 1) {
2019
PyErr_SetString(PyExc_BufferError,
2020
"Buffer must be single dimension");
2021
PyBuffer_Release(&view_a);
2022
return NULL;
2023
}
2024
2025
if (PyObject_GetBuffer(b, &view_b, PyBUF_SIMPLE) == -1) {
2026
PyBuffer_Release(&view_a);
2027
return NULL;
2028
}
2029
if (view_b.ndim > 1) {
2030
PyErr_SetString(PyExc_BufferError,
2031
"Buffer must be single dimension");
2032
PyBuffer_Release(&view_a);
2033
PyBuffer_Release(&view_b);
2034
return NULL;
2035
}
2036
2037
rc = _tscmp((const unsigned char*)view_a.buf,
2038
(const unsigned char*)view_b.buf,
2039
view_a.len,
2040
view_b.len);
2041
2042
PyBuffer_Release(&view_a);
2043
PyBuffer_Release(&view_b);
2044
}
2045
2046
return PyBool_FromLong(rc);
2047
}
2048
2049
/* List of functions exported by this module */
2050
2051
static struct PyMethodDef EVP_functions[] = {
2052
EVP_NEW_METHODDEF
2053
PBKDF2_HMAC_METHODDEF
2054
_HASHLIB_SCRYPT_METHODDEF
2055
_HASHLIB_GET_FIPS_MODE_METHODDEF
2056
_HASHLIB_COMPARE_DIGEST_METHODDEF
2057
_HASHLIB_HMAC_SINGLESHOT_METHODDEF
2058
_HASHLIB_HMAC_NEW_METHODDEF
2059
_HASHLIB_OPENSSL_MD5_METHODDEF
2060
_HASHLIB_OPENSSL_SHA1_METHODDEF
2061
_HASHLIB_OPENSSL_SHA224_METHODDEF
2062
_HASHLIB_OPENSSL_SHA256_METHODDEF
2063
_HASHLIB_OPENSSL_SHA384_METHODDEF
2064
_HASHLIB_OPENSSL_SHA512_METHODDEF
2065
_HASHLIB_OPENSSL_SHA3_224_METHODDEF
2066
_HASHLIB_OPENSSL_SHA3_256_METHODDEF
2067
_HASHLIB_OPENSSL_SHA3_384_METHODDEF
2068
_HASHLIB_OPENSSL_SHA3_512_METHODDEF
2069
_HASHLIB_OPENSSL_SHAKE_128_METHODDEF
2070
_HASHLIB_OPENSSL_SHAKE_256_METHODDEF
2071
{NULL, NULL} /* Sentinel */
2072
};
2073
2074
2075
/* Initialize this module. */
2076
2077
static int
2078
hashlib_traverse(PyObject *m, visitproc visit, void *arg)
2079
{
2080
_hashlibstate *state = get_hashlib_state(m);
2081
Py_VISIT(state->EVPtype);
2082
Py_VISIT(state->HMACtype);
2083
#ifdef PY_OPENSSL_HAS_SHAKE
2084
Py_VISIT(state->EVPXOFtype);
2085
#endif
2086
Py_VISIT(state->constructs);
2087
Py_VISIT(state->unsupported_digestmod_error);
2088
return 0;
2089
}
2090
2091
static int
2092
hashlib_clear(PyObject *m)
2093
{
2094
_hashlibstate *state = get_hashlib_state(m);
2095
Py_CLEAR(state->EVPtype);
2096
Py_CLEAR(state->HMACtype);
2097
#ifdef PY_OPENSSL_HAS_SHAKE
2098
Py_CLEAR(state->EVPXOFtype);
2099
#endif
2100
Py_CLEAR(state->constructs);
2101
Py_CLEAR(state->unsupported_digestmod_error);
2102
2103
if (state->hashtable != NULL) {
2104
_Py_hashtable_destroy(state->hashtable);
2105
state->hashtable = NULL;
2106
}
2107
2108
return 0;
2109
}
2110
2111
static void
2112
hashlib_free(void *m)
2113
{
2114
hashlib_clear((PyObject *)m);
2115
}
2116
2117
/* Py_mod_exec functions */
2118
static int
2119
hashlib_init_hashtable(PyObject *module)
2120
{
2121
_hashlibstate *state = get_hashlib_state(module);
2122
2123
state->hashtable = py_hashentry_table_new();
2124
if (state->hashtable == NULL) {
2125
PyErr_NoMemory();
2126
return -1;
2127
}
2128
return 0;
2129
}
2130
2131
static int
2132
hashlib_init_evptype(PyObject *module)
2133
{
2134
_hashlibstate *state = get_hashlib_state(module);
2135
2136
state->EVPtype = (PyTypeObject *)PyType_FromSpec(&EVPtype_spec);
2137
if (state->EVPtype == NULL) {
2138
return -1;
2139
}
2140
if (PyModule_AddType(module, state->EVPtype) < 0) {
2141
return -1;
2142
}
2143
return 0;
2144
}
2145
2146
static int
2147
hashlib_init_evpxoftype(PyObject *module)
2148
{
2149
#ifdef PY_OPENSSL_HAS_SHAKE
2150
_hashlibstate *state = get_hashlib_state(module);
2151
2152
if (state->EVPtype == NULL) {
2153
return -1;
2154
}
2155
2156
state->EVPXOFtype = (PyTypeObject *)PyType_FromSpecWithBases(
2157
&EVPXOFtype_spec, (PyObject *)state->EVPtype
2158
);
2159
if (state->EVPXOFtype == NULL) {
2160
return -1;
2161
}
2162
if (PyModule_AddType(module, state->EVPXOFtype) < 0) {
2163
return -1;
2164
}
2165
#endif
2166
return 0;
2167
}
2168
2169
static int
2170
hashlib_init_hmactype(PyObject *module)
2171
{
2172
_hashlibstate *state = get_hashlib_state(module);
2173
2174
state->HMACtype = (PyTypeObject *)PyType_FromSpec(&HMACtype_spec);
2175
if (state->HMACtype == NULL) {
2176
return -1;
2177
}
2178
if (PyModule_AddType(module, state->HMACtype) < 0) {
2179
return -1;
2180
}
2181
return 0;
2182
}
2183
2184
static int
2185
hashlib_init_constructors(PyObject *module)
2186
{
2187
/* Create dict from builtin openssl_hash functions to name
2188
* {_hashlib.openssl_sha256: "sha256", ...}
2189
*/
2190
PyModuleDef *mdef;
2191
PyMethodDef *fdef;
2192
PyObject *proxy;
2193
PyObject *func, *name_obj;
2194
_hashlibstate *state = get_hashlib_state(module);
2195
2196
mdef = PyModule_GetDef(module);
2197
if (mdef == NULL) {
2198
return -1;
2199
}
2200
2201
state->constructs = PyDict_New();
2202
if (state->constructs == NULL) {
2203
return -1;
2204
}
2205
2206
for (fdef = mdef->m_methods; fdef->ml_name != NULL; fdef++) {
2207
if (strncmp(fdef->ml_name, "openssl_", 8)) {
2208
continue;
2209
}
2210
name_obj = PyUnicode_FromString(fdef->ml_name + 8);
2211
if (name_obj == NULL) {
2212
return -1;
2213
}
2214
func = PyObject_GetAttrString(module, fdef->ml_name);
2215
if (func == NULL) {
2216
Py_DECREF(name_obj);
2217
return -1;
2218
}
2219
int rc = PyDict_SetItem(state->constructs, func, name_obj);
2220
Py_DECREF(func);
2221
Py_DECREF(name_obj);
2222
if (rc < 0) {
2223
return -1;
2224
}
2225
}
2226
2227
proxy = PyDictProxy_New(state->constructs);
2228
if (proxy == NULL) {
2229
return -1;
2230
}
2231
2232
int rc = PyModule_AddObjectRef(module, "_constructors", proxy);
2233
Py_DECREF(proxy);
2234
if (rc < 0) {
2235
return -1;
2236
}
2237
return 0;
2238
}
2239
2240
static int
2241
hashlib_exception(PyObject *module)
2242
{
2243
_hashlibstate *state = get_hashlib_state(module);
2244
state->unsupported_digestmod_error = PyErr_NewException(
2245
"_hashlib.UnsupportedDigestmodError", PyExc_ValueError, NULL);
2246
if (state->unsupported_digestmod_error == NULL) {
2247
return -1;
2248
}
2249
if (PyModule_AddObjectRef(module, "UnsupportedDigestmodError",
2250
state->unsupported_digestmod_error) < 0) {
2251
return -1;
2252
}
2253
return 0;
2254
}
2255
2256
2257
static PyModuleDef_Slot hashlib_slots[] = {
2258
{Py_mod_exec, hashlib_init_hashtable},
2259
{Py_mod_exec, hashlib_init_evptype},
2260
{Py_mod_exec, hashlib_init_evpxoftype},
2261
{Py_mod_exec, hashlib_init_hmactype},
2262
{Py_mod_exec, hashlib_md_meth_names},
2263
{Py_mod_exec, hashlib_init_constructors},
2264
{Py_mod_exec, hashlib_exception},
2265
{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2266
{0, NULL}
2267
};
2268
2269
static struct PyModuleDef _hashlibmodule = {
2270
PyModuleDef_HEAD_INIT,
2271
.m_name = "_hashlib",
2272
.m_doc = "OpenSSL interface for hashlib module",
2273
.m_size = sizeof(_hashlibstate),
2274
.m_methods = EVP_functions,
2275
.m_slots = hashlib_slots,
2276
.m_traverse = hashlib_traverse,
2277
.m_clear = hashlib_clear,
2278
.m_free = hashlib_free
2279
};
2280
2281
PyMODINIT_FUNC
2282
PyInit__hashlib(void)
2283
{
2284
return PyModuleDef_Init(&_hashlibmodule);
2285
}
2286
2287