blob: e560c18b63c348c49827cde80ac1cdaae906040f [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
29#define MUNCH_SIZE INT_MAX
30
Christian Heimes598894f2016-09-05 23:19:05 +020031#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
32/* OpenSSL < 1.1.0 */
33#define EVP_MD_CTX_new EVP_MD_CTX_create
34#define EVP_MD_CTX_free EVP_MD_CTX_destroy
35#define HAS_FAST_PKCS5_PBKDF2_HMAC 0
36#include <openssl/hmac.h>
37#else
38/* OpenSSL >= 1.1.0 */
39#define HAS_FAST_PKCS5_PBKDF2_HMAC 1
40#endif
41
Gregory P. Smith3f61d612009-05-04 00:45:33 +000042
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000043typedef struct {
44 PyObject_HEAD
45 PyObject *name; /* name of this hash algorithm */
Christian Heimes598894f2016-09-05 23:19:05 +020046 EVP_MD_CTX *ctx; /* OpenSSL message digest context */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +000047 PyThread_type_lock lock; /* OpenSSL context lock */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000048} EVPobject;
49
50
51static PyTypeObject EVPtype;
52
53
54#define DEFINE_CONSTS_FOR_NEW(Name) \
Gregory P. Smithaded2e52013-02-01 17:05:29 -080055 static PyObject *CONST_ ## Name ## _name_obj = NULL; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000056 static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
57
Neal Norwitzf0459142006-01-07 21:20:24 +000058DEFINE_CONSTS_FOR_NEW(md5)
59DEFINE_CONSTS_FOR_NEW(sha1)
60DEFINE_CONSTS_FOR_NEW(sha224)
61DEFINE_CONSTS_FOR_NEW(sha256)
62DEFINE_CONSTS_FOR_NEW(sha384)
63DEFINE_CONSTS_FOR_NEW(sha512)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000064
Tal Einatc6c72372018-12-27 15:43:43 +020065#include "clinic/_hashopenssl.c.h"
66/*[clinic input]
67module _hashlib
68class _hashlib.HASH "EVPobject *" "&EVPtype"
69[clinic start generated code]*/
70/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a881a5092eecad28]*/
71
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000072
Christian Heimes598894f2016-09-05 23:19:05 +020073/* LCOV_EXCL_START */
74static PyObject *
75_setException(PyObject *exc)
76{
77 unsigned long errcode;
78 const char *lib, *func, *reason;
79
80 errcode = ERR_peek_last_error();
81 if (!errcode) {
82 PyErr_SetString(exc, "unknown reasons");
83 return NULL;
84 }
85 ERR_clear_error();
86
87 lib = ERR_lib_error_string(errcode);
88 func = ERR_func_error_string(errcode);
89 reason = ERR_reason_error_string(errcode);
90
91 if (lib && func) {
92 PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
93 }
94 else if (lib) {
95 PyErr_Format(exc, "[%s] %s", lib, reason);
96 }
97 else {
98 PyErr_SetString(exc, reason);
99 }
100 return NULL;
101}
102/* LCOV_EXCL_STOP */
103
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000104static EVPobject *
105newEVPobject(PyObject *name)
106{
107 EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
Christian Heimes598894f2016-09-05 23:19:05 +0200108 if (retval == NULL) {
109 return NULL;
110 }
111
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000112 /* save the name for .name to return */
Christian Heimes598894f2016-09-05 23:19:05 +0200113 Py_INCREF(name);
114 retval->name = name;
Christian Heimes598894f2016-09-05 23:19:05 +0200115 retval->lock = NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000116
Christian Heimesb7bc2832019-03-04 16:45:41 +0100117 retval->ctx = EVP_MD_CTX_new();
118 if (retval->ctx == NULL) {
119 Py_DECREF(retval);
120 PyErr_NoMemory();
121 return NULL;
122 }
123
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000124 return retval;
125}
126
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000127static void
128EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
129{
130 unsigned int process;
131 const unsigned char *cp = (const unsigned char *)vp;
132 while (0 < len) {
133 if (len > (Py_ssize_t)MUNCH_SIZE)
134 process = MUNCH_SIZE;
135 else
136 process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700137 if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
138 _setException(PyExc_ValueError);
139 break;
140 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000141 len -= process;
142 cp += process;
143 }
144}
145
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000146/* Internal methods for a hash object */
147
148static void
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000149EVP_dealloc(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000150{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000151 if (self->lock != NULL)
152 PyThread_free_lock(self->lock);
Christian Heimes598894f2016-09-05 23:19:05 +0200153 EVP_MD_CTX_free(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000154 Py_XDECREF(self->name);
155 PyObject_Del(self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000156}
157
Christian Heimes598894f2016-09-05 23:19:05 +0200158static int
159locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000160{
Christian Heimes598894f2016-09-05 23:19:05 +0200161 int result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000162 ENTER_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200163 result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000164 LEAVE_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200165 return result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000166}
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000167
168/* External methods for a hash object */
169
Tal Einatc6c72372018-12-27 15:43:43 +0200170/*[clinic input]
171_hashlib.HASH.copy as EVP_copy
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000172
Tal Einatc6c72372018-12-27 15:43:43 +0200173Return a copy of the hash object.
174[clinic start generated code]*/
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000175
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000176static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200177EVP_copy_impl(EVPobject *self)
178/*[clinic end generated code: output=b370c21cdb8ca0b4 input=31455b6a3e638069]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000179{
180 EVPobject *newobj;
181
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000182 if ( (newobj = newEVPobject(self->name))==NULL)
183 return NULL;
184
Christian Heimes598894f2016-09-05 23:19:05 +0200185 if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
Christian Heimesb7bc2832019-03-04 16:45:41 +0100186 Py_DECREF(newobj);
Christian Heimes598894f2016-09-05 23:19:05 +0200187 return _setException(PyExc_ValueError);
188 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000189 return (PyObject *)newobj;
190}
191
Tal Einatc6c72372018-12-27 15:43:43 +0200192/*[clinic input]
193_hashlib.HASH.digest as EVP_digest
194
195Return the digest value as a bytes object.
196[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000197
198static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200199EVP_digest_impl(EVPobject *self)
200/*[clinic end generated code: output=0f6a3a0da46dc12d input=03561809a419bf00]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000201{
202 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200203 EVP_MD_CTX *temp_ctx;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000204 PyObject *retval;
205 unsigned int digest_size;
206
Christian Heimes598894f2016-09-05 23:19:05 +0200207 temp_ctx = EVP_MD_CTX_new();
208 if (temp_ctx == NULL) {
209 PyErr_NoMemory();
210 return NULL;
211 }
212
213 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
214 return _setException(PyExc_ValueError);
215 }
216 digest_size = EVP_MD_CTX_size(temp_ctx);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700217 if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
218 _setException(PyExc_ValueError);
219 return NULL;
220 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000221
Christian Heimes72b710a2008-05-26 13:28:38 +0000222 retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
Christian Heimes598894f2016-09-05 23:19:05 +0200223 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000224 return retval;
225}
226
Tal Einatc6c72372018-12-27 15:43:43 +0200227/*[clinic input]
228_hashlib.HASH.hexdigest as EVP_hexdigest
229
230Return the digest value as a string of hexadecimal digits.
231[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000232
233static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200234EVP_hexdigest_impl(EVPobject *self)
235/*[clinic end generated code: output=18e6decbaf197296 input=aff9cf0e4c741a9a]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000236{
237 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200238 EVP_MD_CTX *temp_ctx;
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000239 unsigned int digest_size;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000240
Christian Heimes598894f2016-09-05 23:19:05 +0200241 temp_ctx = EVP_MD_CTX_new();
242 if (temp_ctx == NULL) {
243 PyErr_NoMemory();
244 return NULL;
245 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000246
Christian Heimes598894f2016-09-05 23:19:05 +0200247 /* Get the raw (binary) digest value */
248 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
249 return _setException(PyExc_ValueError);
250 }
251 digest_size = EVP_MD_CTX_size(temp_ctx);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700252 if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
253 _setException(PyExc_ValueError);
254 return NULL;
255 }
Christian Heimes598894f2016-09-05 23:19:05 +0200256
257 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000258
Benjamin Petersone5024512018-09-12 12:06:42 -0700259 return _Py_strhex((const char *)digest, (Py_ssize_t)digest_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000260}
261
Tal Einatc6c72372018-12-27 15:43:43 +0200262/*[clinic input]
263_hashlib.HASH.update as EVP_update
264
265 obj: object
266 /
267
268Update this hash object's state with the provided string.
269[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000270
271static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200272EVP_update(EVPobject *self, PyObject *obj)
273/*[clinic end generated code: output=ec1d55ed2432e966 input=9b30ec848f015501]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000274{
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000275 Py_buffer view;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000276
Gregory P. Smith365a1862009-02-12 07:35:29 +0000277 GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000278
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000279 if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
280 self->lock = PyThread_allocate_lock();
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000281 /* fail? lock = NULL and we fail over to non-threaded code. */
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000282 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000283
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000284 if (self->lock != NULL) {
285 Py_BEGIN_ALLOW_THREADS
286 PyThread_acquire_lock(self->lock, 1);
287 EVP_hash(self, view.buf, view.len);
288 PyThread_release_lock(self->lock);
289 Py_END_ALLOW_THREADS
290 } else {
291 EVP_hash(self, view.buf, view.len);
292 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000293
294 PyBuffer_Release(&view);
295 Py_RETURN_NONE;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000296}
297
298static PyMethodDef EVP_methods[] = {
Tal Einatc6c72372018-12-27 15:43:43 +0200299 EVP_UPDATE_METHODDEF
300 EVP_DIGEST_METHODDEF
301 EVP_HEXDIGEST_METHODDEF
302 EVP_COPY_METHODDEF
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000303 {NULL, NULL} /* sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000304};
305
306static PyObject *
307EVP_get_block_size(EVPobject *self, void *closure)
308{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000309 long block_size;
Christian Heimes598894f2016-09-05 23:19:05 +0200310 block_size = EVP_MD_CTX_block_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000311 return PyLong_FromLong(block_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000312}
313
314static PyObject *
315EVP_get_digest_size(EVPobject *self, void *closure)
316{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000317 long size;
Christian Heimes598894f2016-09-05 23:19:05 +0200318 size = EVP_MD_CTX_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000319 return PyLong_FromLong(size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000320}
321
322static PyMemberDef EVP_members[] = {
323 {"name", T_OBJECT, offsetof(EVPobject, name), READONLY, PyDoc_STR("algorithm name.")},
324 {NULL} /* Sentinel */
325};
326
327static PyGetSetDef EVP_getseters[] = {
328 {"digest_size",
329 (getter)EVP_get_digest_size, NULL,
330 NULL,
331 NULL},
332 {"block_size",
333 (getter)EVP_get_block_size, NULL,
334 NULL,
335 NULL},
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000336 {NULL} /* Sentinel */
337};
338
339
340static PyObject *
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000341EVP_repr(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000342{
Victor Stinner3f1af5c2010-03-12 17:00:41 +0000343 return PyUnicode_FromFormat("<%U HASH object @ %p>", self->name, self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000344}
345
Gregory P. Smithc7e21912018-12-30 17:54:53 -0800346PyDoc_STRVAR(hashtype_doc,
347"HASH(name, string=b\'\')\n"
348"--\n"
349"\n"
350"A hash is an object used to calculate a checksum of a string of information.\n"
351"\n"
352"Methods:\n"
353"\n"
354"update() -- updates the current digest with an additional string\n"
355"digest() -- return the current digest value\n"
356"hexdigest() -- return the current digest as a string of hexadecimal digits\n"
357"copy() -- return a copy of the current hash object\n"
358"\n"
359"Attributes:\n"
360"\n"
361"name -- the hash algorithm being used by this object\n"
362"digest_size -- number of bytes in this hashes output");
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000363
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000364static PyTypeObject EVPtype = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000365 PyVarObject_HEAD_INIT(NULL, 0)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000366 "_hashlib.HASH", /*tp_name*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000367 sizeof(EVPobject), /*tp_basicsize*/
368 0, /*tp_itemsize*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000369 /* methods */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000370 (destructor)EVP_dealloc, /*tp_dealloc*/
371 0, /*tp_print*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000372 0, /*tp_getattr*/
373 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000374 0, /*tp_reserved*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000375 (reprfunc)EVP_repr, /*tp_repr*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000376 0, /*tp_as_number*/
377 0, /*tp_as_sequence*/
378 0, /*tp_as_mapping*/
379 0, /*tp_hash*/
380 0, /*tp_call*/
381 0, /*tp_str*/
382 0, /*tp_getattro*/
383 0, /*tp_setattro*/
384 0, /*tp_as_buffer*/
385 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
Gregory P. Smithc7e21912018-12-30 17:54:53 -0800386 hashtype_doc, /*tp_doc*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000387 0, /*tp_traverse*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000388 0, /*tp_clear*/
389 0, /*tp_richcompare*/
390 0, /*tp_weaklistoffset*/
391 0, /*tp_iter*/
392 0, /*tp_iternext*/
393 EVP_methods, /* tp_methods */
394 EVP_members, /* tp_members */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000395 EVP_getseters, /* tp_getset */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000396 0, /* tp_base */
397 0, /* tp_dict */
398 0, /* tp_descr_get */
399 0, /* tp_descr_set */
400 0, /* tp_dictoffset */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000401};
402
403static PyObject *
404EVPnew(PyObject *name_obj,
405 const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000406 const unsigned char *cp, Py_ssize_t len)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000407{
408 EVPobject *self;
409
410 if (!digest && !initial_ctx) {
411 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
412 return NULL;
413 }
414
415 if ((self = newEVPobject(name_obj)) == NULL)
416 return NULL;
417
418 if (initial_ctx) {
Christian Heimes598894f2016-09-05 23:19:05 +0200419 EVP_MD_CTX_copy(self->ctx, initial_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000420 } else {
Gregory P. Smith07244a82017-05-24 00:04:38 -0700421 if (!EVP_DigestInit(self->ctx, digest)) {
422 _setException(PyExc_ValueError);
423 Py_DECREF(self);
424 return NULL;
425 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000426 }
427
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000428 if (cp && len) {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000429 if (len >= HASHLIB_GIL_MINSIZE) {
430 Py_BEGIN_ALLOW_THREADS
431 EVP_hash(self, cp, len);
432 Py_END_ALLOW_THREADS
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000433 } else {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000434 EVP_hash(self, cp, len);
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000435 }
436 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000437
438 return (PyObject *)self;
439}
440
441
442/* The module-level function: new() */
443
Tal Einatc6c72372018-12-27 15:43:43 +0200444/*[clinic input]
445_hashlib.new as EVP_new
446
447 name as name_obj: object
448 string as data_obj: object(py_default="b''") = NULL
449
450Return a new hash object using the named algorithm.
451
452An optional string argument may be provided and will be
453automatically hashed.
454
455The MD5 and SHA1 algorithms are always supported.
456[clinic start generated code]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000457
458static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200459EVP_new_impl(PyObject *module, PyObject *name_obj, PyObject *data_obj)
460/*[clinic end generated code: output=9e7cf664e04b0226 input=1c46e40e0fec91f3]*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000461{
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000462 Py_buffer view = { 0 };
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000463 PyObject *ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000464 char *name;
465 const EVP_MD *digest;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000466
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000467 if (!PyArg_Parse(name_obj, "s", &name)) {
468 PyErr_SetString(PyExc_TypeError, "name must be a string");
469 return NULL;
470 }
471
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000472 if (data_obj)
Gregory P. Smith365a1862009-02-12 07:35:29 +0000473 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000474
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000475 digest = EVP_get_digestbyname(name);
476
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000477 ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000478
479 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000480 PyBuffer_Release(&view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000481 return ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000482}
483
Christian Heimes351f5392013-10-19 17:59:48 +0200484#if (OPENSSL_VERSION_NUMBER >= 0x10000000 && !defined(OPENSSL_NO_HMAC) \
485 && !defined(OPENSSL_NO_SHA))
Christian Heimese7236222013-10-19 14:24:44 +0200486
Christian Heimese92ef132013-10-13 00:52:43 +0200487#define PY_PBKDF2_HMAC 1
488
Christian Heimes598894f2016-09-05 23:19:05 +0200489#if !HAS_FAST_PKCS5_PBKDF2_HMAC
Christian Heimese7236222013-10-19 14:24:44 +0200490/* Improved implementation of PKCS5_PBKDF2_HMAC()
491 *
492 * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
493 * `iter` times. Today (2013) the iteration count is typically 100,000 or
494 * more. The improved algorithm is not subject to a Denial-of-Service
495 * vulnerability with overly large passwords.
496 *
497 * Also OpenSSL < 1.0 don't provide PKCS5_PBKDF2_HMAC(), only
498 * PKCS5_PBKDF2_SHA1.
499 */
Christian Heimesc6564b92013-10-20 13:23:03 +0200500static int
501PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen,
502 const unsigned char *salt, int saltlen,
503 int iter, const EVP_MD *digest,
504 int keylen, unsigned char *out)
Christian Heimese7236222013-10-19 14:24:44 +0200505{
506 unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
507 int cplen, j, k, tkeylen, mdlen;
508 unsigned long i = 1;
509 HMAC_CTX hctx_tpl, hctx;
510
511 mdlen = EVP_MD_size(digest);
512 if (mdlen < 0)
513 return 0;
514
515 HMAC_CTX_init(&hctx_tpl);
516 HMAC_CTX_init(&hctx);
517 p = out;
518 tkeylen = keylen;
Christian Heimese7236222013-10-19 14:24:44 +0200519 if (!HMAC_Init_ex(&hctx_tpl, pass, passlen, digest, NULL)) {
520 HMAC_CTX_cleanup(&hctx_tpl);
521 return 0;
522 }
Benjamin Peterson3c0769d2015-09-27 02:13:40 -0700523 while (tkeylen) {
524 if (tkeylen > mdlen)
Christian Heimese7236222013-10-19 14:24:44 +0200525 cplen = mdlen;
526 else
527 cplen = tkeylen;
528 /* We are unlikely to ever use more than 256 blocks (5120 bits!)
529 * but just in case...
530 */
531 itmp[0] = (unsigned char)((i >> 24) & 0xff);
532 itmp[1] = (unsigned char)((i >> 16) & 0xff);
533 itmp[2] = (unsigned char)((i >> 8) & 0xff);
534 itmp[3] = (unsigned char)(i & 0xff);
535 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
536 HMAC_CTX_cleanup(&hctx_tpl);
537 return 0;
538 }
539 if (!HMAC_Update(&hctx, salt, saltlen)
540 || !HMAC_Update(&hctx, itmp, 4)
541 || !HMAC_Final(&hctx, digtmp, NULL)) {
542 HMAC_CTX_cleanup(&hctx_tpl);
543 HMAC_CTX_cleanup(&hctx);
544 return 0;
545 }
Christian Heimes68531082013-11-06 17:25:17 +0100546 HMAC_CTX_cleanup(&hctx);
Christian Heimese7236222013-10-19 14:24:44 +0200547 memcpy(p, digtmp, cplen);
548 for (j = 1; j < iter; j++) {
549 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
550 HMAC_CTX_cleanup(&hctx_tpl);
551 return 0;
552 }
553 if (!HMAC_Update(&hctx, digtmp, mdlen)
554 || !HMAC_Final(&hctx, digtmp, NULL)) {
555 HMAC_CTX_cleanup(&hctx_tpl);
556 HMAC_CTX_cleanup(&hctx);
557 return 0;
558 }
559 HMAC_CTX_cleanup(&hctx);
560 for (k = 0; k < cplen; k++) {
561 p[k] ^= digtmp[k];
562 }
563 }
564 tkeylen-= cplen;
565 i++;
566 p+= cplen;
567 }
568 HMAC_CTX_cleanup(&hctx_tpl);
569 return 1;
570}
Christian Heimes598894f2016-09-05 23:19:05 +0200571#endif
Christian Heimese7236222013-10-19 14:24:44 +0200572
573
Tal Einatc6c72372018-12-27 15:43:43 +0200574
575/*[clinic input]
576_hashlib.pbkdf2_hmac as pbkdf2_hmac
577
578 hash_name: str
579 password: Py_buffer
580 salt: Py_buffer
581 iterations: long
582 dklen as dklen_obj: object = None
583
584Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function.
585[clinic start generated code]*/
Christian Heimese92ef132013-10-13 00:52:43 +0200586
587static PyObject *
Tal Einatc6c72372018-12-27 15:43:43 +0200588pbkdf2_hmac_impl(PyObject *module, const char *hash_name,
589 Py_buffer *password, Py_buffer *salt, long iterations,
590 PyObject *dklen_obj)
591/*[clinic end generated code: output=144b76005416599b input=ed3ab0d2d28b5d5c]*/
Christian Heimese92ef132013-10-13 00:52:43 +0200592{
Tal Einatc6c72372018-12-27 15:43:43 +0200593 PyObject *key_obj = NULL;
594 char *key;
595 long dklen;
Christian Heimese92ef132013-10-13 00:52:43 +0200596 int retval;
597 const EVP_MD *digest;
598
Tal Einatc6c72372018-12-27 15:43:43 +0200599 digest = EVP_get_digestbyname(hash_name);
Christian Heimese92ef132013-10-13 00:52:43 +0200600 if (digest == NULL) {
601 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
602 goto end;
603 }
604
Tal Einatc6c72372018-12-27 15:43:43 +0200605 if (password->len > INT_MAX) {
Christian Heimese92ef132013-10-13 00:52:43 +0200606 PyErr_SetString(PyExc_OverflowError,
607 "password is too long.");
608 goto end;
609 }
610
Tal Einatc6c72372018-12-27 15:43:43 +0200611 if (salt->len > INT_MAX) {
Christian Heimese92ef132013-10-13 00:52:43 +0200612 PyErr_SetString(PyExc_OverflowError,
613 "salt is too long.");
614 goto end;
615 }
616
617 if (iterations < 1) {
618 PyErr_SetString(PyExc_ValueError,
619 "iteration value must be greater than 0.");
620 goto end;
621 }
622 if (iterations > INT_MAX) {
623 PyErr_SetString(PyExc_OverflowError,
624 "iteration value is too great.");
625 goto end;
626 }
627
628 if (dklen_obj == Py_None) {
629 dklen = EVP_MD_size(digest);
630 } else {
631 dklen = PyLong_AsLong(dklen_obj);
632 if ((dklen == -1) && PyErr_Occurred()) {
633 goto end;
634 }
635 }
636 if (dklen < 1) {
637 PyErr_SetString(PyExc_ValueError,
638 "key length must be greater than 0.");
639 goto end;
640 }
641 if (dklen > INT_MAX) {
642 /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
643 PyErr_SetString(PyExc_OverflowError,
644 "key length is too great.");
645 goto end;
646 }
647
648 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
649 if (key_obj == NULL) {
650 goto end;
651 }
652 key = PyBytes_AS_STRING(key_obj);
653
654 Py_BEGIN_ALLOW_THREADS
Christian Heimes598894f2016-09-05 23:19:05 +0200655#if HAS_FAST_PKCS5_PBKDF2_HMAC
Tal Einatc6c72372018-12-27 15:43:43 +0200656 retval = PKCS5_PBKDF2_HMAC((char*)password->buf, (int)password->len,
657 (unsigned char *)salt->buf, (int)salt->len,
Christian Heimes598894f2016-09-05 23:19:05 +0200658 iterations, digest, dklen,
659 (unsigned char *)key);
660#else
Tal Einatc6c72372018-12-27 15:43:43 +0200661 retval = PKCS5_PBKDF2_HMAC_fast((char*)password->buf, (int)password->len,
662 (unsigned char *)salt->buf, (int)salt->len,
Christian Heimese7236222013-10-19 14:24:44 +0200663 iterations, digest, dklen,
664 (unsigned char *)key);
Christian Heimes598894f2016-09-05 23:19:05 +0200665#endif
Christian Heimese92ef132013-10-13 00:52:43 +0200666 Py_END_ALLOW_THREADS
667
668 if (!retval) {
669 Py_CLEAR(key_obj);
670 _setException(PyExc_ValueError);
671 goto end;
672 }
673
674 end:
Christian Heimese92ef132013-10-13 00:52:43 +0200675 return key_obj;
676}
677
678#endif
Gregory P. Smith13b55292010-09-06 08:30:23 +0000679
Christian Heimes39093e92016-09-06 20:22:28 +0200680#if OPENSSL_VERSION_NUMBER > 0x10100000L && !defined(OPENSSL_NO_SCRYPT) && !defined(LIBRESSL_VERSION_NUMBER)
681#define PY_SCRYPT 1
682
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300683/* XXX: Parameters salt, n, r and p should be required keyword-only parameters.
684 They are optional in the Argument Clinic declaration only due to a
685 limitation of PyArg_ParseTupleAndKeywords. */
686
Christian Heimes39093e92016-09-06 20:22:28 +0200687/*[clinic input]
688_hashlib.scrypt
689
690 password: Py_buffer
691 *
692 salt: Py_buffer = None
693 n as n_obj: object(subclass_of='&PyLong_Type') = None
694 r as r_obj: object(subclass_of='&PyLong_Type') = None
695 p as p_obj: object(subclass_of='&PyLong_Type') = None
696 maxmem: long = 0
697 dklen: long = 64
698
699
700scrypt password-based key derivation function.
701[clinic start generated code]*/
702
703static PyObject *
704_hashlib_scrypt_impl(PyObject *module, Py_buffer *password, Py_buffer *salt,
705 PyObject *n_obj, PyObject *r_obj, PyObject *p_obj,
706 long maxmem, long dklen)
707/*[clinic end generated code: output=14849e2aa2b7b46c input=48a7d63bf3f75c42]*/
708{
709 PyObject *key_obj = NULL;
710 char *key;
711 int retval;
712 unsigned long n, r, p;
713
714 if (password->len > INT_MAX) {
715 PyErr_SetString(PyExc_OverflowError,
716 "password is too long.");
717 return NULL;
718 }
719
720 if (salt->buf == NULL) {
721 PyErr_SetString(PyExc_TypeError,
722 "salt is required");
723 return NULL;
724 }
725 if (salt->len > INT_MAX) {
726 PyErr_SetString(PyExc_OverflowError,
727 "salt is too long.");
728 return NULL;
729 }
730
731 n = PyLong_AsUnsignedLong(n_obj);
732 if (n == (unsigned long) -1 && PyErr_Occurred()) {
733 PyErr_SetString(PyExc_TypeError,
734 "n is required and must be an unsigned int");
735 return NULL;
736 }
737 if (n < 2 || n & (n - 1)) {
738 PyErr_SetString(PyExc_ValueError,
739 "n must be a power of 2.");
740 return NULL;
741 }
742
743 r = PyLong_AsUnsignedLong(r_obj);
744 if (r == (unsigned long) -1 && PyErr_Occurred()) {
745 PyErr_SetString(PyExc_TypeError,
746 "r is required and must be an unsigned int");
747 return NULL;
748 }
749
750 p = PyLong_AsUnsignedLong(p_obj);
751 if (p == (unsigned long) -1 && PyErr_Occurred()) {
752 PyErr_SetString(PyExc_TypeError,
753 "p is required and must be an unsigned int");
754 return NULL;
755 }
756
757 if (maxmem < 0 || maxmem > INT_MAX) {
Victor Stinner8c663fd2017-11-08 14:44:44 -0800758 /* OpenSSL 1.1.0 restricts maxmem to 32 MiB. It may change in the
Christian Heimes39093e92016-09-06 20:22:28 +0200759 future. The maxmem constant is private to OpenSSL. */
760 PyErr_Format(PyExc_ValueError,
761 "maxmem must be positive and smaller than %d",
762 INT_MAX);
763 return NULL;
764 }
765
766 if (dklen < 1 || dklen > INT_MAX) {
767 PyErr_Format(PyExc_ValueError,
768 "dklen must be greater than 0 and smaller than %d",
769 INT_MAX);
770 return NULL;
771 }
772
773 /* let OpenSSL validate the rest */
774 retval = EVP_PBE_scrypt(NULL, 0, NULL, 0, n, r, p, maxmem, NULL, 0);
775 if (!retval) {
776 /* sorry, can't do much better */
777 PyErr_SetString(PyExc_ValueError,
Emmanuel Ariasb71e28e2019-03-06 11:35:35 -0300778 "Invalid parameter combination for n, r, p, maxmem.");
Christian Heimes39093e92016-09-06 20:22:28 +0200779 return NULL;
780 }
781
782 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
783 if (key_obj == NULL) {
784 return NULL;
785 }
786 key = PyBytes_AS_STRING(key_obj);
787
788 Py_BEGIN_ALLOW_THREADS
789 retval = EVP_PBE_scrypt(
790 (const char*)password->buf, (size_t)password->len,
791 (const unsigned char *)salt->buf, (size_t)salt->len,
792 n, r, p, maxmem,
793 (unsigned char *)key, (size_t)dklen
794 );
795 Py_END_ALLOW_THREADS
796
797 if (!retval) {
798 Py_CLEAR(key_obj);
799 _setException(PyExc_ValueError);
800 return NULL;
801 }
802 return key_obj;
803}
804#endif
805
Christian Heimes2f050c72018-01-27 09:53:43 +0100806/* Fast HMAC for hmac.digest()
807 */
808
809/*[clinic input]
810_hashlib.hmac_digest
811
812 key: Py_buffer
813 msg: Py_buffer
814 digest: str
815
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300816Single-shot HMAC.
Christian Heimes2f050c72018-01-27 09:53:43 +0100817[clinic start generated code]*/
818
819static PyObject *
820_hashlib_hmac_digest_impl(PyObject *module, Py_buffer *key, Py_buffer *msg,
821 const char *digest)
Serhiy Storchakaf1d36d82018-07-31 09:50:16 +0300822/*[clinic end generated code: output=75630e684cdd8762 input=562d2f4249511bd3]*/
Christian Heimes2f050c72018-01-27 09:53:43 +0100823{
824 unsigned char md[EVP_MAX_MD_SIZE] = {0};
825 unsigned int md_len = 0;
826 unsigned char *result;
827 const EVP_MD *evp;
828
829 evp = EVP_get_digestbyname(digest);
830 if (evp == NULL) {
831 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
832 return NULL;
833 }
834 if (key->len > INT_MAX) {
835 PyErr_SetString(PyExc_OverflowError,
836 "key is too long.");
837 return NULL;
838 }
839 if (msg->len > INT_MAX) {
840 PyErr_SetString(PyExc_OverflowError,
841 "msg is too long.");
842 return NULL;
843 }
844
845 Py_BEGIN_ALLOW_THREADS
846 result = HMAC(
847 evp,
848 (const void*)key->buf, (int)key->len,
849 (const unsigned char*)msg->buf, (int)msg->len,
850 md, &md_len
851 );
852 Py_END_ALLOW_THREADS
853
854 if (result == NULL) {
855 _setException(PyExc_ValueError);
856 return NULL;
857 }
858 return PyBytes_FromStringAndSize((const char*)md, md_len);
859}
860
Gregory P. Smith13b55292010-09-06 08:30:23 +0000861/* State for our callback function so that it can accumulate a result. */
862typedef struct _internal_name_mapper_state {
863 PyObject *set;
864 int error;
865} _InternalNameMapperState;
866
867
868/* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
869static void
870_openssl_hash_name_mapper(const OBJ_NAME *openssl_obj_name, void *arg)
871{
872 _InternalNameMapperState *state = (_InternalNameMapperState *)arg;
873 PyObject *py_name;
874
875 assert(state != NULL);
876 if (openssl_obj_name == NULL)
877 return;
878 /* Ignore aliased names, they pollute the list and OpenSSL appears to
Martin Panter7462b6492015-11-02 03:37:02 +0000879 * have its own definition of alias as the resulting list still
Gregory P. Smith13b55292010-09-06 08:30:23 +0000880 * contains duplicate and alternate names for several algorithms. */
881 if (openssl_obj_name->alias)
882 return;
883
884 py_name = PyUnicode_FromString(openssl_obj_name->name);
885 if (py_name == NULL) {
886 state->error = 1;
887 } else {
888 if (PySet_Add(state->set, py_name) != 0) {
Gregory P. Smith13b55292010-09-06 08:30:23 +0000889 state->error = 1;
890 }
Christian Heimesdb816d62013-10-29 12:14:55 +0100891 Py_DECREF(py_name);
Gregory P. Smith13b55292010-09-06 08:30:23 +0000892 }
893}
894
895
896/* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
897static PyObject*
898generate_hash_name_list(void)
899{
900 _InternalNameMapperState state;
901 state.set = PyFrozenSet_New(NULL);
902 if (state.set == NULL)
903 return NULL;
904 state.error = 0;
905
906 OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, &_openssl_hash_name_mapper, &state);
907
908 if (state.error) {
909 Py_DECREF(state.set);
910 return NULL;
911 }
912 return state.set;
913}
914
915
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000916/*
917 * This macro generates constructor function definitions for specific
918 * hash algorithms. These constructors are much faster than calling
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700919 * the generic one passing it a python string and are noticeably
Leo Ariasc3d95082018-02-03 18:36:10 -0600920 * faster than calling a python new() wrapper. That is important for
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000921 * code that wants to make hashes of a bunch of small strings.
Gregory P. Smith07244a82017-05-24 00:04:38 -0700922 * The first call will lazy-initialize, which reports an exception
923 * if initialization fails.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000924 */
925#define GEN_CONSTRUCTOR(NAME) \
926 static PyObject * \
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200927 EVP_new_ ## NAME (PyObject *self, PyObject *const *args, Py_ssize_t nargs) \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000928 { \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000929 PyObject *data_obj = NULL; \
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000930 Py_buffer view = { 0 }; \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000931 PyObject *ret_obj; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000932 \
Sylvain96c7c062017-06-15 17:05:23 +0200933 if (!_PyArg_ParseStack(args, nargs, "|O:" #NAME , &data_obj)) { \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000934 return NULL; \
935 } \
936 \
Gregory P. Smith07244a82017-05-24 00:04:38 -0700937 if (CONST_new_ ## NAME ## _ctx_p == NULL) { \
938 EVP_MD_CTX *ctx_p = EVP_MD_CTX_new(); \
939 if (!EVP_get_digestbyname(#NAME) || \
940 !EVP_DigestInit(ctx_p, EVP_get_digestbyname(#NAME))) { \
941 _setException(PyExc_ValueError); \
942 EVP_MD_CTX_free(ctx_p); \
943 return NULL; \
944 } \
945 CONST_new_ ## NAME ## _ctx_p = ctx_p; \
946 } \
947 \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000948 if (data_obj) \
Gregory P. Smith365a1862009-02-12 07:35:29 +0000949 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000950 \
951 ret_obj = EVPnew( \
952 CONST_ ## NAME ## _name_obj, \
953 NULL, \
954 CONST_new_ ## NAME ## _ctx_p, \
955 (unsigned char*)view.buf, \
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000956 view.len); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000957 \
958 if (data_obj) \
Martin v. Löwis423be952008-08-13 15:53:07 +0000959 PyBuffer_Release(&view); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000960 return ret_obj; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000961 }
962
963/* a PyMethodDef structure for the constructor */
964#define CONSTRUCTOR_METH_DEF(NAME) \
Serhiy Storchaka62be7422018-11-27 13:27:31 +0200965 {"openssl_" #NAME, (PyCFunction)(void(*)(void))EVP_new_ ## NAME, METH_FASTCALL, \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000966 PyDoc_STR("Returns a " #NAME \
967 " hash object; optionally initialized with a string") \
968 }
969
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800970/* used in the init function to setup a constructor: initialize OpenSSL
971 constructor constants if they haven't been initialized already. */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000972#define INIT_CONSTRUCTOR_CONSTANTS(NAME) do { \
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800973 if (CONST_ ## NAME ## _name_obj == NULL) { \
974 CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000975 } \
976} while (0);
977
978GEN_CONSTRUCTOR(md5)
979GEN_CONSTRUCTOR(sha1)
980GEN_CONSTRUCTOR(sha224)
981GEN_CONSTRUCTOR(sha256)
982GEN_CONSTRUCTOR(sha384)
983GEN_CONSTRUCTOR(sha512)
984
985/* List of functions exported by this module */
986
987static struct PyMethodDef EVP_functions[] = {
Tal Einatc6c72372018-12-27 15:43:43 +0200988 EVP_NEW_METHODDEF
Christian Heimese92ef132013-10-13 00:52:43 +0200989#ifdef PY_PBKDF2_HMAC
Tal Einatc6c72372018-12-27 15:43:43 +0200990 PBKDF2_HMAC_METHODDEF
Christian Heimese92ef132013-10-13 00:52:43 +0200991#endif
Christian Heimes39093e92016-09-06 20:22:28 +0200992 _HASHLIB_SCRYPT_METHODDEF
Christian Heimes2f050c72018-01-27 09:53:43 +0100993 _HASHLIB_HMAC_DIGEST_METHODDEF
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000994 CONSTRUCTOR_METH_DEF(md5),
995 CONSTRUCTOR_METH_DEF(sha1),
996 CONSTRUCTOR_METH_DEF(sha224),
997 CONSTRUCTOR_METH_DEF(sha256),
998 CONSTRUCTOR_METH_DEF(sha384),
999 CONSTRUCTOR_METH_DEF(sha512),
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001000 {NULL, NULL} /* Sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001001};
1002
1003
1004/* Initialize this module. */
1005
Martin v. Löwis1a214512008-06-11 05:26:20 +00001006
1007static struct PyModuleDef _hashlibmodule = {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +00001008 PyModuleDef_HEAD_INIT,
1009 "_hashlib",
1010 NULL,
1011 -1,
1012 EVP_functions,
1013 NULL,
1014 NULL,
1015 NULL,
1016 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001017};
1018
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001019PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001020PyInit__hashlib(void)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001021{
Gregory P. Smith13b55292010-09-06 08:30:23 +00001022 PyObject *m, *openssl_md_meth_names;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001023
Christian Heimesc941e622017-09-05 15:47:11 +02001024#ifndef OPENSSL_VERSION_1_1
1025 /* Load all digest algorithms and initialize cpuid */
1026 OPENSSL_add_all_algorithms_noconf();
Christian Heimesb7ddbc82013-10-21 19:48:22 +02001027 ERR_load_crypto_strings();
Christian Heimesc941e622017-09-05 15:47:11 +02001028#endif
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001029
1030 /* TODO build EVP_functions openssl_* entries dynamically based
1031 * on what hashes are supported rather than listing many
1032 * but having some be unsupported. Only init appropriate
1033 * constants. */
1034
Christian Heimes90aa7642007-12-19 02:45:37 +00001035 Py_TYPE(&EVPtype) = &PyType_Type;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001036 if (PyType_Ready(&EVPtype) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001037 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001038
Martin v. Löwis1a214512008-06-11 05:26:20 +00001039 m = PyModule_Create(&_hashlibmodule);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001040 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001041 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001042
Gregory P. Smith13b55292010-09-06 08:30:23 +00001043 openssl_md_meth_names = generate_hash_name_list();
1044 if (openssl_md_meth_names == NULL) {
1045 Py_DECREF(m);
1046 return NULL;
1047 }
1048 if (PyModule_AddObject(m, "openssl_md_meth_names", openssl_md_meth_names)) {
1049 Py_DECREF(m);
1050 return NULL;
1051 }
1052
Christian Heimes327dd732013-10-22 15:05:23 +02001053 Py_INCREF((PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001054 PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001055
1056 /* these constants are used by the convenience constructors */
1057 INIT_CONSTRUCTOR_CONSTANTS(md5);
1058 INIT_CONSTRUCTOR_CONSTANTS(sha1);
1059 INIT_CONSTRUCTOR_CONSTANTS(sha224);
1060 INIT_CONSTRUCTOR_CONSTANTS(sha256);
1061 INIT_CONSTRUCTOR_CONSTANTS(sha384);
1062 INIT_CONSTRUCTOR_CONSTANTS(sha512);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001063 return m;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001064}