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