Skip to content

Commit 219a122

Browse files
susmitsusmit
authored andcommitted
[Fix] Memory Leak in py-tlsh
1 parent 25bc5d2 commit 219a122

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

‎py_ext/tlshmodule.cpp

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -368,33 +368,54 @@ Tlsh_fromTlshStr(tlsh_TlshObject *self, PyObject *args)
368368

369369
arg = PyTuple_GetItem(args, 0);
370370
#if PY_MAJOR_VERSION >= 3
371-
if (!PyUnicode_Check(arg) || (arg = PyUnicode_AsASCIIString(arg)) == NULL) {
372-
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
373-
return NULL;
371+
if (!PyUnicode_Check(arg)) {
372+
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
373+
return NULL;
374+
}
375+
376+
PyObject *asciiStr = PyUnicode_AsASCIIString(arg);
377+
if (asciiStr == NULL) {
378+
PyErr_SetString(PyExc_ValueError, "failed to convert argument to ASCII string");
379+
return NULL;
374380
}
381+
arg = asciiStr;
375382
#else
376383
if (!PyString_Check(arg)) {
377-
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
378-
return NULL;
384+
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
385+
return NULL;
379386
}
380387
#endif
381388

382389
if (PyBytes_AsStringAndSize(arg, &str, &len) == -1) {
383-
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
390+
PyErr_SetString(PyExc_ValueError, "failed to extract string and size");
391+
#if PY_MAJOR_VERSION >= 3
392+
Py_XDECREF(asciiStr);
393+
#endif
384394
return NULL;
385395
}
386396

387-
if ((len != TLSH_STRING_LEN_REQ) && (len != TLSH_STRING_LEN_REQ-2)) {
397+
if ((len != TLSH_STRING_LEN_REQ) && (len != TLSH_STRING_LEN_REQ - 2)) {
388398
PyErr_SetString(PyExc_ValueError, "argument length incorrect: not a TLSH hex string");
399+
#if PY_MAJOR_VERSION >= 3
400+
Py_XDECREF(asciiStr);
401+
#endif
389402
return NULL;
390403
}
391404

392405
if (self->tlsh.fromTlshStr(str) != 0) {
393406
PyErr_SetString(PyExc_ValueError, "argument value incorrect: not a TLSH hex string");
407+
#if PY_MAJOR_VERSION >= 3
408+
Py_XDECREF(asciiStr);
409+
#endif
394410
return NULL;
395411
}
412+
396413
self->finalized = true;
397414

415+
#if PY_MAJOR_VERSION >= 3
416+
Py_XDECREF(asciiStr);
417+
#endif
418+
398419
Py_RETURN_NONE;
399420
}
400421

0 commit comments

Comments
 (0)