cgit

commit fe36f84d843cd755c6dab629a0758264de5bcc00

Author: Jason A. Donenfeld <Jason@zx2c4.com>

ui-summary: Disallow directory traversal

Using the url= query string, it was possible request arbitrary files
from the filesystem if the readme for a given page was set to a
filesystem file. The following request would return my /etc/passwd file:

http://git.zx2c4.com/?url=/somerepo/about/../../../../etc/passwd
http://data.zx2c4.com/cgit-directory-traversal.png

This fix uses realpath(3) to canonicalize all paths, and then compares
the base components.

This fix introduces a subtle timing attack, whereby a client can check
whether or not strstr is called using timing measurements in order
to determine if a given file exists on the filesystem.

This fix also does not account for filesystem race conditions (TOCTOU)
in resolving symlinks.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>

 ui-summary.c | 16 ++++++++++++++++


diff --git a/ui-summary.c b/ui-summary.c
index 2f8a822ad5c1b5414b99ffeec2573669b2ba9a46..57206ddff1518b3a757df6c6fc390797fc34a410 100644
--- a/ui-summary.c
+++ b/ui-summary.c
@@ -99,6 +99,7 @@ /* The caller must free filename and ref after calling this. */
 void cgit_parse_readme(const char *readme, const char *path, char **filename, char **ref, struct cgit_repo *repo)
 {
 	const char *slash, *colon;
+	char *resolved_base, *resolved_full;
 
 	*filename = NULL;
 	*ref = NULL;
@@ -133,7 +134,19 @@ 			slash = colon;
 		}
 		*filename = xmalloc(slash - readme + 1 + strlen(path) + 1);
 		strncpy(*filename, readme, slash - readme + 1);
+		if (!(*ref))
+			resolved_base = realpath(*filename, NULL);
 		strcpy(*filename + (slash - readme + 1), path);
+		if (!(*ref))
+			resolved_full = realpath(*filename, NULL);
+		if (!(*ref) && (!resolved_base || !resolved_full || strstr(resolved_full, resolved_base) != resolved_full)) {
+			free(*filename);
+			*filename = NULL;
+		}
+		if (!(*ref)) {
+			free(resolved_base);
+			free(resolved_full);
+		}
 	} else
 		*filename = xstrdup(readme);
 }
@@ -142,6 +155,9 @@ void cgit_print_repo_readme(char *path)
 {
 	char *filename, *ref;
 	cgit_parse_readme(ctx.repo->readme, path, &filename, &ref, ctx.repo);
+
+	if (!filename)
+		return;
 
 	/* Print the calculated readme, either from the git repo or from the
 	 * filesystem, while applying the about-filter.