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