blob: 1513e4e35edc6e6e5819d2ce90bd162279ee838f [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001/* Module that wraps all OpenSSL hash algorithms */
2
3/*
Benjamin Peterson46a99002010-01-09 18:45:30 +00004 * Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00005 * 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
Thomas Wouters9bc844e2006-03-01 21:50:07 +000014#define PY_SSIZE_T_CLEAN
15
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000016#include "Python.h"
17#include "structmember.h"
Gregory P. Smith365a1862009-02-12 07:35:29 +000018#include "hashlib.h"
Gregory P. Smith4dff6f62015-04-25 23:42:38 +000019#include "pystrhex.h"
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000020
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +000021
Gregory P. Smith3f61d612009-05-04 00:45:33 +000022/* EVP is the preferred interface to hashing in OpenSSL */
23#include <openssl/evp.h>
Christian Heimes2f050c72018-01-27 09:53:43 +010024#include <openssl/hmac.h>
Gregory P. Smith13b55292010-09-06 08:30:23 +000025/* We use the object interface to discover what hashes OpenSSL supports. */
26#include <openssl/objects.h>
Christian Heimese92ef132013-10-13 00:52:43 +020027#include "openssl/err.h"
Gregory P. Smith3f61d612009-05-04 00:45:33 +000028
Stéphane Wirtel36c29e42019-09-12 15:57:03 +010029#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
30/* OpenSSL < 1.1.0 */
31#define EVP_MD_CTX_new EVP_MD_CTX_create
32#define EVP_MD_CTX_free EVP_MD_CTX_destroy
33#endif
34
Gregory P. Smith3f61d612009-05-04 00:45:33 +000035#define MUNCH_SIZE INT_MAX
36
Miss Islington (bot)0067fc22019-09-16 05:28:32 -070037#ifdef NID_sha3_224
Christian Heimese8d7fa22019-09-16 14:08:55 +020038#define PY_OPENSSL_HAS_SHA3 1
39#endif
40
Miss Islington (bot)0067fc22019-09-16 05:28:32 -070041#if defined(EVP_MD_FLAG_XOF) && defined(NID_shake128)
42#define PY_OPENSSL_HAS_SHAKE 1
43#endif
44
Christian Heimese8d7fa22019-09-16 14:08:55 +020045#ifdef NID_blake2b512
46#define PY_OPENSSL_HAS_BLAKE2 1
47#endif
48
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000049typedef struct {
50 PyObject_HEAD
Christian Heimes598894f2016-09-05 23:19:05 +020051 EVP_MD_CTX *ctx; /* OpenSSL message digest context */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +000052 PyThread_type_lock lock; /* OpenSSL context lock */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000053} EVPobject;
54
55
56static PyTypeObject EVPtype;
57
Tal Einatc6c72372018-12-27 15:43:43 +020058#include "clinic/_hashopenssl.c.h"
59/*[clinic input]
60module _hashlib
61class _hashlib.HASH "EVPobject *" "&EVPtype"
62[clinic start generated code]*/
63/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a881a5092eecad28]*/
64
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000065
Christian Heimes598894f2016-09-05 23:19:05 +020066/* LCOV_EXCL_START */
67static PyObject *
68_setException(PyObject *exc)
69{
70 unsigned long errcode;
71 const char *lib, *func, *reason;
72
73 errcode = ERR_peek_last_error();
74 if (!errcode) {
75 PyErr_SetString(exc, "unknown reasons");
76 return NULL;
77 }
78 ERR_clear_error();
79
80 lib = ERR_lib_error_string(errcode);
81 func = ERR_func_error_string(errcode);
82 reason = ERR_reason_error_string(errcode);
83
84 if (lib && func) {
85 PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
86 }
87 else if (lib) {
88 PyErr_Format(exc, "[%s] %s", lib, reason);
89 }
90 else {
91 PyErr_SetString(exc, reason);
92 }
93 return NULL;
94}
95/* LCOV_EXCL_STOP */
96
Christian Heimese8d7fa22019-09-16 14:08:55 +020097static PyObject*
98py_digest_name(const EVP_MD *md)
99{
100 int nid = EVP_MD_nid(md);
101 const char *name = NULL;
102
103 /* Hard-coded names for well-known hashing algorithms.
104 * OpenSSL uses slightly different names algorithms like SHA3.
105 */
106 switch (nid) {
107 case NID_md5:
108 name = "md5";
109 break;
110 case NID_sha1:
111 name = "sha1";
112 break;
113 case NID_sha224:
114 name ="sha224";
115 break;
116 case NID_sha256:
117 name ="sha256";
118 break;
119 case NID_sha384:
120 name ="sha384";
121 break;
122 case NID_sha512:
123 name ="sha512";
124 break;
125#ifdef NID_sha512_224
126 case NID_sha512_224:
127 name ="sha512_224";
128 break;
129 case NID_sha512_256:
130 name ="sha512_256";
131 break;
132#endif
133#ifdef PY_OPENSSL_HAS_SHA3
134 case NID_sha3_224:
135 name ="sha3_224";
136 break;
137 case NID_sha3_256:
138 name ="sha3_256";
139 break;
140 case NID_sha3_384:
141 name ="sha3_384";
142 break;
143 case NID_sha3_512:
144 name ="sha3_512";
145 break;
Miss Islington (bot)0067fc22019-09-16 05:28:32 -0700146#endif
147#ifdef PY_OPENSSL_HAS_SHAKE
Christian Heimese8d7fa22019-09-16 14:08:55 +0200148 case NID_shake128:
149 name ="shake_128";
150 break;
151 case NID_shake256:
152 name ="shake_256";
153 break;
154#endif
155#ifdef PY_OPENSSL_HAS_BLAKE2
156 case NID_blake2s256:
157 name ="blake2s";
158 break;
159 case NID_blake2b512:
160 name ="blake2b";
161 break;
162#endif
163 default:
164 /* Ignore aliased names and only use long, lowercase name. The aliases
165 * pollute the list and OpenSSL appears to have its own definition of
166 * alias as the resulting list still contains duplicate and alternate
167 * names for several algorithms.
168 */
169 name = OBJ_nid2ln(nid);
170 if (name == NULL)
171 name = OBJ_nid2sn(nid);
172 break;
173 }
174
175 return PyUnicode_FromString(name);
176}
177
178static const EVP_MD*
179py_digest_by_name(const char *name)
180{
181 const EVP_MD *digest = EVP_get_digestbyname(name);
182
183 /* OpenSSL uses dash instead of underscore in names of some algorithms
184 * like SHA3 and SHAKE. Detect different spellings. */
185 if (digest == NULL) {
Miss Islington (bot)0067fc22019-09-16 05:28:32 -0700186 if (0) {}
Christian Heimese8d7fa22019-09-16 14:08:55 +0200187#ifdef NID_sha512_224
Miss Islington (bot)0067fc22019-09-16 05:28:32 -0700188 else if (!strcmp(name, "sha512_224") || !strcmp(name, "SHA512_224")) {
Christian Heimese8d7fa22019-09-16 14:08:55 +0200189 digest = EVP_sha512_224();
190 }
191 else if (!strcmp(name, "sha512_256") || !strcmp(name, "SHA512_256")) {
192 digest = EVP_sha512_256();
193 }
194#endif
195#ifdef PY_OPENSSL_HAS_SHA3
196 /* could be sha3_ or shake_, Python never defined upper case */
197 else if (!strcmp(name, "sha3_224")) {
198 digest = EVP_sha3_224();
199 }
200 else if (!strcmp(name, "sha3_256")) {
201 digest = EVP_sha3_256();
202 }
203 else if (!strcmp(name, "sha3_384")) {
204 digest = EVP_sha3_384();
205 }
206 else if (!strcmp(name, "sha3_512")) {
207 digest = EVP_sha3_512();
208 }
Miss Islington (bot)0067fc22019-09-16 05:28:32 -0700209#endif
210#ifdef PY_OPENSSL_HAS_SHAKE
Christian Heimese8d7fa22019-09-16 14:08:55 +0200211 else if (!strcmp(name, "shake_128")) {
212 digest = EVP_shake128();
213 }
214 else if (!strcmp(name, "shake_256")) {
215 digest = EVP_shake256();
216 }
217#endif
218#ifdef PY_OPENSSL_HAS_BLAKE2
219 else if (!strcmp(name, "blake2s256")) {
220 digest = EVP_blake2s256();
221 }
222 else if (!strcmp(name, "blake2b512")) {
223 digest = EVP_blake2b512();
224 }
225#endif
226 }
227
228 return digest;
229}
230
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000231static EVPobject *
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700232newEVPobject(void)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000233{
234 EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
Christian Heimes598894f2016-09-05 23:19:05 +0200235 if (retval == NULL) {
236 return NULL;
237 }
238
Christian Heimes598894f2016-09-05 23:19:05 +0200239 retval->lock = NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000240
Christian Heimesb7bc2832019-03-04 16:45:41 +0100241 retval->ctx = EVP_MD_CTX_new();
242 if (retval->ctx == NULL) {
243 Py_DECREF(retval);
244 PyErr_NoMemory();
245 return NULL;
246 }
247
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000248 return retval;
249}
250
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700251static int
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000252EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
253{
254 unsigned int process;
255 const unsigned char *cp = (const unsigned char *)vp;
256 while (0 < len) {
257 if (len > (Py_ssize_t)MUNCH_SIZE)
258 process = MUNCH_SIZE;
259 else
260 process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700261 if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
262 _setException(PyExc_ValueError);
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700263 return -1;
Gregory P. Smith07244a82017-05-24 00:04:38 -0700264 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000265 len -= process;
266 cp += process;
267 }
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700268 return 0;
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000269}
270
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000271/* Internal methods for a hash object */
272
273static void
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000274EVP_dealloc(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000275{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000276 if (self->lock != NULL)
277 PyThread_free_lock(self->lock);
Christian Heimes598894f2016-09-05 23:19:05 +0200278 EVP_MD_CTX_free(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000279 PyObject_Del(self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000280}
281
Christian Heimes598894f2016-09-05 23:19:05 +0200282static int
283locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000284{
Christian Heimes598894f2016-09-05 23:19:05 +0200285 int result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000286 ENTER_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200287 result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000288 LEAVE_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200289 return result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000290}
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000291
292/* External methods for a hash object */
293
Tal Einatc6c72372018-12-27 15:43:43 +0200294/*[clinic input]
295_hashlib.HASH.copy as EVP_copy
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000296
Tal Einatc6c72372018-12-27 15:43:43 +0200297Return a copy of the hash object.
298[clinic start generated code]*/
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000299
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000300static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200301EVP_copy_impl(EVPobject *self)
302/*[clinic end generated code: output=b370c21cdb8ca0b4 input=31455b6a3e638069]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000303{
304 EVPobject *newobj;
305
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700306 if ( (newobj = newEVPobject())==NULL)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000307 return NULL;
308
Christian Heimes598894f2016-09-05 23:19:05 +0200309 if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
Christian Heimesb7bc2832019-03-04 16:45:41 +0100310 Py_DECREF(newobj);
Christian Heimes598894f2016-09-05 23:19:05 +0200311 return _setException(PyExc_ValueError);
312 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000313 return (PyObject *)newobj;
314}
315
Tal Einatc6c72372018-12-27 15:43:43 +0200316/*[clinic input]
317_hashlib.HASH.digest as EVP_digest
318
319Return the digest value as a bytes object.
320[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000321
322static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200323EVP_digest_impl(EVPobject *self)
324/*[clinic end generated code: output=0f6a3a0da46dc12d input=03561809a419bf00]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000325{
326 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200327 EVP_MD_CTX *temp_ctx;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000328 PyObject *retval;
329 unsigned int digest_size;
330
Christian Heimes598894f2016-09-05 23:19:05 +0200331 temp_ctx = EVP_MD_CTX_new();
332 if (temp_ctx == NULL) {
333 PyErr_NoMemory();
334 return NULL;
335 }
336
337 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
338 return _setException(PyExc_ValueError);
339 }
340 digest_size = EVP_MD_CTX_size(temp_ctx);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700341 if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
342 _setException(PyExc_ValueError);
343 return NULL;
344 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000345
Christian Heimes72b710a2008-05-26 13:28:38 +0000346 retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
Christian Heimes598894f2016-09-05 23:19:05 +0200347 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000348 return retval;
349}
350
Tal Einatc6c72372018-12-27 15:43:43 +0200351/*[clinic input]
352_hashlib.HASH.hexdigest as EVP_hexdigest
353
354Return the digest value as a string of hexadecimal digits.
355[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000356
357static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200358EVP_hexdigest_impl(EVPobject *self)
359/*[clinic end generated code: output=18e6decbaf197296 input=aff9cf0e4c741a9a]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000360{
361 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200362 EVP_MD_CTX *temp_ctx;
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000363 unsigned int digest_size;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000364
Christian Heimes598894f2016-09-05 23:19:05 +0200365 temp_ctx = EVP_MD_CTX_new();
366 if (temp_ctx == NULL) {
367 PyErr_NoMemory();
368 return NULL;
369 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000370
Christian Heimes598894f2016-09-05 23:19:05 +0200371 /* Get the raw (binary) digest value */
372 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
373 return _setException(PyExc_ValueError);
374 }
375 digest_size = EVP_MD_CTX_size(temp_ctx);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700376 if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
377 _setException(PyExc_ValueError);
378 return NULL;
379 }
Christian Heimes598894f2016-09-05 23:19:05 +0200380
381 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000382
Benjamin Petersone5024512018-09-12 12:06:42 -0700383 return _Py_strhex((const char *)digest, (Py_ssize_t)digest_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000384}
385
Tal Einatc6c72372018-12-27 15:43:43 +0200386/*[clinic input]
387_hashlib.HASH.update as EVP_update
388
389 obj: object
390 /
391
392Update this hash object's state with the provided string.
393[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000394
395static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200396EVP_update(EVPobject *self, PyObject *obj)
397/*[clinic end generated code: output=ec1d55ed2432e966 input=9b30ec848f015501]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000398{
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700399 int result;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000400 Py_buffer view;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000401
Gregory P. Smith365a1862009-02-12 07:35:29 +0000402 GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000403
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000404 if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
405 self->lock = PyThread_allocate_lock();
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000406 /* fail? lock = NULL and we fail over to non-threaded code. */
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000407 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000408
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000409 if (self->lock != NULL) {
410 Py_BEGIN_ALLOW_THREADS
411 PyThread_acquire_lock(self->lock, 1);
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700412 result = EVP_hash(self, view.buf, view.len);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000413 PyThread_release_lock(self->lock);
414 Py_END_ALLOW_THREADS
415 } else {
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700416 result = EVP_hash(self, view.buf, view.len);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000417 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000418
419 PyBuffer_Release(&view);
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700420
421 if (result == -1)
422 return NULL;
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000423 Py_RETURN_NONE;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000424}
425
426static PyMethodDef EVP_methods[] = {
Tal Einatc6c72372018-12-27 15:43:43 +0200427 EVP_UPDATE_METHODDEF
428 EVP_DIGEST_METHODDEF
429 EVP_HEXDIGEST_METHODDEF
430 EVP_COPY_METHODDEF
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000431 {NULL, NULL} /* sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000432};
433
434static PyObject *
435EVP_get_block_size(EVPobject *self, void *closure)
436{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000437 long block_size;
Christian Heimes598894f2016-09-05 23:19:05 +0200438 block_size = EVP_MD_CTX_block_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000439 return PyLong_FromLong(block_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000440}
441
442static PyObject *
443EVP_get_digest_size(EVPobject *self, void *closure)
444{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000445 long size;
Christian Heimes598894f2016-09-05 23:19:05 +0200446 size = EVP_MD_CTX_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000447 return PyLong_FromLong(size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000448}
449
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700450static PyObject *
451EVP_get_name(EVPobject *self, void *closure)
452{
Christian Heimese8d7fa22019-09-16 14:08:55 +0200453 return py_digest_name(EVP_MD_CTX_md(self->ctx));
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700454}
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000455
456static PyGetSetDef EVP_getseters[] = {
457 {"digest_size",
458 (getter)EVP_get_digest_size, NULL,
459 NULL,
460 NULL},
461 {"block_size",
462 (getter)EVP_get_block_size, NULL,
463 NULL,
464 NULL},
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700465 {"name",
466 (getter)EVP_get_name, NULL,
467 NULL,
468 PyDoc_STR("algorithm name.")},
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000469 {NULL} /* Sentinel */
470};
471
472
473static PyObject *
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000474EVP_repr(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000475{
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700476 PyObject *name_obj, *repr;
Christian Heimese8d7fa22019-09-16 14:08:55 +0200477 name_obj = py_digest_name(EVP_MD_CTX_md(self->ctx));
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700478 if (!name_obj) {
479 return NULL;
480 }
481 repr = PyUnicode_FromFormat("<%U HASH object @ %p>", name_obj, self);
482 Py_DECREF(name_obj);
483 return repr;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000484}
485
Gregory P. Smithc7e21912018-12-30 17:54:53 -0800486PyDoc_STRVAR(hashtype_doc,
487"HASH(name, string=b\'\')\n"
488"--\n"
489"\n"
490"A hash is an object used to calculate a checksum of a string of information.\n"
491"\n"
492"Methods:\n"
493"\n"
494"update() -- updates the current digest with an additional string\n"
495"digest() -- return the current digest value\n"
496"hexdigest() -- return the current digest as a string of hexadecimal digits\n"
497"copy() -- return a copy of the current hash object\n"
498"\n"
499"Attributes:\n"
500"\n"
501"name -- the hash algorithm being used by this object\n"
502"digest_size -- number of bytes in this hashes output");
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000503
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000504static PyTypeObject EVPtype = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000505 PyVarObject_HEAD_INIT(NULL, 0)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000506 "_hashlib.HASH", /*tp_name*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000507 sizeof(EVPobject), /*tp_basicsize*/
508 0, /*tp_itemsize*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000509 /* methods */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000510 (destructor)EVP_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200511 0, /*tp_vectorcall_offset*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000512 0, /*tp_getattr*/
513 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200514 0, /*tp_as_async*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000515 (reprfunc)EVP_repr, /*tp_repr*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000516 0, /*tp_as_number*/
517 0, /*tp_as_sequence*/
518 0, /*tp_as_mapping*/
519 0, /*tp_hash*/
520 0, /*tp_call*/
521 0, /*tp_str*/
522 0, /*tp_getattro*/
523 0, /*tp_setattro*/
524 0, /*tp_as_buffer*/
525 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Gregory P. Smithc7e21912018-12-30 17:54:53 -0800526 hashtype_doc, /*tp_doc*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000527 0, /*tp_traverse*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000528 0, /*tp_clear*/
529 0, /*tp_richcompare*/
530 0, /*tp_weaklistoffset*/
531 0, /*tp_iter*/
532 0, /*tp_iternext*/
533 EVP_methods, /* tp_methods */
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700534 NULL, /* tp_members */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000535 EVP_getseters, /* tp_getset */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000536 0, /* tp_base */
537 0, /* tp_dict */
538 0, /* tp_descr_get */
539 0, /* tp_descr_set */
540 0, /* tp_dictoffset */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000541};
542
Christian Heimese8d7fa22019-09-16 14:08:55 +0200543\
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000544static PyObject *
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700545EVPnew(const EVP_MD *digest,
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000546 const unsigned char *cp, Py_ssize_t len)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000547{
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700548 int result = 0;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000549 EVPobject *self;
550
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700551 if (!digest) {
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000552 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
553 return NULL;
554 }
555
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700556 if ((self = newEVPobject()) == NULL)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000557 return NULL;
558
Christian Heimesbfca56b2019-09-30 09:10:38 +0200559 if (!EVP_DigestInit_ex(self->ctx, digest, NULL)) {
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700560 _setException(PyExc_ValueError);
561 Py_DECREF(self);
562 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000563 }
564
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000565 if (cp && len) {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000566 if (len >= HASHLIB_GIL_MINSIZE) {
567 Py_BEGIN_ALLOW_THREADS
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700568 result = EVP_hash(self, cp, len);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000569 Py_END_ALLOW_THREADS
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000570 } else {
Miss Islington (bot)0d7cb5b2019-09-12 06:50:46 -0700571 result = EVP_hash(self, cp, len);
572 }
573 if (result == -1) {
574 Py_DECREF(self);
575 return NULL;
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000576 }
577 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000578
579 return (PyObject *)self;
580}
581
582
583/* The module-level function: new() */
584
Tal Einatc6c72372018-12-27 15:43:43 +0200585/*[clinic input]
586_hashlib.new as EVP_new
587
588 name as name_obj: object
Serhiy Storchakad322abb2019-09-14 13:31:50 +0300589 string as data_obj: object(c_default="NULL") = b''
Tal Einatc6c72372018-12-27 15:43:43 +0200590
591Return a new hash object using the named algorithm.
592
593An optional string argument may be provided and will be
594automatically hashed.
595
596The MD5 and SHA1 algorithms are always supported.
597[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000598
599static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200600EVP_new_impl(PyObject *module, PyObject *name_obj, PyObject *data_obj)
Serhiy Storchakad322abb2019-09-14 13:31:50 +0300601/*[clinic end generated code: output=9e7cf664e04b0226 input=7eb79bf30058bd02]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000602{
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000603 Py_buffer view = { 0 };
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000604 PyObject *ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000605 char *name;
606 const EVP_MD *digest;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000607
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000608 if (!PyArg_Parse(name_obj, "s", &name)) {
609 PyErr_SetString(PyExc_TypeError, "name must be a string");
610 return NULL;
611 }
612
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000613 if (data_obj)
Gregory P. Smith365a1862009-02-12 07:35:29 +0000614 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000615
Christian Heimese8d7fa22019-09-16 14:08:55 +0200616 digest = py_digest_by_name(name);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000617
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700618 ret_obj = EVPnew(digest, (unsigned char*)view.buf, view.len);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000619
620 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000621 PyBuffer_Release(&view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000622 return ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000623}
624
Miss Islington (bot)67b90a02019-09-12 06:03:50 -0700625static PyObject*
626EVP_fast_new(PyObject *module, PyObject *data_obj, const EVP_MD *digest)
627{
628 Py_buffer view = { 0 };
629 PyObject *ret_obj;
630
631 if (data_obj)
632 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
633
634 ret_obj = EVPnew(digest, (unsigned char*)view.buf, view.len);
635
636 if (data_obj)
637 PyBuffer_Release(&view);
638
639 return ret_obj;
640}
641
642/*[clinic input]
643_hashlib.openssl_md5
644
645 string as data_obj: object(py_default="b''") = NULL
646
647Returns a md5 hash object; optionally initialized with a string
648
649[clinic start generated code]*/
650
651static PyObject *
652_hashlib_openssl_md5_impl(PyObject *module, PyObject *data_obj)
653/*[clinic end generated code: output=6caae75b73e22c3f input=52010d3869e1b1a7]*/
654{
655 return EVP_fast_new(module, data_obj, EVP_md5());
656}
657
658
659/*[clinic input]
660_hashlib.openssl_sha1
661
662 string as data_obj: object(py_default="b''") = NULL
663
664Returns a sha1 hash object; optionally initialized with a string
665
666[clinic start generated code]*/
667
668static PyObject *
669_hashlib_openssl_sha1_impl(PyObject *module, PyObject *data_obj)
670/*[clinic end generated code: output=07606d8f75153e61 input=16807d30e4aa8ae9]*/
671{
672 return EVP_fast_new(module, data_obj, EVP_sha1());
673}
674
675
676/*[clinic input]
677_hashlib.openssl_sha224
678
679 string as data_obj: object(py_default="b''") = NULL
680
681Returns a sha224 hash object; optionally initialized with a string
682
683[clinic start generated code]*/
684
685static PyObject *
686_hashlib_openssl_sha224_impl(PyObject *module, PyObject *data_obj)
687/*[clinic end generated code: output=55e848761bcef0c9 input=5dbc2f1d84eb459b]*/
688{
689 return EVP_fast_new(module, data_obj, EVP_sha224());
690}
691
692
693/*[clinic input]
694_hashlib.openssl_sha256
695
696 string as data_obj: object(py_default="b''") = NULL
697
698Returns a sha256 hash object; optionally initialized with a string
699
700[clinic start generated code]*/
701
702static PyObject *
703_hashlib_openssl_sha256_impl(PyObject *module, PyObject *data_obj)
704/*[clinic end generated code: output=05851d7cce34ac65 input=a68a5d21cda5a80f]*/
705{
706 return EVP_fast_new(module, data_obj, EVP_sha256());
707}
708
709
710/*[clinic input]
711_hashlib.openssl_sha384
712
713 string as data_obj: object(py_default="b''") = NULL
714
715Returns a sha384 hash object; optionally initialized with a string
716
717[clinic start generated code]*/
718
719static PyObject *
720_hashlib_openssl_sha384_impl(PyObject *module, PyObject *data_obj)
721/*[clinic end generated code: output=5101a4704a932c2f input=6bdfa006622b64ea]*/
722{
723 return EVP_fast_new(module, data_obj, EVP_sha384());
724}
725
726
727/*[clinic input]
728_hashlib.openssl_sha512
729
730 string as data_obj: object(py_default="b''") = NULL
731
732Returns a sha512 hash object; optionally initialized with a string
733
734[clinic start generated code]*/
735
736static PyObject *
737_hashlib_openssl_sha512_impl(PyObject *module, PyObject *data_obj)
738/*[clinic end generated code: output=20c8e63ee560a5cb input=ece50182ad4b76a6]*/
739{
740 return EVP_fast_new(module, data_obj, EVP_sha512());
741}
742
743
Tal Einatc6c72372018-12-27 15:43:43 +0200744/*[clinic input]
745_hashlib.pbkdf2_hmac as pbkdf2_hmac
746
747 hash_name: str
748 password: Py_buffer
749 salt: Py_buffer
750 iterations: long
751 dklen as dklen_obj: object = None
752
753Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function.
754[clinic start generated code]*/
Christian Heimese92ef132013-10-13 00:52:43 +0200755
756static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200757pbkdf2_hmac_impl(PyObject *module, const char *hash_name,
758 Py_buffer *password, Py_buffer *salt, long iterations,
759 PyObject *dklen_obj)
760/*[clinic end generated code: output=144b76005416599b input=ed3ab0d2d28b5d5c]*/
Christian Heimese92ef132013-10-13 00:52:43 +0200761{
Tal Einatc6c72372018-12-27 15:43:43 +0200762 PyObject *key_obj = NULL;
763 char *key;
764 long dklen;
Christian Heimese92ef132013-10-13 00:52:43 +0200765 int retval;
766 const EVP_MD *digest;
767
Tal Einatc6c72372018-12-27 15:43:43 +0200768 digest = EVP_get_digestbyname(hash_name);
Christian Heimese92ef132013-10-13 00:52:43 +0200769 if (digest == NULL) {
770 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
771 goto end;
772 }
773
Tal Einatc6c72372018-12-27 15:43:43 +0200774 if (password->len > INT_MAX) {
Christian Heimese92ef132013-10-13 00:52:43 +0200775 PyErr_SetString(PyExc_OverflowError,
776 "password is too long.");
777 goto end;
778 }
779
Tal Einatc6c72372018-12-27 15:43:43 +0200780 if (salt->len > INT_MAX) {
Christian Heimese92ef132013-10-13 00:52:43 +0200781 PyErr_SetString(PyExc_OverflowError,
782 "salt is too long.");
783 goto end;
784 }
785
786 if (iterations < 1) {
787 PyErr_SetString(PyExc_ValueError,
788 "iteration value must be greater than 0.");
789 goto end;
790 }
791 if (iterations > INT_MAX) {
792 PyErr_SetString(PyExc_OverflowError,
793 "iteration value is too great.");
794 goto end;
795 }
796
797 if (dklen_obj == Py_None) {
798 dklen = EVP_MD_size(digest);
799 } else {
800 dklen = PyLong_AsLong(dklen_obj);
801 if ((dklen == -1) && PyErr_Occurred()) {
802 goto end;
803 }
804 }
805 if (dklen < 1) {
806 PyErr_SetString(PyExc_ValueError,
807 "key length must be greater than 0.");
808 goto end;
809 }
810 if (dklen > INT_MAX) {
811 /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
812 PyErr_SetString(PyExc_OverflowError,
813 "key length is too great.");
814 goto end;
815 }
816
817 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
818 if (key_obj == NULL) {
819 goto end;
820 }
821 key = PyBytes_AS_STRING(key_obj);
822
823 Py_BEGIN_ALLOW_THREADS
Tal Einatc6c72372018-12-27 15:43:43 +0200824 retval = PKCS5_PBKDF2_HMAC((char*)password->buf, (int)password->len,
825 (unsigned char *)salt->buf, (int)salt->len,
Christian Heimes598894f2016-09-05 23:19:05 +0200826 iterations, digest, dklen,
827 (unsigned char *)key);
Christian Heimese92ef132013-10-13 00:52:43 +0200828 Py_END_ALLOW_THREADS
829
830 if (!retval) {
831 Py_CLEAR(key_obj);
832 _setException(PyExc_ValueError);
833 goto end;
834 }
835
836 end:
Christian Heimese92ef132013-10-13 00:52:43 +0200837 return key_obj;
838}
839
Christian Heimes39093e92016-09-06 20:22:28 +0200840#if OPENSSL_VERSION_NUMBER > 0x10100000L && !defined(OPENSSL_NO_SCRYPT) && !defined(LIBRESSL_VERSION_NUMBER)
841#define PY_SCRYPT 1
842
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300843/* XXX: Parameters salt, n, r and p should be required keyword-only parameters.
844 They are optional in the Argument Clinic declaration only due to a
845 limitation of PyArg_ParseTupleAndKeywords. */
846
Christian Heimes39093e92016-09-06 20:22:28 +0200847/*[clinic input]
848_hashlib.scrypt
849
850 password: Py_buffer
851 *
852 salt: Py_buffer = None
853 n as n_obj: object(subclass_of='&PyLong_Type') = None
854 r as r_obj: object(subclass_of='&PyLong_Type') = None
855 p as p_obj: object(subclass_of='&PyLong_Type') = None
856 maxmem: long = 0
857 dklen: long = 64
858
859
860scrypt password-based key derivation function.
861[clinic start generated code]*/
862
863static PyObject *
864_hashlib_scrypt_impl(PyObject *module, Py_buffer *password, Py_buffer *salt,
865 PyObject *n_obj, PyObject *r_obj, PyObject *p_obj,
866 long maxmem, long dklen)
867/*[clinic end generated code: output=14849e2aa2b7b46c input=48a7d63bf3f75c42]*/
868{
869 PyObject *key_obj = NULL;
870 char *key;
871 int retval;
872 unsigned long n, r, p;
873
874 if (password->len > INT_MAX) {
875 PyErr_SetString(PyExc_OverflowError,
876 "password is too long.");
877 return NULL;
878 }
879
880 if (salt->buf == NULL) {
881 PyErr_SetString(PyExc_TypeError,
882 "salt is required");
883 return NULL;
884 }
885 if (salt->len > INT_MAX) {
886 PyErr_SetString(PyExc_OverflowError,
887 "salt is too long.");
888 return NULL;
889 }
890
891 n = PyLong_AsUnsignedLong(n_obj);
892 if (n == (unsigned long) -1 && PyErr_Occurred()) {
893 PyErr_SetString(PyExc_TypeError,
894 "n is required and must be an unsigned int");
895 return NULL;
896 }
897 if (n < 2 || n & (n - 1)) {
898 PyErr_SetString(PyExc_ValueError,
899 "n must be a power of 2.");
900 return NULL;
901 }
902
903 r = PyLong_AsUnsignedLong(r_obj);
904 if (r == (unsigned long) -1 && PyErr_Occurred()) {
905 PyErr_SetString(PyExc_TypeError,
906 "r is required and must be an unsigned int");
907 return NULL;
908 }
909
910 p = PyLong_AsUnsignedLong(p_obj);
911 if (p == (unsigned long) -1 && PyErr_Occurred()) {
912 PyErr_SetString(PyExc_TypeError,
913 "p is required and must be an unsigned int");
914 return NULL;
915 }
916
917 if (maxmem < 0 || maxmem > INT_MAX) {
Victor Stinner8c663fd2017-11-08 14:44:44 -0800918 /* OpenSSL 1.1.0 restricts maxmem to 32 MiB. It may change in the
Christian Heimes39093e92016-09-06 20:22:28 +0200919 future. The maxmem constant is private to OpenSSL. */
920 PyErr_Format(PyExc_ValueError,
921 "maxmem must be positive and smaller than %d",
922 INT_MAX);
923 return NULL;
924 }
925
926 if (dklen < 1 || dklen > INT_MAX) {
927 PyErr_Format(PyExc_ValueError,
928 "dklen must be greater than 0 and smaller than %d",
929 INT_MAX);
930 return NULL;
931 }
932
933 /* let OpenSSL validate the rest */
934 retval = EVP_PBE_scrypt(NULL, 0, NULL, 0, n, r, p, maxmem, NULL, 0);
935 if (!retval) {
936 /* sorry, can't do much better */
937 PyErr_SetString(PyExc_ValueError,
Emmanuel Ariasb71e28e2019-03-06 11:35:35 -0300938 "Invalid parameter combination for n, r, p, maxmem.");
Christian Heimes39093e92016-09-06 20:22:28 +0200939 return NULL;
940 }
941
942 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
943 if (key_obj == NULL) {
944 return NULL;
945 }
946 key = PyBytes_AS_STRING(key_obj);
947
948 Py_BEGIN_ALLOW_THREADS
949 retval = EVP_PBE_scrypt(
950 (const char*)password->buf, (size_t)password->len,
951 (const unsigned char *)salt->buf, (size_t)salt->len,
952 n, r, p, maxmem,
953 (unsigned char *)key, (size_t)dklen
954 );
955 Py_END_ALLOW_THREADS
956
957 if (!retval) {
958 Py_CLEAR(key_obj);
959 _setException(PyExc_ValueError);
960 return NULL;
961 }
962 return key_obj;
963}
964#endif
965
Christian Heimes2f050c72018-01-27 09:53:43 +0100966/* Fast HMAC for hmac.digest()
967 */
968
969/*[clinic input]
970_hashlib.hmac_digest
971
972 key: Py_buffer
973 msg: Py_buffer
974 digest: str
975
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300976Single-shot HMAC.
Christian Heimes2f050c72018-01-27 09:53:43 +0100977[clinic start generated code]*/
978
979static PyObject *
980_hashlib_hmac_digest_impl(PyObject *module, Py_buffer *key, Py_buffer *msg,
981 const char *digest)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300982/*[clinic end generated code: output=75630e684cdd8762 input=562d2f4249511bd3]*/
Christian Heimes2f050c72018-01-27 09:53:43 +0100983{
984 unsigned char md[EVP_MAX_MD_SIZE] = {0};
985 unsigned int md_len = 0;
986 unsigned char *result;
987 const EVP_MD *evp;
988
989 evp = EVP_get_digestbyname(digest);
990 if (evp == NULL) {
991 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
992 return NULL;
993 }
994 if (key->len > INT_MAX) {
995 PyErr_SetString(PyExc_OverflowError,
996 "key is too long.");
997 return NULL;
998 }
999 if (msg->len > INT_MAX) {
1000 PyErr_SetString(PyExc_OverflowError,
1001 "msg is too long.");
1002 return NULL;
1003 }
1004
1005 Py_BEGIN_ALLOW_THREADS
1006 result = HMAC(
1007 evp,
1008 (const void*)key->buf, (int)key->len,
1009 (const unsigned char*)msg->buf, (int)msg->len,
1010 md, &md_len
1011 );
1012 Py_END_ALLOW_THREADS
1013
1014 if (result == NULL) {
1015 _setException(PyExc_ValueError);
1016 return NULL;
1017 }
1018 return PyBytes_FromStringAndSize((const char*)md, md_len);
1019}
1020
Gregory P. Smith13b55292010-09-06 08:30:23 +00001021/* State for our callback function so that it can accumulate a result. */
1022typedef struct _internal_name_mapper_state {
1023 PyObject *set;
1024 int error;
1025} _InternalNameMapperState;
1026
1027
1028/* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
1029static void
Christian Heimese8d7fa22019-09-16 14:08:55 +02001030_openssl_hash_name_mapper(const EVP_MD *md, const char *from,
1031 const char *to, void *arg)
Gregory P. Smith13b55292010-09-06 08:30:23 +00001032{
1033 _InternalNameMapperState *state = (_InternalNameMapperState *)arg;
1034 PyObject *py_name;
1035
1036 assert(state != NULL);
Christian Heimese8d7fa22019-09-16 14:08:55 +02001037 if (md == NULL)
Gregory P. Smith13b55292010-09-06 08:30:23 +00001038 return;
1039
Christian Heimese8d7fa22019-09-16 14:08:55 +02001040 py_name = py_digest_name(md);
Gregory P. Smith13b55292010-09-06 08:30:23 +00001041 if (py_name == NULL) {
1042 state->error = 1;
1043 } else {
1044 if (PySet_Add(state->set, py_name) != 0) {
Gregory P. Smith13b55292010-09-06 08:30:23 +00001045 state->error = 1;
1046 }
Christian Heimesdb816d62013-10-29 12:14:55 +01001047 Py_DECREF(py_name);
Gregory P. Smith13b55292010-09-06 08:30:23 +00001048 }
1049}
1050
1051
1052/* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
1053static PyObject*
1054generate_hash_name_list(void)
1055{
1056 _InternalNameMapperState state;
1057 state.set = PyFrozenSet_New(NULL);
1058 if (state.set == NULL)
1059 return NULL;
1060 state.error = 0;
1061
Christian Heimese8d7fa22019-09-16 14:08:55 +02001062 EVP_MD_do_all(&_openssl_hash_name_mapper, &state);
Gregory P. Smith13b55292010-09-06 08:30:23 +00001063
1064 if (state.error) {
1065 Py_DECREF(state.set);
1066 return NULL;
1067 }
1068 return state.set;
1069}
1070
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001071/* List of functions exported by this module */
1072
1073static struct PyMethodDef EVP_functions[] = {
Tal Einatc6c72372018-12-27 15:43:43 +02001074 EVP_NEW_METHODDEF
Tal Einatc6c72372018-12-27 15:43:43 +02001075 PBKDF2_HMAC_METHODDEF
Christian Heimes39093e92016-09-06 20:22:28 +02001076 _HASHLIB_SCRYPT_METHODDEF
Christian Heimes2f050c72018-01-27 09:53:43 +01001077 _HASHLIB_HMAC_DIGEST_METHODDEF
Miss Islington (bot)67b90a02019-09-12 06:03:50 -07001078 _HASHLIB_OPENSSL_MD5_METHODDEF
1079 _HASHLIB_OPENSSL_SHA1_METHODDEF
1080 _HASHLIB_OPENSSL_SHA224_METHODDEF
1081 _HASHLIB_OPENSSL_SHA256_METHODDEF
1082 _HASHLIB_OPENSSL_SHA384_METHODDEF
1083 _HASHLIB_OPENSSL_SHA512_METHODDEF
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001084 {NULL, NULL} /* Sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001085};
1086
1087
1088/* Initialize this module. */
1089
Martin v. Löwis1a214512008-06-11 05:26:20 +00001090
1091static struct PyModuleDef _hashlibmodule = {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +00001092 PyModuleDef_HEAD_INIT,
1093 "_hashlib",
1094 NULL,
1095 -1,
1096 EVP_functions,
1097 NULL,
1098 NULL,
1099 NULL,
1100 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001101};
1102
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001103PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001104PyInit__hashlib(void)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001105{
Gregory P. Smith13b55292010-09-06 08:30:23 +00001106 PyObject *m, *openssl_md_meth_names;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001107
Miss Islington (bot)1ecc75a2019-09-16 12:48:03 -07001108#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
Christian Heimesc941e622017-09-05 15:47:11 +02001109 /* Load all digest algorithms and initialize cpuid */
1110 OPENSSL_add_all_algorithms_noconf();
Christian Heimesb7ddbc82013-10-21 19:48:22 +02001111 ERR_load_crypto_strings();
Christian Heimesc941e622017-09-05 15:47:11 +02001112#endif
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001113
1114 /* TODO build EVP_functions openssl_* entries dynamically based
1115 * on what hashes are supported rather than listing many
1116 * but having some be unsupported. Only init appropriate
1117 * constants. */
1118
Christian Heimes90aa7642007-12-19 02:45:37 +00001119 Py_TYPE(&EVPtype) = &PyType_Type;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001120 if (PyType_Ready(&EVPtype) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001121 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001122
Martin v. Löwis1a214512008-06-11 05:26:20 +00001123 m = PyModule_Create(&_hashlibmodule);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001124 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001125 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001126
Gregory P. Smith13b55292010-09-06 08:30:23 +00001127 openssl_md_meth_names = generate_hash_name_list();
1128 if (openssl_md_meth_names == NULL) {
1129 Py_DECREF(m);
1130 return NULL;
1131 }
1132 if (PyModule_AddObject(m, "openssl_md_meth_names", openssl_md_meth_names)) {
1133 Py_DECREF(m);
1134 return NULL;
1135 }
1136
Christian Heimes327dd732013-10-22 15:05:23 +02001137 Py_INCREF((PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001138 PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001139
Martin v. Löwis1a214512008-06-11 05:26:20 +00001140 return m;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001141}