pyglue: generate_random_bytes/str accept positive numbers only
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Sun, 4 Aug 2019 12:41:49 +0000 (00:41 +1200)
committerAndreas Schneider <asn@cryptomilk.org>
Fri, 26 Aug 2022 07:59:32 +0000 (07:59 +0000)
We aren't yet able to generate negative numbers of random bytes.

Instead a request for -n bytes is implicitly converted into one for
SIZE_MAX - n bytes, which is typically very large. Memory exhaustion
seems a likely outcome.

With this patch callers will see a ValueError.

Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andreas Schneider <asn@samba.org>
python/pyglue.c

index 5ee2b68b8ad26e34ea5d584c2ff9625fbcca0a24..969b35145de715f76672357a80f558535c89d108 100644 (file)
@@ -37,9 +37,15 @@ static PyObject *py_generate_random_str(PyObject *self, PyObject *args)
        int len;
        PyObject *ret;
        char *retstr;
-       if (!PyArg_ParseTuple(args, "i", &len))
+       if (!PyArg_ParseTuple(args, "i", &len)) {
                return NULL;
-
+       }
+       if (len < 0) {
+               PyErr_Format(PyExc_ValueError,
+                            "random string length should be positive, not %d",
+                            len);
+               return NULL;
+       }
        retstr = generate_random_str(NULL, len);
        ret = PyUnicode_FromString(retstr);
        talloc_free(retstr);
@@ -97,9 +103,15 @@ static PyObject *py_generate_random_bytes(PyObject *self, PyObject *args)
        PyObject *ret;
        uint8_t *bytes = NULL;
 
-       if (!PyArg_ParseTuple(args, "i", &len))
+       if (!PyArg_ParseTuple(args, "i", &len)) {
                return NULL;
-
+       }
+       if (len < 0) {
+               PyErr_Format(PyExc_ValueError,
+                            "random bytes length should be positive, not %d",
+                            len);
+               return NULL;
+       }
        bytes = talloc_zero_size(NULL, len);
        if (bytes == NULL) {
                PyErr_NoMemory();