[PYTHON-CRYPTO] Erasing strings from memory?

M.-A. Lemburg mal at LEMBURG.COM
Mon Nov 11 09:30:42 CET 2002


Rich Salz wrote:
> The following module zero's out a python string.
> hope it helps.

Be careful with this: Python strings are immutable and some
are shared. The code you gave below can result in a
completely broken Python interpreter.

> # --cut here--
> #! /bin/sh
> # To unshar, remove everything before the "cut here" line
> # and feed the result to /bin/sh
> sed -e 's/^X//' >zerostr.c <<'FUNKY_STUFF'
> X/*
> X**
> X**  To compile:
> X    gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.2 -c zerostr.c
> X    gcc -shared zerostr.o -o zerostr.so
> X**  To use:
> X      a = '1234'
> X      import zerostr
> X      zerostr.zero(a)
> X      print a
> X*/
> X#include <Python.h>
> X
> Xstatic PyObject*
> Xzerostr_zero(PyObject* self, PyObject* args)
> X{
> X    PyObject* t;
> X    char* p;
> X    int i;
> X
> X    if (!PyArg_ParseTuple(args, "O", &t))
> X        return NULL;
> X    if (!PyString_Check(t)) {
> X        Py_DECREF(t);
> X        PyErr_SetString(PyExc_TypeError, "Must be a string");
> X        return NULL;
> X    }
> X    i = PyString_GET_SIZE(t);
> X    p = PyString_AS_STRING(t);
> X    while (--i >= 0)
> X        *p++ = '\0';
> X    Py_DECREF(t);
> X    Py_INCREF(Py_None);
> X    return Py_None;
> X}
> X
> Xstatic PyMethodDef zerostrMethods[] = {
> X    { "zero", zerostr_zero, METH_VARARGS,
> X        "Fill a string with NUL bytes."},
> X    { NULL, NULL, 0, NULL }
> X};
> X
> X
> Xvoid
> Xinitzerostr(void)
> X{
> X    (void)Py_InitModule("zerostr", zerostrMethods);
> X}
> FUNKY_STUFF
> sed -e 's/^X//' >setup.py <<'FUNKY_STUFF'
> X
> Xfrom distutils.core import setup, Extension
> X
> Xzm = Extension('zerostr', sources = ['zerostr.c'])
> X
> Xsetup(name='ZeroStrPackage',
> X        version='1.0',
> X        description="Sample package zero'ing a string",
> X        ext_modules = [ zm ])
> X
> FUNKY_STUFF

--
Marc-Andre Lemburg
CEO eGenix.com Software GmbH
_______________________________________________________________________
eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,...
Python Consulting:                               http://www.egenix.com/
Python Software:                    http://www.egenix.com/files/python/



More information about the python-crypto mailing list