HEADS UP: emalloc issue

php.internals

Sascha Schumann

23 years ago
Hi, if your extension determines the amount of memory to allocate by using a multiplication such as this void *p = emalloc(sizeof(struct foo) * nr_entries); then it is likely that your code is vulnerable to an integer overflow. This happens, when the product of the multiplication cannot be represented by the integral type "long". This can enable an attacker to overwrite data on the heap, possibly leading to a full compromise of the server. To avert such a scenario, we have introduced a safe_emalloc function. You use this API member as follows: void *p = safe_emalloc(sizeof(struct foo), nr_entries, 0); The function calculates the product of the first two operands and finally adds the third operand to that product. During all steps, the function ensures that no integer overflow takes place. If it detects an overflow, the script execution will be halted. Otherwise, it returns the requested amount of memory. Please audit your source code! Look at each and every invocation of emalloc and ensure that instances are properly replaced with safe_emalloc calls. If your extension code should work independently of the PHP version, we suggest placing the following code after #include "php.h": #ifndef safe_emalloc # define safe_emalloc(a,b,c) emalloc((a)*(b)+(c)) #endif This won't protect you from integer overflows. However, it enables you to write code which automatically works savely when compiled in the right context. - Sascha