blob: 986c10be52fc08baf0fc3a357c8b6d3ce379b21c [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>
Gregory P. Smith13b55292010-09-06 08:30:23 +000024/* We use the object interface to discover what hashes OpenSSL supports. */
25#include <openssl/objects.h>
Christian Heimese92ef132013-10-13 00:52:43 +020026#include "openssl/err.h"
Gregory P. Smith3f61d612009-05-04 00:45:33 +000027
28#define MUNCH_SIZE INT_MAX
29
Gregory P. Smith3f61d612009-05-04 00:45:33 +000030#ifndef HASH_OBJ_CONSTRUCTOR
31#define HASH_OBJ_CONSTRUCTOR 0
32#endif
33
Christian Heimes598894f2016-09-05 23:19:05 +020034#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
35/* OpenSSL < 1.1.0 */
36#define EVP_MD_CTX_new EVP_MD_CTX_create
37#define EVP_MD_CTX_free EVP_MD_CTX_destroy
38#define HAS_FAST_PKCS5_PBKDF2_HMAC 0
39#include <openssl/hmac.h>
40#else
41/* OpenSSL >= 1.1.0 */
42#define HAS_FAST_PKCS5_PBKDF2_HMAC 1
43#endif
44
Gregory P. Smith3f61d612009-05-04 00:45:33 +000045
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000046typedef struct {
47 PyObject_HEAD
48 PyObject *name; /* name of this hash algorithm */
Christian Heimes598894f2016-09-05 23:19:05 +020049 EVP_MD_CTX *ctx; /* OpenSSL message digest context */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +000050#ifdef WITH_THREAD
51 PyThread_type_lock lock; /* OpenSSL context lock */
52#endif
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000053} EVPobject;
54
55
56static PyTypeObject EVPtype;
57
58
59#define DEFINE_CONSTS_FOR_NEW(Name) \
Gregory P. Smithaded2e52013-02-01 17:05:29 -080060 static PyObject *CONST_ ## Name ## _name_obj = NULL; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000061 static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
62
Neal Norwitzf0459142006-01-07 21:20:24 +000063DEFINE_CONSTS_FOR_NEW(md5)
64DEFINE_CONSTS_FOR_NEW(sha1)
65DEFINE_CONSTS_FOR_NEW(sha224)
66DEFINE_CONSTS_FOR_NEW(sha256)
67DEFINE_CONSTS_FOR_NEW(sha384)
68DEFINE_CONSTS_FOR_NEW(sha512)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000069
70
Christian Heimes598894f2016-09-05 23:19:05 +020071/* LCOV_EXCL_START */
72static PyObject *
73_setException(PyObject *exc)
74{
75 unsigned long errcode;
76 const char *lib, *func, *reason;
77
78 errcode = ERR_peek_last_error();
79 if (!errcode) {
80 PyErr_SetString(exc, "unknown reasons");
81 return NULL;
82 }
83 ERR_clear_error();
84
85 lib = ERR_lib_error_string(errcode);
86 func = ERR_func_error_string(errcode);
87 reason = ERR_reason_error_string(errcode);
88
89 if (lib && func) {
90 PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
91 }
92 else if (lib) {
93 PyErr_Format(exc, "[%s] %s", lib, reason);
94 }
95 else {
96 PyErr_SetString(exc, reason);
97 }
98 return NULL;
99}
100/* LCOV_EXCL_STOP */
101
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000102static EVPobject *
103newEVPobject(PyObject *name)
104{
105 EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
Christian Heimes598894f2016-09-05 23:19:05 +0200106 if (retval == NULL) {
107 return NULL;
108 }
109
110 retval->ctx = EVP_MD_CTX_new();
111 if (retval->ctx == NULL) {
112 PyErr_NoMemory();
113 return NULL;
114 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000115
116 /* save the name for .name to return */
Christian Heimes598894f2016-09-05 23:19:05 +0200117 Py_INCREF(name);
118 retval->name = name;
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000119#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +0200120 retval->lock = NULL;
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000121#endif
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000122
123 return retval;
124}
125
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000126static void
127EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
128{
129 unsigned int process;
130 const unsigned char *cp = (const unsigned char *)vp;
131 while (0 < len) {
132 if (len > (Py_ssize_t)MUNCH_SIZE)
133 process = MUNCH_SIZE;
134 else
135 process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
Christian Heimes598894f2016-09-05 23:19:05 +0200136 EVP_DigestUpdate(self->ctx, (const void*)cp, process);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000137 len -= process;
138 cp += process;
139 }
140}
141
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000142/* Internal methods for a hash object */
143
144static void
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000145EVP_dealloc(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000146{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000147#ifdef WITH_THREAD
148 if (self->lock != NULL)
149 PyThread_free_lock(self->lock);
150#endif
Christian Heimes598894f2016-09-05 23:19:05 +0200151 EVP_MD_CTX_free(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000152 Py_XDECREF(self->name);
153 PyObject_Del(self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000154}
155
Christian Heimes598894f2016-09-05 23:19:05 +0200156static int
157locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000158{
Christian Heimes598894f2016-09-05 23:19:05 +0200159 int result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000160 ENTER_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200161 result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000162 LEAVE_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200163 return result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000164}
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000165
166/* External methods for a hash object */
167
168PyDoc_STRVAR(EVP_copy__doc__, "Return a copy of the hash object.");
169
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000170
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000171static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000172EVP_copy(EVPobject *self, PyObject *unused)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000173{
174 EVPobject *newobj;
175
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000176 if ( (newobj = newEVPobject(self->name))==NULL)
177 return NULL;
178
Christian Heimes598894f2016-09-05 23:19:05 +0200179 if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
180 return _setException(PyExc_ValueError);
181 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000182 return (PyObject *)newobj;
183}
184
185PyDoc_STRVAR(EVP_digest__doc__,
186"Return the digest value as a string of binary data.");
187
188static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000189EVP_digest(EVPobject *self, PyObject *unused)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000190{
191 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200192 EVP_MD_CTX *temp_ctx;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000193 PyObject *retval;
194 unsigned int digest_size;
195
Christian Heimes598894f2016-09-05 23:19:05 +0200196 temp_ctx = EVP_MD_CTX_new();
197 if (temp_ctx == NULL) {
198 PyErr_NoMemory();
199 return NULL;
200 }
201
202 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
203 return _setException(PyExc_ValueError);
204 }
205 digest_size = EVP_MD_CTX_size(temp_ctx);
206 EVP_DigestFinal(temp_ctx, digest, NULL);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000207
Christian Heimes72b710a2008-05-26 13:28:38 +0000208 retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
Christian Heimes598894f2016-09-05 23:19:05 +0200209 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000210 return retval;
211}
212
213PyDoc_STRVAR(EVP_hexdigest__doc__,
214"Return the digest value as a string of hexadecimal digits.");
215
216static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000217EVP_hexdigest(EVPobject *self, PyObject *unused)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000218{
219 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200220 EVP_MD_CTX *temp_ctx;
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000221 unsigned int digest_size;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000222
Christian Heimes598894f2016-09-05 23:19:05 +0200223 temp_ctx = EVP_MD_CTX_new();
224 if (temp_ctx == NULL) {
225 PyErr_NoMemory();
226 return NULL;
227 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000228
Christian Heimes598894f2016-09-05 23:19:05 +0200229 /* Get the raw (binary) digest value */
230 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
231 return _setException(PyExc_ValueError);
232 }
233 digest_size = EVP_MD_CTX_size(temp_ctx);
234 EVP_DigestFinal(temp_ctx, digest, NULL);
235
236 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000237
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000238 return _Py_strhex((const char *)digest, digest_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000239}
240
241PyDoc_STRVAR(EVP_update__doc__,
242"Update this hash object's state with the provided string.");
243
244static PyObject *
245EVP_update(EVPobject *self, PyObject *args)
246{
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000247 PyObject *obj;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000248 Py_buffer view;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000249
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000250 if (!PyArg_ParseTuple(args, "O:update", &obj))
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000251 return NULL;
252
Gregory P. Smith365a1862009-02-12 07:35:29 +0000253 GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000254
255#ifdef WITH_THREAD
256 if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
257 self->lock = PyThread_allocate_lock();
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000258 /* fail? lock = NULL and we fail over to non-threaded code. */
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000259 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000260
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000261 if (self->lock != NULL) {
262 Py_BEGIN_ALLOW_THREADS
263 PyThread_acquire_lock(self->lock, 1);
264 EVP_hash(self, view.buf, view.len);
265 PyThread_release_lock(self->lock);
266 Py_END_ALLOW_THREADS
267 } else {
268 EVP_hash(self, view.buf, view.len);
269 }
270#else
271 EVP_hash(self, view.buf, view.len);
272#endif
273
274 PyBuffer_Release(&view);
275 Py_RETURN_NONE;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000276}
277
278static PyMethodDef EVP_methods[] = {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000279 {"update", (PyCFunction)EVP_update, METH_VARARGS, EVP_update__doc__},
280 {"digest", (PyCFunction)EVP_digest, METH_NOARGS, EVP_digest__doc__},
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000281 {"hexdigest", (PyCFunction)EVP_hexdigest, METH_NOARGS, EVP_hexdigest__doc__},
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000282 {"copy", (PyCFunction)EVP_copy, METH_NOARGS, EVP_copy__doc__},
283 {NULL, NULL} /* sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000284};
285
286static PyObject *
287EVP_get_block_size(EVPobject *self, void *closure)
288{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000289 long block_size;
Christian Heimes598894f2016-09-05 23:19:05 +0200290 block_size = EVP_MD_CTX_block_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000291 return PyLong_FromLong(block_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000292}
293
294static PyObject *
295EVP_get_digest_size(EVPobject *self, void *closure)
296{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000297 long size;
Christian Heimes598894f2016-09-05 23:19:05 +0200298 size = EVP_MD_CTX_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000299 return PyLong_FromLong(size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000300}
301
302static PyMemberDef EVP_members[] = {
303 {"name", T_OBJECT, offsetof(EVPobject, name), READONLY, PyDoc_STR("algorithm name.")},
304 {NULL} /* Sentinel */
305};
306
307static PyGetSetDef EVP_getseters[] = {
308 {"digest_size",
309 (getter)EVP_get_digest_size, NULL,
310 NULL,
311 NULL},
312 {"block_size",
313 (getter)EVP_get_block_size, NULL,
314 NULL,
315 NULL},
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000316 {NULL} /* Sentinel */
317};
318
319
320static PyObject *
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000321EVP_repr(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000322{
Victor Stinner3f1af5c2010-03-12 17:00:41 +0000323 return PyUnicode_FromFormat("<%U HASH object @ %p>", self->name, self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000324}
325
326#if HASH_OBJ_CONSTRUCTOR
327static int
328EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
329{
Martin v. Löwis15e62742006-02-27 16:46:16 +0000330 static char *kwlist[] = {"name", "string", NULL};
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000331 PyObject *name_obj = NULL;
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000332 PyObject *data_obj = NULL;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000333 Py_buffer view;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000334 char *nameStr;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000335 const EVP_MD *digest;
336
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000337 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:HASH", kwlist,
338 &name_obj, &data_obj)) {
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000339 return -1;
340 }
341
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000342 if (data_obj)
Gregory P. Smith365a1862009-02-12 07:35:29 +0000343 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000344
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000345 if (!PyArg_Parse(name_obj, "s", &nameStr)) {
346 PyErr_SetString(PyExc_TypeError, "name must be a string");
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000347 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000348 PyBuffer_Release(&view);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000349 return -1;
350 }
351
352 digest = EVP_get_digestbyname(nameStr);
353 if (!digest) {
354 PyErr_SetString(PyExc_ValueError, "unknown hash function");
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000355 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000356 PyBuffer_Release(&view);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000357 return -1;
358 }
Christian Heimes598894f2016-09-05 23:19:05 +0200359 EVP_DigestInit(self->ctx, digest);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000360
361 self->name = name_obj;
362 Py_INCREF(self->name);
363
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000364 if (data_obj) {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000365 if (view.len >= HASHLIB_GIL_MINSIZE) {
366 Py_BEGIN_ALLOW_THREADS
367 EVP_hash(self, view.buf, view.len);
368 Py_END_ALLOW_THREADS
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000369 } else {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000370 EVP_hash(self, view.buf, view.len);
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000371 }
Martin v. Löwis423be952008-08-13 15:53:07 +0000372 PyBuffer_Release(&view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000373 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000374
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000375 return 0;
376}
377#endif
378
379
380PyDoc_STRVAR(hashtype_doc,
381"A hash represents the object used to calculate a checksum of a\n\
382string of information.\n\
383\n\
384Methods:\n\
385\n\
386update() -- updates the current digest with an additional string\n\
387digest() -- return the current digest value\n\
388hexdigest() -- return the current digest as a string of hexadecimal digits\n\
389copy() -- return a copy of the current hash object\n\
390\n\
391Attributes:\n\
392\n\
393name -- the hash algorithm being used by this object\n\
394digest_size -- number of bytes in this hashes output\n");
395
396static PyTypeObject EVPtype = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000397 PyVarObject_HEAD_INIT(NULL, 0)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000398 "_hashlib.HASH", /*tp_name*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000399 sizeof(EVPobject), /*tp_basicsize*/
400 0, /*tp_itemsize*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000401 /* methods */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000402 (destructor)EVP_dealloc, /*tp_dealloc*/
403 0, /*tp_print*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000404 0, /*tp_getattr*/
405 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000406 0, /*tp_reserved*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000407 (reprfunc)EVP_repr, /*tp_repr*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000408 0, /*tp_as_number*/
409 0, /*tp_as_sequence*/
410 0, /*tp_as_mapping*/
411 0, /*tp_hash*/
412 0, /*tp_call*/
413 0, /*tp_str*/
414 0, /*tp_getattro*/
415 0, /*tp_setattro*/
416 0, /*tp_as_buffer*/
417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
418 hashtype_doc, /*tp_doc*/
419 0, /*tp_traverse*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000420 0, /*tp_clear*/
421 0, /*tp_richcompare*/
422 0, /*tp_weaklistoffset*/
423 0, /*tp_iter*/
424 0, /*tp_iternext*/
425 EVP_methods, /* tp_methods */
426 EVP_members, /* tp_members */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000427 EVP_getseters, /* tp_getset */
428#if 1
429 0, /* tp_base */
430 0, /* tp_dict */
431 0, /* tp_descr_get */
432 0, /* tp_descr_set */
433 0, /* tp_dictoffset */
434#endif
435#if HASH_OBJ_CONSTRUCTOR
436 (initproc)EVP_tp_init, /* tp_init */
437#endif
438};
439
440static PyObject *
441EVPnew(PyObject *name_obj,
442 const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000443 const unsigned char *cp, Py_ssize_t len)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000444{
445 EVPobject *self;
446
447 if (!digest && !initial_ctx) {
448 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
449 return NULL;
450 }
451
452 if ((self = newEVPobject(name_obj)) == NULL)
453 return NULL;
454
455 if (initial_ctx) {
Christian Heimes598894f2016-09-05 23:19:05 +0200456 EVP_MD_CTX_copy(self->ctx, initial_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000457 } else {
Christian Heimes598894f2016-09-05 23:19:05 +0200458 EVP_DigestInit(self->ctx, digest);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000459 }
460
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000461 if (cp && len) {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000462 if (len >= HASHLIB_GIL_MINSIZE) {
463 Py_BEGIN_ALLOW_THREADS
464 EVP_hash(self, cp, len);
465 Py_END_ALLOW_THREADS
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000466 } else {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000467 EVP_hash(self, cp, len);
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000468 }
469 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000470
471 return (PyObject *)self;
472}
473
474
475/* The module-level function: new() */
476
477PyDoc_STRVAR(EVP_new__doc__,
478"Return a new hash object using the named algorithm.\n\
479An optional string argument may be provided and will be\n\
480automatically hashed.\n\
481\n\
482The MD5 and SHA1 algorithms are always supported.\n");
483
484static PyObject *
485EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
486{
Martin v. Löwis15e62742006-02-27 16:46:16 +0000487 static char *kwlist[] = {"name", "string", NULL};
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000488 PyObject *name_obj = NULL;
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000489 PyObject *data_obj = NULL;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000490 Py_buffer view = { 0 };
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000491 PyObject *ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000492 char *name;
493 const EVP_MD *digest;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000494
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000495 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|O:new", kwlist,
496 &name_obj, &data_obj)) {
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000497 return NULL;
498 }
499
500 if (!PyArg_Parse(name_obj, "s", &name)) {
501 PyErr_SetString(PyExc_TypeError, "name must be a string");
502 return NULL;
503 }
504
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000505 if (data_obj)
Gregory P. Smith365a1862009-02-12 07:35:29 +0000506 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000507
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000508 digest = EVP_get_digestbyname(name);
509
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000510 ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000511
512 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000513 PyBuffer_Release(&view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000514 return ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000515}
516
Christian Heimese7236222013-10-19 14:24:44 +0200517
518
Christian Heimes351f5392013-10-19 17:59:48 +0200519#if (OPENSSL_VERSION_NUMBER >= 0x10000000 && !defined(OPENSSL_NO_HMAC) \
520 && !defined(OPENSSL_NO_SHA))
Christian Heimese7236222013-10-19 14:24:44 +0200521
Christian Heimese92ef132013-10-13 00:52:43 +0200522#define PY_PBKDF2_HMAC 1
523
Christian Heimes598894f2016-09-05 23:19:05 +0200524#if !HAS_FAST_PKCS5_PBKDF2_HMAC
Christian Heimese7236222013-10-19 14:24:44 +0200525/* Improved implementation of PKCS5_PBKDF2_HMAC()
526 *
527 * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
528 * `iter` times. Today (2013) the iteration count is typically 100,000 or
529 * more. The improved algorithm is not subject to a Denial-of-Service
530 * vulnerability with overly large passwords.
531 *
532 * Also OpenSSL < 1.0 don't provide PKCS5_PBKDF2_HMAC(), only
533 * PKCS5_PBKDF2_SHA1.
534 */
Christian Heimesc6564b92013-10-20 13:23:03 +0200535static int
536PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen,
537 const unsigned char *salt, int saltlen,
538 int iter, const EVP_MD *digest,
539 int keylen, unsigned char *out)
Christian Heimese7236222013-10-19 14:24:44 +0200540{
541 unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
542 int cplen, j, k, tkeylen, mdlen;
543 unsigned long i = 1;
544 HMAC_CTX hctx_tpl, hctx;
545
546 mdlen = EVP_MD_size(digest);
547 if (mdlen < 0)
548 return 0;
549
550 HMAC_CTX_init(&hctx_tpl);
551 HMAC_CTX_init(&hctx);
552 p = out;
553 tkeylen = keylen;
Christian Heimese7236222013-10-19 14:24:44 +0200554 if (!HMAC_Init_ex(&hctx_tpl, pass, passlen, digest, NULL)) {
555 HMAC_CTX_cleanup(&hctx_tpl);
556 return 0;
557 }
Benjamin Peterson3c0769d2015-09-27 02:13:40 -0700558 while (tkeylen) {
559 if (tkeylen > mdlen)
Christian Heimese7236222013-10-19 14:24:44 +0200560 cplen = mdlen;
561 else
562 cplen = tkeylen;
563 /* We are unlikely to ever use more than 256 blocks (5120 bits!)
564 * but just in case...
565 */
566 itmp[0] = (unsigned char)((i >> 24) & 0xff);
567 itmp[1] = (unsigned char)((i >> 16) & 0xff);
568 itmp[2] = (unsigned char)((i >> 8) & 0xff);
569 itmp[3] = (unsigned char)(i & 0xff);
570 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
571 HMAC_CTX_cleanup(&hctx_tpl);
572 return 0;
573 }
574 if (!HMAC_Update(&hctx, salt, saltlen)
575 || !HMAC_Update(&hctx, itmp, 4)
576 || !HMAC_Final(&hctx, digtmp, NULL)) {
577 HMAC_CTX_cleanup(&hctx_tpl);
578 HMAC_CTX_cleanup(&hctx);
579 return 0;
580 }
Christian Heimes68531082013-11-06 17:25:17 +0100581 HMAC_CTX_cleanup(&hctx);
Christian Heimese7236222013-10-19 14:24:44 +0200582 memcpy(p, digtmp, cplen);
583 for (j = 1; j < iter; j++) {
584 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
585 HMAC_CTX_cleanup(&hctx_tpl);
586 return 0;
587 }
588 if (!HMAC_Update(&hctx, digtmp, mdlen)
589 || !HMAC_Final(&hctx, digtmp, NULL)) {
590 HMAC_CTX_cleanup(&hctx_tpl);
591 HMAC_CTX_cleanup(&hctx);
592 return 0;
593 }
594 HMAC_CTX_cleanup(&hctx);
595 for (k = 0; k < cplen; k++) {
596 p[k] ^= digtmp[k];
597 }
598 }
599 tkeylen-= cplen;
600 i++;
601 p+= cplen;
602 }
603 HMAC_CTX_cleanup(&hctx_tpl);
604 return 1;
605}
Christian Heimes598894f2016-09-05 23:19:05 +0200606#endif
Christian Heimese7236222013-10-19 14:24:44 +0200607
608
Christian Heimese92ef132013-10-13 00:52:43 +0200609PyDoc_STRVAR(pbkdf2_hmac__doc__,
610"pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
611\n\
612Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as\n\
613pseudorandom function.");
614
615static PyObject *
616pbkdf2_hmac(PyObject *self, PyObject *args, PyObject *kwdict)
617{
618 static char *kwlist[] = {"hash_name", "password", "salt", "iterations",
619 "dklen", NULL};
620 PyObject *key_obj = NULL, *dklen_obj = Py_None;
621 char *name, *key;
622 Py_buffer password, salt;
623 long iterations, dklen;
624 int retval;
625 const EVP_MD *digest;
626
627 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "sy*y*l|O:pbkdf2_hmac",
628 kwlist, &name, &password, &salt,
629 &iterations, &dklen_obj)) {
630 return NULL;
631 }
632
633 digest = EVP_get_digestbyname(name);
634 if (digest == NULL) {
635 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
636 goto end;
637 }
638
639 if (password.len > INT_MAX) {
640 PyErr_SetString(PyExc_OverflowError,
641 "password is too long.");
642 goto end;
643 }
644
645 if (salt.len > INT_MAX) {
646 PyErr_SetString(PyExc_OverflowError,
647 "salt is too long.");
648 goto end;
649 }
650
651 if (iterations < 1) {
652 PyErr_SetString(PyExc_ValueError,
653 "iteration value must be greater than 0.");
654 goto end;
655 }
656 if (iterations > INT_MAX) {
657 PyErr_SetString(PyExc_OverflowError,
658 "iteration value is too great.");
659 goto end;
660 }
661
662 if (dklen_obj == Py_None) {
663 dklen = EVP_MD_size(digest);
664 } else {
665 dklen = PyLong_AsLong(dklen_obj);
666 if ((dklen == -1) && PyErr_Occurred()) {
667 goto end;
668 }
669 }
670 if (dklen < 1) {
671 PyErr_SetString(PyExc_ValueError,
672 "key length must be greater than 0.");
673 goto end;
674 }
675 if (dklen > INT_MAX) {
676 /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
677 PyErr_SetString(PyExc_OverflowError,
678 "key length is too great.");
679 goto end;
680 }
681
682 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
683 if (key_obj == NULL) {
684 goto end;
685 }
686 key = PyBytes_AS_STRING(key_obj);
687
688 Py_BEGIN_ALLOW_THREADS
Christian Heimes598894f2016-09-05 23:19:05 +0200689#if HAS_FAST_PKCS5_PBKDF2_HMAC
690 retval = PKCS5_PBKDF2_HMAC((char*)password.buf, (int)password.len,
691 (unsigned char *)salt.buf, (int)salt.len,
692 iterations, digest, dklen,
693 (unsigned char *)key);
694#else
Victor Stinnerc1a57d32013-11-16 00:27:16 +0100695 retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
Christian Heimescc6cdce2013-11-18 09:59:44 +0100696 (unsigned char *)salt.buf, (int)salt.len,
Christian Heimese7236222013-10-19 14:24:44 +0200697 iterations, digest, dklen,
698 (unsigned char *)key);
Christian Heimes598894f2016-09-05 23:19:05 +0200699#endif
Christian Heimese92ef132013-10-13 00:52:43 +0200700 Py_END_ALLOW_THREADS
701
702 if (!retval) {
703 Py_CLEAR(key_obj);
704 _setException(PyExc_ValueError);
705 goto end;
706 }
707
708 end:
709 PyBuffer_Release(&password);
710 PyBuffer_Release(&salt);
711 return key_obj;
712}
713
714#endif
Gregory P. Smith13b55292010-09-06 08:30:23 +0000715
716/* State for our callback function so that it can accumulate a result. */
717typedef struct _internal_name_mapper_state {
718 PyObject *set;
719 int error;
720} _InternalNameMapperState;
721
722
723/* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
724static void
725_openssl_hash_name_mapper(const OBJ_NAME *openssl_obj_name, void *arg)
726{
727 _InternalNameMapperState *state = (_InternalNameMapperState *)arg;
728 PyObject *py_name;
729
730 assert(state != NULL);
731 if (openssl_obj_name == NULL)
732 return;
733 /* Ignore aliased names, they pollute the list and OpenSSL appears to
Martin Panter7462b6492015-11-02 03:37:02 +0000734 * have its own definition of alias as the resulting list still
Gregory P. Smith13b55292010-09-06 08:30:23 +0000735 * contains duplicate and alternate names for several algorithms. */
736 if (openssl_obj_name->alias)
737 return;
738
739 py_name = PyUnicode_FromString(openssl_obj_name->name);
740 if (py_name == NULL) {
741 state->error = 1;
742 } else {
743 if (PySet_Add(state->set, py_name) != 0) {
Gregory P. Smith13b55292010-09-06 08:30:23 +0000744 state->error = 1;
745 }
Christian Heimesdb816d62013-10-29 12:14:55 +0100746 Py_DECREF(py_name);
Gregory P. Smith13b55292010-09-06 08:30:23 +0000747 }
748}
749
750
751/* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
752static PyObject*
753generate_hash_name_list(void)
754{
755 _InternalNameMapperState state;
756 state.set = PyFrozenSet_New(NULL);
757 if (state.set == NULL)
758 return NULL;
759 state.error = 0;
760
761 OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, &_openssl_hash_name_mapper, &state);
762
763 if (state.error) {
764 Py_DECREF(state.set);
765 return NULL;
766 }
767 return state.set;
768}
769
770
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000771/*
772 * This macro generates constructor function definitions for specific
773 * hash algorithms. These constructors are much faster than calling
774 * the generic one passing it a python string and are noticably
775 * faster than calling a python new() wrapper. Thats important for
776 * code that wants to make hashes of a bunch of small strings.
777 */
778#define GEN_CONSTRUCTOR(NAME) \
779 static PyObject * \
780 EVP_new_ ## NAME (PyObject *self, PyObject *args) \
781 { \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000782 PyObject *data_obj = NULL; \
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000783 Py_buffer view = { 0 }; \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000784 PyObject *ret_obj; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000785 \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000786 if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000787 return NULL; \
788 } \
789 \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000790 if (data_obj) \
Gregory P. Smith365a1862009-02-12 07:35:29 +0000791 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000792 \
793 ret_obj = EVPnew( \
794 CONST_ ## NAME ## _name_obj, \
795 NULL, \
796 CONST_new_ ## NAME ## _ctx_p, \
797 (unsigned char*)view.buf, \
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000798 view.len); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000799 \
800 if (data_obj) \
Martin v. Löwis423be952008-08-13 15:53:07 +0000801 PyBuffer_Release(&view); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000802 return ret_obj; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000803 }
804
805/* a PyMethodDef structure for the constructor */
806#define CONSTRUCTOR_METH_DEF(NAME) \
807 {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
808 PyDoc_STR("Returns a " #NAME \
809 " hash object; optionally initialized with a string") \
810 }
811
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800812/* used in the init function to setup a constructor: initialize OpenSSL
813 constructor constants if they haven't been initialized already. */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000814#define INIT_CONSTRUCTOR_CONSTANTS(NAME) do { \
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800815 if (CONST_ ## NAME ## _name_obj == NULL) { \
816 CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
817 if (EVP_get_digestbyname(#NAME)) { \
Christian Heimes598894f2016-09-05 23:19:05 +0200818 CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800819 EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
820 } \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000821 } \
822} while (0);
823
824GEN_CONSTRUCTOR(md5)
825GEN_CONSTRUCTOR(sha1)
826GEN_CONSTRUCTOR(sha224)
827GEN_CONSTRUCTOR(sha256)
828GEN_CONSTRUCTOR(sha384)
829GEN_CONSTRUCTOR(sha512)
830
831/* List of functions exported by this module */
832
833static struct PyMethodDef EVP_functions[] = {
834 {"new", (PyCFunction)EVP_new, METH_VARARGS|METH_KEYWORDS, EVP_new__doc__},
Christian Heimese92ef132013-10-13 00:52:43 +0200835#ifdef PY_PBKDF2_HMAC
836 {"pbkdf2_hmac", (PyCFunction)pbkdf2_hmac, METH_VARARGS|METH_KEYWORDS,
837 pbkdf2_hmac__doc__},
838#endif
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000839 CONSTRUCTOR_METH_DEF(md5),
840 CONSTRUCTOR_METH_DEF(sha1),
841 CONSTRUCTOR_METH_DEF(sha224),
842 CONSTRUCTOR_METH_DEF(sha256),
843 CONSTRUCTOR_METH_DEF(sha384),
844 CONSTRUCTOR_METH_DEF(sha512),
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000845 {NULL, NULL} /* Sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000846};
847
848
849/* Initialize this module. */
850
Martin v. Löwis1a214512008-06-11 05:26:20 +0000851
852static struct PyModuleDef _hashlibmodule = {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000853 PyModuleDef_HEAD_INIT,
854 "_hashlib",
855 NULL,
856 -1,
857 EVP_functions,
858 NULL,
859 NULL,
860 NULL,
861 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000862};
863
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000864PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000865PyInit__hashlib(void)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000866{
Gregory P. Smith13b55292010-09-06 08:30:23 +0000867 PyObject *m, *openssl_md_meth_names;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000868
869 OpenSSL_add_all_digests();
Christian Heimesb7ddbc82013-10-21 19:48:22 +0200870 ERR_load_crypto_strings();
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000871
872 /* TODO build EVP_functions openssl_* entries dynamically based
873 * on what hashes are supported rather than listing many
874 * but having some be unsupported. Only init appropriate
875 * constants. */
876
Christian Heimes90aa7642007-12-19 02:45:37 +0000877 Py_TYPE(&EVPtype) = &PyType_Type;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000878 if (PyType_Ready(&EVPtype) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000879 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000880
Martin v. Löwis1a214512008-06-11 05:26:20 +0000881 m = PyModule_Create(&_hashlibmodule);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000882 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000883 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000884
Gregory P. Smith13b55292010-09-06 08:30:23 +0000885 openssl_md_meth_names = generate_hash_name_list();
886 if (openssl_md_meth_names == NULL) {
887 Py_DECREF(m);
888 return NULL;
889 }
890 if (PyModule_AddObject(m, "openssl_md_meth_names", openssl_md_meth_names)) {
891 Py_DECREF(m);
892 return NULL;
893 }
894
Christian Heimes327dd732013-10-22 15:05:23 +0200895 Py_INCREF((PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000896 PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000897
898 /* these constants are used by the convenience constructors */
899 INIT_CONSTRUCTOR_CONSTANTS(md5);
900 INIT_CONSTRUCTOR_CONSTANTS(sha1);
901 INIT_CONSTRUCTOR_CONSTANTS(sha224);
902 INIT_CONSTRUCTOR_CONSTANTS(sha256);
903 INIT_CONSTRUCTOR_CONSTANTS(sha384);
904 INIT_CONSTRUCTOR_CONSTANTS(sha512);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000905 return m;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000906}