Commit 014d49559acfe9351a3b1f77e9aa43513ce53c94

Erik Aigner 2019-02-20T15:30:11

apply: prevent OOB read when parsing source buffer When parsing the patch image from a string, we split the string by newlines to get a line-based view of it. To split, we use `memchr` on the buffer and limit the buffer length by the original length provided by the caller. This works just fine for the first line, but for every subsequent line we need to actually subtract the amount of bytes that we have already read. The above issue can be easily triggered by having a source buffer with at least two lines, where the second line does _not_ end in a newline. Given a string "foo\nb", we have an original length of five bytes. After having extracted the first line, we will point to 'b' and again try to `memchr(p, '\n', 5)`, resulting in an out-of-bounds read of four bytes. Fix the issue by correctly subtracting the amount of bytes already read.

diff --git a/AUTHORS b/AUTHORS
index 458ff06..784bab3 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -23,6 +23,7 @@ Dmitry Kovega
 Emeric Fermas
 Emmanuel Rodriguez
 Eric Myhre
+Erik Aigner
 Florian Forster
 Holger Weiss
 Ingmar Vanhassel
diff --git a/src/apply.c b/src/apply.c
index d72aa83..0becf94 100644
--- a/src/apply.c
+++ b/src/apply.c
@@ -59,7 +59,7 @@ static int patch_image_init_fromstr(
 	git_pool_init(&out->pool, sizeof(git_diff_line));
 
 	for (start = in; start < in + in_len; start = end) {
-		end = memchr(start, '\n', in_len);
+		end = memchr(start, '\n', in_len - (start - in));
 
 		if (end == NULL)
 			end = in + in_len;