From c9d31b711e8906cf248566f43142f20b03e20cbf Mon Sep 17 00:00:00 2001
From: Edward Thomson <ethomson@edwardthomson.com>
Date: Fri, 17 Nov 2023 16:54:47 +0000
Subject: [PATCH] revparse: fix parsing bug for trailing `@`

When parsing a revspec that ends with a trailing `@`, explicitly stop
parsing. Introduce a sentinel variable to explicitly stop parsing.

Prior to this, we would set `spec` to `HEAD`, but were looping on the
value of `spec[pos]`, so we would continue walking the (new) `spec`
at offset `pos`, looking for a NUL. This is obviously an out-of-bounds
read.

Credit to Michael Rodler (@f0rki) and Amazon AWS Security.

CVE: CVE-2024-24575

Upstream-Status: Backport [https://github.com/libgit2/libgit2/commit/c9d31b711e8906cf248566f43142f20b03e20cbf]

Signed-off-by: Soumya Sambu <soumya.sambu@windriver.com>
---
 src/revparse.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/src/revparse.c b/src/revparse.c
index 9bc28e9fc..d3bbe840b 100644
--- a/src/revparse.c
+++ b/src/revparse.c
@@ -685,6 +685,7 @@ static int revparse(
	git_object *base_rev = NULL;

	bool should_return_reference = true;
+	bool parsed = false;

	GIT_ASSERT_ARG(object_out);
	GIT_ASSERT_ARG(reference_out);
@@ -694,7 +695,7 @@ static int revparse(
	*object_out = NULL;
	*reference_out = NULL;

-	while (spec[pos]) {
+	while (!parsed && spec[pos]) {
		switch (spec[pos]) {
		case '^':
			should_return_reference = false;
@@ -801,6 +802,8 @@ static int revparse(
				break;
			} else if (spec[pos+1] == '\0') {
				spec = "HEAD";
+				identifier_len = 4;
+				parsed = true;
				break;
			}
			/* fall through */
--
2.40.0
