ยปCore Development>Code coverage>Modules/_hashopenssl.c

Python code coverage for Modules/_hashopenssl.c

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