Blob Blame History Raw
From a9cb173c3c07e4cdb82c9bb90a28c28289207a4e Mon Sep 17 00:00:00 2001
From: Frank Denis <github@pureftpd.org>
Date: Mon, 30 Dec 2019 17:40:04 +0100
Subject: [PATCH] listdir(): reuse a single buffer to store every file name to
 display

Allocating a new buffer for each entry is useless.

And as these buffers are allocated on the stack, on systems with a
small stack size, with many entries, the limit can easily be reached,
causing a stack exhaustion and aborting the user session.

Reported by Antonio Morales from the GitHub Security Lab team, thanks!
---
 src/ls.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/src/ls.c b/src/ls.c
index 9d01ecf..d4dd653 100644
--- a/src/ls.c
+++ b/src/ls.c
@@ -695,6 +695,8 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
     PureFileInfo *s;
     PureFileInfo *r;
     char *c_buf;
+    char *alloca_subdir;
+    size_t sizeof_subdir;
     int d;
 
     if (depth >= max_ls_depth || matches >= max_ls_files) {
@@ -729,14 +731,12 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
     }
     outputfiles(f, tls_fd);
     r = dir;
+    sizeof_subdir = PATH_MAX + 1U;
+    if ((alloca_subdir = ALLOCA(sizeof_subdir)) == NULL) {
+        goto toomany;
+    }
     while (opt_R && r != s) {
         if (r->name_offset != (size_t) -1 && !chdir(FI_NAME(r))) {
-            char *alloca_subdir;
-            const size_t sizeof_subdir = PATH_MAX + 1U;
-
-            if ((alloca_subdir = ALLOCA(sizeof_subdir)) == NULL) {
-                goto toomany;
-            }
             if (SNCHECK(snprintf(alloca_subdir, sizeof_subdir, "%s/%s",
                                  name, FI_NAME(r)), sizeof_subdir)) {
                 goto nolist;
@@ -765,8 +765,8 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
             free(c_buf);
 #endif
             listdir(depth + 1U, f, tls_fd, alloca_subdir);
+
             nolist:
-            ALLOCA_FREE(alloca_subdir);
             if (matches >= max_ls_files) {
                 goto toomany;
             }
@@ -779,6 +779,7 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
         r++;
     }
     toomany:
+    ALLOCA_FREE(alloca_subdir);
     free(names);
     free(dir);
     names = NULL;
-- 
2.25.4