Adapted from PHP upstream - Shawn Starr
From e6c48213c22ed50b2b987b479fcc1ac709394caa Mon Sep 17 00:00:00 2001
From: Stanislav Malyshev <stas@php.net>
Date: Mon, 18 Jul 2016 21:44:39 -0700
Subject: [PATCH] Fix bug #72606: heap-buffer-overflow (write)
simplestring_addn simplestring.c
--- a/src/simplestring.c 2017-07-25 19:14:20.201298471 -0400
+++ b/src/simplestring.c 2017-07-25 19:19:43.162374298 -0400
@@ -35,6 +35,7 @@ static const char rcsid[] = "#(@) $Id: s
#include <string.h>
#include <stdlib.h>
+#include <limits.h>
#define SIMPLESTRING_INCR 32
@@ -167,6 +168,9 @@ void simplestring_free(simplestring* str
}
/******/
+#ifndef SIZE_MAX
+#define SIZE_MAX ((size_t)-1)
+#endif
/****f* FUNC/simplestring_addn
* NAME
* simplestring_addn
@@ -185,18 +189,31 @@ void simplestring_free(simplestring* str
* simplestring_add ()
* SOURCE
*/
-void simplestring_addn(simplestring* target, const char* source, int add_len) {
+void simplestring_addn(simplestring* target, const char* source, size_t add_len) {
+ size_t newsize = target->size, incr = 0;
if(target && source) {
if(!target->str) {
simplestring_init_str(target);
}
+
+ if((SIZE_MAX - add_len) < target->len || (SIZE_MAX - add_len - 1) < target->len) {
+ /* check for overflows, if there's a potential overflow do nothing */
+ return;
+ }
+
if(target->len + add_len + 1 > target->size) {
/* newsize is current length + new length */
- int newsize = target->len + add_len + 1;
- int incr = target->size * 2;
+ newsize = target->len + add_len + 1;
+ incr = target->size * 2;
/* align to SIMPLESTRING_INCR increments */
- newsize = newsize - (newsize % incr) + incr;
+ if (incr) {
+ newsize = newsize - (newsize % incr) + incr;
+ }
+ if(newsize < (target->len + add_len + 1)) {
+ /* some kind of overflow happened */
+ return;
+ }
target->str = (char*)realloc(target->str, newsize);
target->size = target->str ? newsize : 0;
--- a/src/simplestring.h 2017-07-25 19:14:24.030263803 -0400
+++ b/src/simplestring.h 2017-07-25 19:14:32.547186689 -0400
@@ -63,7 +63,7 @@ void simplestring_init(simplestring* str
void simplestring_clear(simplestring* string);
void simplestring_free(simplestring* string);
void simplestring_add(simplestring* string, const char* add);
-void simplestring_addn(simplestring* string, const char* add, int add_len);
+void simplestring_addn(simplestring* string, const char* add, size_t add_len);
#ifdef __cplusplus
}