Subject: [PATCH v2] win32: ensure len does not cause any overreads

From: "AreaZR via GitGitGadget" <[email-masked]>
Date: Wed, 18 Dec 2024 00:29:49 +0000

From: Seija Kijin <[email-masked]>

Check to make sure len is always two less than MAX_PATH,
otherwise an overread will occur, which is
undefined behavior.

Signed-off-by: Seija Kijin <[email-masked]>
---
    win32: ensure len does not cause any overreads
    
    Check to make sure len is always less than MAX_PATH, otherwise an
    overread will occur, which is undefined behavior.
    
    Signed-off-by: Seija Kijin [email-masked]

Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-1404%2FAreaZR%2Foverread-v2
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-1404/AreaZR/overread-v2
Pull-Request: https://github.com/git/git/pull/1404

Range-diff vs v1:

 1:  f9ec5429d01 ! 1:  dfc34fb4c1a win32: ensure len does not cause any overreads
     @@ Metadata
       ## Commit message ##
          win32: ensure len does not cause any overreads
      
     -    Check to make sure len is always less than MAX_PATH,
     +    Check to make sure len is always two less than MAX_PATH,
          otherwise an overread will occur, which is
          undefined behavior.
      
     @@ Commit message
      
       ## compat/win32/dirent.c ##
      @@ compat/win32/dirent.c: DIR *opendir(const char *name)
     - 	DIR *dir;
     - 
     - 	/* convert name to UTF-16 and check length < MAX_PATH */
     --	if ((len = xutftowcs_path(pattern, name)) < 0)
     -+	if ((len = xutftowcs_path(pattern, name)) < 0 || len > MAX_PATH)
     + 	if ((len = xutftowcs_path(pattern, name)) < 0)
       		return NULL;
       
     ++	if (len + 2 >= MAX_PATH)
     ++		return NULL;
     ++
       	/* append optional '/' and wildcard '*' */
     + 	if (len && !is_dir_sep(pattern[len - 1]))
     + 		pattern[len++] = '/';

 compat/win32/dirent.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/compat/win32/dirent.c b/compat/win32/dirent.c
index 52420ec7d4d..fb63d1adbc5 100644
--- a/compat/win32/dirent.c
+++ b/compat/win32/dirent.c
@@ -30,6 +30,9 @@ DIR *opendir(const char *name)
 	if ((len = xutftowcs_path(pattern, name)) < 0)
 		return NULL;
 
+	if (len + 2 >= MAX_PATH)
+		return NULL;
+
 	/* append optional '/' and wildcard '*' */
 	if (len && !is_dir_sep(pattern[len - 1]))
 		pattern[len++] = '/';

base-commit: 2ccc89b0c16c51561da90d21cfbb4b58cc877bf6
-- 
gitgitgadget