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