Issue 2589: PyOS_vsnprintf() potential integer overflow leads to memory corruption (original) (raw)

On architectures that do not have a vsnprintf() in their standard library Python attempts to emulate it. When doing so, the implementation ambitiously allocates more memory than requested without verifying the sanity of the summed value. As a result it becomes possible (although unlikely) for an integer overflow to occur misallocating memory and causing a buffer overflow.

53 int 54 PyOS_vsnprintf(char *str, size_t size, const char format, va_list va) 55 { 56 int len; / # bytes written, excluding \0 / [...] 60 assert(str != NULL); 61 assert(size > 0); 62 assert(format != NULL); 63 [...] 67 / Emulate it. */ 68 buffer = PyMem_MALLOC(size + 512); 69 if (buffer == NULL) { 70 len = -666; 71 goto Done; 72 } 73 74 len = vsprintf(buffer, format, va); 75 if (len < 0) 76 /* ignore the error */; 77 78 else if ((size_t)len >= size + 512) 79 Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); 80 81 else { 82 const size_t to_copy = (size_t)len < size ? 83 (size_t)len : size - 1; 84 assert(to_copy < size); 85 memcpy(str, buffer, to_copy); 86 str[to_copy] = '\0'; 87 } 88 PyMem_FREE(buffer); 89 Done: [...] 91 str[size-1] = '\0'; 92 return len; 93 }