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