|
| 1 | +#include <Python.h> |
| 2 | +#include <iostream> |
| 3 | +#include <tuple> |
| 4 | + |
| 5 | +PyObject *bytes_join = NULL; |
| 6 | +PyObject *bytearray_join = NULL; |
| 7 | +PyObject *empty_bytes = NULL; |
| 8 | +PyObject *empty_bytearray = NULL; |
| 9 | +PyObject *empty_unicode = NULL; |
| 10 | + |
| 11 | +static PyObject *setup(PyObject *Py_UNUSED(module), PyObject *args) { |
| 12 | + PyArg_ParseTuple(args, "OO", &bytes_join, &bytearray_join); |
| 13 | + empty_bytes = PyBytes_FromString(""); |
| 14 | + empty_bytearray = PyByteArray_FromObject(empty_bytes); |
| 15 | + empty_unicode = PyUnicode_New(0, 127); |
| 16 | + Py_RETURN_NONE; |
| 17 | +} |
| 18 | + |
| 19 | +static PyObject *new_pyobject_id(PyObject *Py_UNUSED(module), PyObject *args) { |
| 20 | + PyObject *tainted_object; |
| 21 | + Py_ssize_t object_length; |
| 22 | + PyArg_ParseTuple(args, "On", &tainted_object, &object_length); |
| 23 | + if (PyUnicode_Check(tainted_object)) { |
| 24 | + if (PyUnicode_CHECK_INTERNED(tainted_object) == 0) { // SSTATE_NOT_INTERNED |
| 25 | + Py_INCREF(tainted_object); |
| 26 | + return tainted_object; |
| 27 | + } |
| 28 | + return PyUnicode_Join(empty_unicode, |
| 29 | + Py_BuildValue("(OO)", tainted_object, empty_unicode)); |
| 30 | + } else if (object_length > 1) { |
| 31 | + // Bytes and bytearrays with length > 1 are not interned |
| 32 | + Py_INCREF(tainted_object); |
| 33 | + return tainted_object; |
| 34 | + } else if (PyBytes_Check(tainted_object)) { |
| 35 | + return PyObject_CallFunctionObjArgs( |
| 36 | + bytes_join, empty_bytes, |
| 37 | + Py_BuildValue("(OO)", tainted_object, empty_bytes), NULL); |
| 38 | + } else { |
| 39 | + return PyObject_CallFunctionObjArgs( |
| 40 | + bytearray_join, empty_bytearray, |
| 41 | + Py_BuildValue("(OO)", tainted_object, empty_bytearray), NULL); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +static PyMethodDef TaintTrackingMethods[] = { |
| 46 | + // We are using METH_VARARGS because we need compatibility with |
| 47 | + // python 3.5, 3.6. but METH_FASTCALL could be used instead for python |
| 48 | + // >= 3.7 |
| 49 | + {"setup", (PyCFunction)setup, METH_VARARGS, "setup tainting module"}, |
| 50 | + {"new_pyobject_id", (PyCFunction)new_pyobject_id, METH_VARARGS, |
| 51 | + "new_pyobject_id"}, |
| 52 | + {NULL, NULL, 0, NULL}}; |
| 53 | + |
| 54 | +static struct PyModuleDef taint_tracking = { |
| 55 | + PyModuleDef_HEAD_INIT, "ddtrace.appsec.iast._taint_tracking._native", |
| 56 | + "taint tracking module", -1, TaintTrackingMethods}; |
| 57 | + |
| 58 | +PyMODINIT_FUNC PyInit__native(void) { |
| 59 | + PyObject *m; |
| 60 | + m = PyModule_Create(&taint_tracking); |
| 61 | + if (m == NULL) |
| 62 | + return NULL; |
| 63 | + return m; |
| 64 | +} |
0 commit comments