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