7c0489
commit ddc650e9b3dc916eab417ce9f79e67337b05035c
7c0489
Author: Andreas Schwab <schwab@suse.de>
7c0489
Date:   Wed Feb 19 17:21:46 2020 +0100
7c0489
7c0489
    Fix use-after-free in glob when expanding ~user (bug 25414)
7c0489
    
7c0489
    The value of `end_name' points into the value of `dirname', thus don't
7c0489
    deallocate the latter before the last use of the former.
7c0489
7c0489
diff --git a/posix/glob.c b/posix/glob.c
7c0489
index cba9cd1819..4580cefb9f 100644
7c0489
--- a/posix/glob.c
7c0489
+++ b/posix/glob.c
7c0489
@@ -827,31 +827,32 @@ __glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
7c0489
 	      {
7c0489
 		size_t home_len = strlen (p->pw_dir);
7c0489
 		size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
7c0489
-		char *d;
7c0489
+		char *d, *newp;
7c0489
+		bool use_alloca = glob_use_alloca (alloca_used,
7c0489
+						   home_len + rest_len + 1);
7c0489
 
7c0489
-		if (__glibc_unlikely (malloc_dirname))
7c0489
-		  free (dirname);
7c0489
-		malloc_dirname = 0;
7c0489
-
7c0489
-		if (glob_use_alloca (alloca_used, home_len + rest_len + 1))
7c0489
-		  dirname = alloca_account (home_len + rest_len + 1,
7c0489
-					    alloca_used);
7c0489
+		if (use_alloca)
7c0489
+		  newp = alloca_account (home_len + rest_len + 1, alloca_used);
7c0489
 		else
7c0489
 		  {
7c0489
-		    dirname = malloc (home_len + rest_len + 1);
7c0489
-		    if (dirname == NULL)
7c0489
+		    newp = malloc (home_len + rest_len + 1);
7c0489
+		    if (newp == NULL)
7c0489
 		      {
7c0489
 			scratch_buffer_free (&pwtmpbuf);
7c0489
 			retval = GLOB_NOSPACE;
7c0489
 			goto out;
7c0489
 		      }
7c0489
-		    malloc_dirname = 1;
7c0489
 		  }
7c0489
-		d = mempcpy (dirname, p->pw_dir, home_len);
7c0489
+		d = mempcpy (newp, p->pw_dir, home_len);
7c0489
 		if (end_name != NULL)
7c0489
 		  d = mempcpy (d, end_name, rest_len);
7c0489
 		*d = '\0';
7c0489
 
7c0489
+		if (__glibc_unlikely (malloc_dirname))
7c0489
+		  free (dirname);
7c0489
+		dirname = newp;
7c0489
+		malloc_dirname = !use_alloca;
7c0489
+
7c0489
 		dirlen = home_len + rest_len;
7c0489
 		dirname_modified = 1;
7c0489
 	      }