Debian Codegraph @

cpython27/Modules/_hashopenssl.c

raw symbols SCIP
1 /* Module that wraps all OpenSSL hash algorithms */
2
3 /*
4 * Copyright (C) 2005-2010 Gregory P. Smith ([email protected])
5 * Licensed to PSF under a Contributor Agreement.
6 *
7 * Derived from a skeleton of shamodule.c containing work performed by:
8 *
9 * Andrew Kuchling ([email protected])
10 * Greg Stein ([email protected])
11 *
12 */
13
14 #define PY_SSIZE_T_CLEAN
15
16 #include "Python.h"
17 #include "structmember.h"
18
19 #ifdef WITH_THREAD
20 #include "pythread.h"
21 #define ENTER_HASHLIB(obj) \
22 if ((obj)->lock) { \
23 if (!PyThread_acquire_lock((obj)->lock, 0)) { \
24 Py_BEGIN_ALLOW_THREADS \
25 PyThread_acquire_lock((obj)->lock, 1); \
26 Py_END_ALLOW_THREADS \
27 } \
28 }
29 #define LEAVE_HASHLIB(obj) \
30 if ((obj)->lock) { \
31 PyThread_release_lock((obj)->lock); \
32 }
33 #else
34 #define ENTER_HASHLIB(obj)
35 #define LEAVE_HASHLIB(obj)
36 #endif
37
38 /* EVP is the preferred interface to hashing in OpenSSL */
39 #include <openssl/evp.h>
40 #include <openssl/err.h>
41 /* We use the object interface to discover what hashes OpenSSL supports. */
42 #include <openssl/objects.h>
43 #include "openssl/err.h"
44
45 #define MUNCH_SIZE INT_MAX
46
47 /* TODO(gps): We should probably make this a module or EVPobject attribute
48 * to allow the user to optimize based on the platform they're using. */
49 #define HASHLIB_GIL_MINSIZE 2048
50
51 #ifndef HASH_OBJ_CONSTRUCTOR
52 #define HASH_OBJ_CONSTRUCTOR 0
53 #endif
54
55 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x00908000)
56 #define _OPENSSL_SUPPORTS_SHA2
57 #endif
58
59 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
60 /* OpenSSL < 1.1.0 */
61 #define EVP_MD_CTX_new EVP_MD_CTX_create
62 #define EVP_MD_CTX_free EVP_MD_CTX_destroy
63 #define HAS_FAST_PKCS5_PBKDF2_HMAC 0
64 #include <openssl/hmac.h>
65 #else
66 /* OpenSSL >= 1.1.0 */
67 #define HAS_FAST_PKCS5_PBKDF2_HMAC 1
68 #endif
69
70
71 typedef struct {
72 PyObject_HEAD
73 PyObject *name; /* name of this hash algorithm */
74 EVP_MD_CTX *ctx; /* OpenSSL message digest context */
75 #ifdef WITH_THREAD
76 PyThread_type_lock lock; /* OpenSSL context lock */
77 #endif
78 } EVPobject;
79
80
81 static PyTypeObject EVPtype;
82
83
84 #define DEFINE_CONSTS_FOR_NEW(Name) \
85 static PyObject *CONST_ ## Name ## _name_obj = NULL; \
86 static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
87
88 DEFINE_CONSTS_FOR_NEW(md5)
89 DEFINE_CONSTS_FOR_NEW(sha1)
90 #ifdef _OPENSSL_SUPPORTS_SHA2
91 DEFINE_CONSTS_FOR_NEW(sha224)
92 DEFINE_CONSTS_FOR_NEW(sha256)
93 DEFINE_CONSTS_FOR_NEW(sha384)
94 DEFINE_CONSTS_FOR_NEW(sha512)
95 #endif
96
97
98 /* LCOV_EXCL_START */
99 static PyObject *
100 _setException(PyObject *exc)
101 {
102 unsigned long errcode;
103 const char *lib, *func, *reason;
104
105 errcode = ERR_peek_last_error();
106 if (!errcode) {
107 PyErr_SetString(exc, "unknown reasons");
108 return NULL;
109 }
110 ERR_clear_error();
111
112 lib = ERR_lib_error_string(errcode);
113 func = ERR_func_error_string(errcode);
114 reason = ERR_reason_error_string(errcode);
115
116 if (lib && func) {
117 PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
118 }
119 else if (lib) {
120 PyErr_Format(exc, "[%s] %s", lib, reason);
121 }
122 else {
123 PyErr_SetString(exc, reason);
124 }
125 return NULL;
126 }
127 /* LCOV_EXCL_STOP */
128
129 static EVPobject *
130 newEVPobject(PyObject *name)
131 {
132 EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
133 if (retval == NULL)
134 return NULL;
135
136 /* save the name for .name to return */
137 Py_INCREF(name);
138 retval->name = name;
139 #ifdef WITH_THREAD
140 retval->lock = NULL;
141 #endif
142
143 retval->ctx = EVP_MD_CTX_new();
144 if (retval->ctx == NULL) {
145 Py_DECREF(retval);
146 PyErr_NoMemory();
147 return NULL;
148 }
149
150 return retval;
151 }
152
153 static void
154 EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
155 {
156 unsigned int process;
157 const unsigned char *cp = (const unsigned char *)vp;
158 while (0 < len)
159 {
160 if (len > (Py_ssize_t)MUNCH_SIZE)
161 process = MUNCH_SIZE;
162 else
163 process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
164 EVP_DigestUpdate(self->ctx, (const void*)cp, process);
165 len -= process;
166 cp += process;
167 }
168 }
169
170 /* Internal methods for a hash object */
171
172 static void
173 EVP_dealloc(EVPobject *self)
174 {
175 #ifdef WITH_THREAD
176 if (self->lock != NULL)
177 PyThread_free_lock(self->lock);
178 #endif
179 EVP_MD_CTX_free(self->ctx);
180 Py_XDECREF(self->name);
181 PyObject_Del(self);
182 }
183
184 static int
185 locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
186 {
187 int result;
188 ENTER_HASHLIB(self);
189 /* XXX no error reporting */
190 result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
191 LEAVE_HASHLIB(self);
192 return result;
193 }
194
195 /* External methods for a hash object */
196
197 PyDoc_STRVAR(EVP_copy__doc__, "Return a copy of the hash object.");
198
199
200 static PyObject *
201 EVP_copy(EVPobject *self, PyObject *unused)
202 {
203 EVPobject *newobj;
204
205 if ( (newobj = newEVPobject(self->name))==NULL)
206 return NULL;
207
208 if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
209 Py_DECREF(newobj);
210 return _setException(PyExc_ValueError);
211 }
212 return (PyObject *)newobj;
213 }
214
215 PyDoc_STRVAR(EVP_digest__doc__,
216 "Return the digest value as a string of binary data.");
217
218 static PyObject *
219 EVP_digest(EVPobject *self, PyObject *unused)
220 {
221 unsigned char digest[EVP_MAX_MD_SIZE];
222 EVP_MD_CTX *temp_ctx;
223 PyObject *retval;
224 unsigned int digest_size;
225
226 temp_ctx = EVP_MD_CTX_new();
227 if (temp_ctx == NULL) {
228 PyErr_NoMemory();
229 return NULL;
230 }
231
232 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
233 return _setException(PyExc_ValueError);
234 }
235 digest_size = EVP_MD_CTX_size(temp_ctx);
236 EVP_DigestFinal(temp_ctx, digest, NULL);
237
238 retval = PyString_FromStringAndSize((const char *)digest, digest_size);
239 EVP_MD_CTX_free(temp_ctx);
240 return retval;
241 }
242
243 PyDoc_STRVAR(EVP_hexdigest__doc__,
244 "Return the digest value as a string of hexadecimal digits.");
245
246 static PyObject *
247 EVP_hexdigest(EVPobject *self, PyObject *unused)
248 {
249 unsigned char digest[EVP_MAX_MD_SIZE];
250 EVP_MD_CTX *temp_ctx;
251 PyObject *retval;
252 char *hex_digest;
253 unsigned int i, j, digest_size;
254
255 temp_ctx = EVP_MD_CTX_new();
256 if (temp_ctx == NULL) {
257 PyErr_NoMemory();
258 return NULL;
259 }
260
261 /* Get the raw (binary) digest value */
262 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
263 return _setException(PyExc_ValueError);
264 }
265 digest_size = EVP_MD_CTX_size(temp_ctx);
266 EVP_DigestFinal(temp_ctx, digest, NULL);
267
268 EVP_MD_CTX_free(temp_ctx);
269
270 /* Create a new string */
271 /* NOTE: not thread safe! modifying an already created string object */
272 /* (not a problem because we hold the GIL by default) */
273 retval = PyString_FromStringAndSize(NULL, digest_size * 2);
274 if (!retval)
275 return NULL;
276 hex_digest = PyString_AsString(retval);
277 if (!hex_digest) {
278 Py_DECREF(retval);
279 return NULL;
280 }
281
282 /* Make hex version of the digest */
283 for(i=j=0; i<digest_size; i++) {
284 char c;
285 c = (digest[i] >> 4) & 0xf;
286 c = (c>9) ? c+'a'-10 : c + '0';
287 hex_digest[j++] = c;
288 c = (digest[i] & 0xf);
289 c = (c>9) ? c+'a'-10 : c + '0';
290 hex_digest[j++] = c;
291 }
292 return retval;
293 }
294
295 PyDoc_STRVAR(EVP_update__doc__,
296 "Update this hash object's state with the provided string.");
297
298 static PyObject *
299 EVP_update(EVPobject *self, PyObject *args)
300 {
301 Py_buffer view;
302
303 if (!PyArg_ParseTuple(args, "s*:update", &view))
304 return NULL;
305
306 #ifdef WITH_THREAD
307 if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
308 self->lock = PyThread_allocate_lock();
309 /* fail? lock = NULL and we fail over to non-threaded code. */
310 }
311
312 if (self->lock != NULL) {
313 Py_BEGIN_ALLOW_THREADS
314 PyThread_acquire_lock(self->lock, 1);
315 EVP_hash(self, view.buf, view.len);
316 PyThread_release_lock(self->lock);
317 Py_END_ALLOW_THREADS
318 }
319 else
320 #endif
321 {
322 EVP_hash(self, view.buf, view.len);
323 }
324
325 PyBuffer_Release(&view);
326
327 Py_RETURN_NONE;
328 }
329
330 static PyMethodDef EVP_methods[] = {
331 {"update", (PyCFunction)EVP_update, METH_VARARGS, EVP_update__doc__},
332 {"digest", (PyCFunction)EVP_digest, METH_NOARGS, EVP_digest__doc__},
333 {"hexdigest", (PyCFunction)EVP_hexdigest, METH_NOARGS, EVP_hexdigest__doc__},
334 {"copy", (PyCFunction)EVP_copy, METH_NOARGS, EVP_copy__doc__},
335 {NULL, NULL} /* sentinel */
336 };
337
338 static PyObject *
339 EVP_get_block_size(EVPobject *self, void *closure)
340 {
341 long block_size;
342 block_size = EVP_MD_CTX_block_size(self->ctx);
343 return PyLong_FromLong(block_size);
344 }
345
346 static PyObject *
347 EVP_get_digest_size(EVPobject *self, void *closure)
348 {
349 long size;
350 size = EVP_MD_CTX_size(self->ctx);
351 return PyLong_FromLong(size);
352 }
353
354 static PyMemberDef EVP_members[] = {
355 {"name", T_OBJECT, offsetof(EVPobject, name), READONLY, PyDoc_STR("algorithm name.")},
356 {NULL} /* Sentinel */
357 };
358
359 static PyGetSetDef EVP_getseters[] = {
360 {"digest_size",
361 (getter)EVP_get_digest_size, NULL,
362 NULL,
363 NULL},
364 {"block_size",
365 (getter)EVP_get_block_size, NULL,
366 NULL,
367 NULL},
368 /* the old md5 and sha modules support 'digest_size' as in PEP 247.
369 * the old sha module also supported 'digestsize'. ugh. */
370 {"digestsize",
371 (getter)EVP_get_digest_size, NULL,
372 NULL,
373 NULL},
374 {NULL} /* Sentinel */
375 };
376
377
378 static PyObject *
379 EVP_repr(PyObject *self)
380 {
381 char buf[100];
382 PyOS_snprintf(buf, sizeof(buf), "<%s HASH object @ %p>",
383 PyString_AsString(((EVPobject *)self)->name), self);
384 return PyString_FromString(buf);
385 }
386
387 #if HASH_OBJ_CONSTRUCTOR
388 static int
389 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
390 {
391 static char *kwlist[] = {"name", "string", NULL};
392 PyObject *name_obj = NULL;
393 Py_buffer view = { 0 };
394 char *nameStr;
395 const EVP_MD *digest;
396
397 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s*:HASH", kwlist,
398 &name_obj, &view)) {
399 return -1;
400 }
401
402 if (!PyArg_Parse(name_obj, "s", &nameStr)) {
403 PyErr_SetString(PyExc_TypeError, "name must be a string");
404 PyBuffer_Release(&view);
405 return -1;
406 }
407
408 digest = EVP_get_digestbyname(nameStr);
409 if (!digest) {
410 PyErr_SetString(PyExc_ValueError, "unknown hash function");
411 PyBuffer_Release(&view);
412 return -1;
413 }
414 EVP_DigestInit(self->ctx, digest);
415
416 self->name = name_obj;
417 Py_INCREF(self->name);
418
419 if (view.obj) {
420 if (view.len >= HASHLIB_GIL_MINSIZE) {
421 Py_BEGIN_ALLOW_THREADS
422 EVP_hash(self, view.buf, view.len);
423 Py_END_ALLOW_THREADS
424 } else {
425 EVP_hash(self, view.buf, view.len);
426 }
427 PyBuffer_Release(&view);
428 }
429
430 return 0;
431 }
432 #endif
433
434
435 PyDoc_STRVAR(hashtype_doc,
436 "A hash represents the object used to calculate a checksum of a\n\
437 string of information.\n\
438 \n\
439 Methods:\n\
440 \n\
441 update() -- updates the current digest with an additional string\n\
442 digest() -- return the current digest value\n\
443 hexdigest() -- return the current digest as a string of hexadecimal digits\n\
444 copy() -- return a copy of the current hash object\n\
445 \n\
446 Attributes:\n\
447 \n\
448 name -- the hash algorithm being used by this object\n\
449 digest_size -- number of bytes in this hashes output\n");
450
451 static PyTypeObject EVPtype = {
452 PyVarObject_HEAD_INIT(NULL, 0)
453 "_hashlib.HASH", /*tp_name*/
454 sizeof(EVPobject), /*tp_basicsize*/
455 0, /*tp_itemsize*/
456 /* methods */
457 (destructor)EVP_dealloc, /*tp_dealloc*/
458 0, /*tp_print*/
459 0, /*tp_getattr*/
460 0, /*tp_setattr*/
461 0, /*tp_compare*/
462 EVP_repr, /*tp_repr*/
463 0, /*tp_as_number*/
464 0, /*tp_as_sequence*/
465 0, /*tp_as_mapping*/
466 0, /*tp_hash*/
467 0, /*tp_call*/
468 0, /*tp_str*/
469 0, /*tp_getattro*/
470 0, /*tp_setattro*/
471 0, /*tp_as_buffer*/
472 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
473 hashtype_doc, /*tp_doc*/
474 0, /*tp_traverse*/
475 0, /*tp_clear*/
476 0, /*tp_richcompare*/
477 0, /*tp_weaklistoffset*/
478 0, /*tp_iter*/
479 0, /*tp_iternext*/
480 EVP_methods, /* tp_methods */
481 EVP_members, /* tp_members */
482 EVP_getseters, /* tp_getset */
483 #if 1
484 0, /* tp_base */
485 0, /* tp_dict */
486 0, /* tp_descr_get */
487 0, /* tp_descr_set */
488 0, /* tp_dictoffset */
489 #endif
490 #if HASH_OBJ_CONSTRUCTOR
491 (initproc)EVP_tp_init, /* tp_init */
492 #endif
493 };
494
495 static PyObject *
496 EVPnew(PyObject *name_obj,
497 const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
498 const unsigned char *cp, Py_ssize_t len)
499 {
500 EVPobject *self;
501
502 if (!digest && !initial_ctx) {
503 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
504 return NULL;
505 }
506
507 if ((self = newEVPobject(name_obj)) == NULL)
508 return NULL;
509
510 if (initial_ctx) {
511 EVP_MD_CTX_copy(self->ctx, initial_ctx);
512 } else {
513 EVP_DigestInit(self->ctx, digest);
514 }
515
516 if (cp && len) {
517 if (len >= HASHLIB_GIL_MINSIZE) {
518 Py_BEGIN_ALLOW_THREADS
519 EVP_hash(self, cp, len);
520 Py_END_ALLOW_THREADS
521 } else {
522 EVP_hash(self, cp, len);
523 }
524 }
525
526 return (PyObject *)self;
527 }
528
529
530 /* The module-level function: new() */
531
532 PyDoc_STRVAR(EVP_new__doc__,
533 "Return a new hash object using the named algorithm.\n\
534 An optional string argument may be provided and will be\n\
535 automatically hashed.\n\
536 \n\
537 The MD5 and SHA1 algorithms are always supported.\n");
538
539 static PyObject *
540 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
541 {
542 static char *kwlist[] = {"name", "string", NULL};
543 PyObject *name_obj = NULL;
544 Py_buffer view = { 0 };
545 PyObject *ret_obj;
546 char *name;
547 const EVP_MD *digest;
548
549 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*:new", kwlist,
550 &name_obj, &view)) {
551 return NULL;
552 }
553
554 if (!PyArg_Parse(name_obj, "s", &name)) {
555 PyBuffer_Release(&view);
556 PyErr_SetString(PyExc_TypeError, "name must be a string");
557 return NULL;
558 }
559
560 digest = EVP_get_digestbyname(name);
561
562 ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf,
563 view.len);
564 PyBuffer_Release(&view);
565
566 return ret_obj;
567 }
568
569
570 #if (OPENSSL_VERSION_NUMBER >= 0x10000000 && !defined(OPENSSL_NO_HMAC) \
571 && !defined(OPENSSL_NO_SHA))
572
573 #define PY_PBKDF2_HMAC 1
574
575 #if !HAS_FAST_PKCS5_PBKDF2_HMAC
576 /* Improved implementation of PKCS5_PBKDF2_HMAC()
577 *
578 * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
579 * `iter` times. Today (2013) the iteration count is typically 100,000 or
580 * more. The improved algorithm is not subject to a Denial-of-Service
581 * vulnerability with overly large passwords.
582 *
583 * Also OpenSSL < 1.0 don't provide PKCS5_PBKDF2_HMAC(), only
584 * PKCS5_PBKDF2_SHA1.
585 */
586 static int
587 PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen,
588 const unsigned char *salt, int saltlen,
589 int iter, const EVP_MD *digest,
590 int keylen, unsigned char *out)
591 {
592 unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
593 int cplen, j, k, tkeylen, mdlen;
594 unsigned long i = 1;
595 HMAC_CTX hctx_tpl, hctx;
596
597 mdlen = EVP_MD_size(digest);
598 if (mdlen < 0)
599 return 0;
600
601 HMAC_CTX_init(&hctx_tpl);
602 HMAC_CTX_init(&hctx);
603 p = out;
604 tkeylen = keylen;
605 if (!HMAC_Init_ex(&hctx_tpl, pass, passlen, digest, NULL)) {
606 HMAC_CTX_cleanup(&hctx_tpl);
607 return 0;
608 }
609 while (tkeylen) {
610 if (tkeylen > mdlen)
611 cplen = mdlen;
612 else
613 cplen = tkeylen;
614 /* We are unlikely to ever use more than 256 blocks (5120 bits!)
615 * but just in case...
616 */
617 itmp[0] = (unsigned char)((i >> 24) & 0xff);
618 itmp[1] = (unsigned char)((i >> 16) & 0xff);
619 itmp[2] = (unsigned char)((i >> 8) & 0xff);
620 itmp[3] = (unsigned char)(i & 0xff);
621 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
622 HMAC_CTX_cleanup(&hctx_tpl);
623 return 0;
624 }
625 if (!HMAC_Update(&hctx, salt, saltlen)
626 || !HMAC_Update(&hctx, itmp, 4)
627 || !HMAC_Final(&hctx, digtmp, NULL)) {
628 HMAC_CTX_cleanup(&hctx_tpl);
629 HMAC_CTX_cleanup(&hctx);
630 return 0;
631 }
632 HMAC_CTX_cleanup(&hctx);
633 memcpy(p, digtmp, cplen);
634 for (j = 1; j < iter; j++) {
635 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
636 HMAC_CTX_cleanup(&hctx_tpl);
637 return 0;
638 }
639 if (!HMAC_Update(&hctx, digtmp, mdlen)
640 || !HMAC_Final(&hctx, digtmp, NULL)) {
641 HMAC_CTX_cleanup(&hctx_tpl);
642 HMAC_CTX_cleanup(&hctx);
643 return 0;
644 }
645 HMAC_CTX_cleanup(&hctx);
646 for (k = 0; k < cplen; k++) {
647 p[k] ^= digtmp[k];
648 }
649 }
650 tkeylen-= cplen;
651 i++;
652 p+= cplen;
653 }
654 HMAC_CTX_cleanup(&hctx_tpl);
655 return 1;
656 }
657 #endif
658
659
660 PyDoc_STRVAR(pbkdf2_hmac__doc__,
661 "pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
662 \n\
663 Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as\n\
664 pseudorandom function.");
665
666 static PyObject *
667 pbkdf2_hmac(PyObject *self, PyObject *args, PyObject *kwdict)
668 {
669 static char *kwlist[] = {"hash_name", "password", "salt", "iterations",
670 "dklen", NULL};
671 PyObject *key_obj = NULL, *dklen_obj = Py_None;
672 char *name, *key;
673 Py_buffer password, salt;
674 long iterations, dklen;
675 int retval;
676 const EVP_MD *digest;
677
678 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "ss*s*l|O:pbkdf2_hmac",
679 kwlist, &name, &password, &salt,
680 &iterations, &dklen_obj)) {
681 return NULL;
682 }
683
684 digest = EVP_get_digestbyname(name);
685 if (digest == NULL) {
686 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
687 goto end;
688 }
689
690 if (password.len > INT_MAX) {
691 PyErr_SetString(PyExc_OverflowError,
692 "password is too long.");
693 goto end;
694 }
695
696 if (salt.len > INT_MAX) {
697 PyErr_SetString(PyExc_OverflowError,
698 "salt is too long.");
699 goto end;
700 }
701
702 if (iterations < 1) {
703 PyErr_SetString(PyExc_ValueError,
704 "iteration value must be greater than 0.");
705 goto end;
706 }
707 if (iterations > INT_MAX) {
708 PyErr_SetString(PyExc_OverflowError,
709 "iteration value is too great.");
710 goto end;
711 }
712
713 if (dklen_obj == Py_None) {
714 dklen = EVP_MD_size(digest);
715 } else {
716 dklen = PyLong_AsLong(dklen_obj);
717 if ((dklen == -1) && PyErr_Occurred()) {
718 goto end;
719 }
720 }
721 if (dklen < 1) {
722 PyErr_SetString(PyExc_ValueError,
723 "key length must be greater than 0.");
724 goto end;
725 }
726 if (dklen > INT_MAX) {
727 /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
728 PyErr_SetString(PyExc_OverflowError,
729 "key length is too great.");
730 goto end;
731 }
732
733 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
734 if (key_obj == NULL) {
735 goto end;
736 }
737 key = PyBytes_AS_STRING(key_obj);
738
739 Py_BEGIN_ALLOW_THREADS
740 #if HAS_FAST_PKCS5_PBKDF2_HMAC
741 retval = PKCS5_PBKDF2_HMAC((char*)password.buf, (int)password.len,
742 (unsigned char *)salt.buf, (int)salt.len,
743 iterations, digest, dklen,
744 (unsigned char *)key);
745 #else
746 retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
747 (unsigned char *)salt.buf, (int)salt.len,
748 iterations, digest, dklen,
749 (unsigned char *)key);
750 #endif
751 Py_END_ALLOW_THREADS
752
753 if (!retval) {
754 Py_CLEAR(key_obj);
755 _setException(PyExc_ValueError);
756 goto end;
757 }
758
759 end:
760 PyBuffer_Release(&password);
761 PyBuffer_Release(&salt);
762 return key_obj;
763 }
764
765 #endif
766
767 /* State for our callback function so that it can accumulate a result. */
768 typedef struct _internal_name_mapper_state {
769 PyObject *set;
770 int error;
771 } _InternalNameMapperState;
772
773
774 /* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
775 static void
776 _openssl_hash_name_mapper(const OBJ_NAME *openssl_obj_name, void *arg)
777 {
778 _InternalNameMapperState *state = (_InternalNameMapperState *)arg;
779 PyObject *py_name;
780
781 assert(state != NULL);
782 if (openssl_obj_name == NULL)
783 return;
784 /* Ignore aliased names, they pollute the list and OpenSSL appears to
785 * have its own definition of alias as the resulting list still
786 * contains duplicate and alternate names for several algorithms. */
787 if (openssl_obj_name->alias)
788 return;
789
790 py_name = PyString_FromString(openssl_obj_name->name);
791 if (py_name == NULL) {
792 state->error = 1;
793 } else {
794 if (PySet_Add(state->set, py_name) != 0) {
795 state->error = 1;
796 }
797 Py_DECREF(py_name);
798 }
799 }
800
801
802 /* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
803 static PyObject*
804 generate_hash_name_list(void)
805 {
806 _InternalNameMapperState state;
807 state.set = PyFrozenSet_New(NULL);
808 if (state.set == NULL)
809 return NULL;
810 state.error = 0;
811
812 OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, &_openssl_hash_name_mapper, &state);
813
814 if (state.error) {
815 Py_DECREF(state.set);
816 return NULL;
817 }
818 return state.set;
819 }
820
821
822 /*
823 * This macro generates constructor function definitions for specific
824 * hash algorithms. These constructors are much faster than calling
825 * the generic one passing it a python string and are noticeably
826 * faster than calling a python new() wrapper. Thats important for
827 * code that wants to make hashes of a bunch of small strings.
828 */
829 #define GEN_CONSTRUCTOR(NAME) \
830 static PyObject * \
831 EVP_new_ ## NAME (PyObject *self, PyObject *args) \
832 { \
833 Py_buffer view = { 0 }; \
834 PyObject *ret_obj; \
835 \
836 if (!PyArg_ParseTuple(args, "|s*:" #NAME , &view)) { \
837 return NULL; \
838 } \
839 \
840 ret_obj = EVPnew( \
841 CONST_ ## NAME ## _name_obj, \
842 NULL, \
843 CONST_new_ ## NAME ## _ctx_p, \
844 (unsigned char*)view.buf, view.len); \
845 PyBuffer_Release(&view); \
846 return ret_obj; \
847 }
848
849 /* a PyMethodDef structure for the constructor */
850 #define CONSTRUCTOR_METH_DEF(NAME) \
851 {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
852 PyDoc_STR("Returns a " #NAME \
853 " hash object; optionally initialized with a string") \
854 }
855
856 /* used in the init function to setup a constructor: initialize OpenSSL
857 constructor constants if they haven't been initialized already. */
858 #define INIT_CONSTRUCTOR_CONSTANTS(NAME) do { \
859 if (CONST_ ## NAME ## _name_obj == NULL) { \
860 CONST_ ## NAME ## _name_obj = PyString_FromString(#NAME); \
861 if (EVP_get_digestbyname(#NAME)) { \
862 CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
863 EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
864 } \
865 } \
866 } while (0);
867
868 GEN_CONSTRUCTOR(md5)
869 GEN_CONSTRUCTOR(sha1)
870 #ifdef _OPENSSL_SUPPORTS_SHA2
871 GEN_CONSTRUCTOR(sha224)
872 GEN_CONSTRUCTOR(sha256)
873 GEN_CONSTRUCTOR(sha384)
874 GEN_CONSTRUCTOR(sha512)
875 #endif
876
877 /* List of functions exported by this module */
878
879 static struct PyMethodDef EVP_functions[] = {
880 {"new", (PyCFunction)EVP_new, METH_VARARGS|METH_KEYWORDS, EVP_new__doc__},
881 CONSTRUCTOR_METH_DEF(md5),
882 CONSTRUCTOR_METH_DEF(sha1),
883 #ifdef _OPENSSL_SUPPORTS_SHA2
884 CONSTRUCTOR_METH_DEF(sha224),
885 CONSTRUCTOR_METH_DEF(sha256),
886 CONSTRUCTOR_METH_DEF(sha384),
887 CONSTRUCTOR_METH_DEF(sha512),
888 #endif
889 #ifdef PY_PBKDF2_HMAC
890 {"pbkdf2_hmac", (PyCFunction)pbkdf2_hmac, METH_VARARGS|METH_KEYWORDS,
891 pbkdf2_hmac__doc__},
892 #endif
893 {NULL, NULL} /* Sentinel */
894 };
895
896
897 /* Initialize this module. */
898
899 PyMODINIT_FUNC
900 init_hashlib(void)
901 {
902 PyObject *m, *openssl_md_meth_names;
903
904 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
905 /* Load all digest algorithms and initialize cpuid */
906 OPENSSL_add_all_algorithms_noconf();
907 ERR_load_crypto_strings();
908 #endif
909
910 /* TODO build EVP_functions openssl_* entries dynamically based
911 * on what hashes are supported rather than listing many
912 * but having some be unsupported. Only init appropriate
913 * constants. */
914
915 Py_TYPE(&EVPtype) = &PyType_Type;
916 if (PyType_Ready(&EVPtype) < 0)
917 return;
918
919 m = Py_InitModule("_hashlib", EVP_functions);
920 if (m == NULL)
921 return;
922
923 openssl_md_meth_names = generate_hash_name_list();
924 if (openssl_md_meth_names == NULL) {
925 return;
926 }
927 if (PyModule_AddObject(m, "openssl_md_meth_names", openssl_md_meth_names)) {
928 return;
929 }
930
931 #if HASH_OBJ_CONSTRUCTOR
932 Py_INCREF(&EVPtype);
933 PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
934 #endif
935
936 /* these constants are used by the convenience constructors */
937 INIT_CONSTRUCTOR_CONSTANTS(md5);
938 INIT_CONSTRUCTOR_CONSTANTS(sha1);
939 #ifdef _OPENSSL_SUPPORTS_SHA2
940 INIT_CONSTRUCTOR_CONSTANTS(sha224);
941 INIT_CONSTRUCTOR_CONSTANTS(sha256);
942 INIT_CONSTRUCTOR_CONSTANTS(sha384);
943 INIT_CONSTRUCTOR_CONSTANTS(sha512);
944 #endif
945 }