=================================================================== RCS file: /cvs/mandoc/cgi.c,v retrieving revision 1.74 retrieving revision 1.76 diff -u -p -r1.74 -r1.76 --- mandoc/cgi.c 2014/07/18 14:46:25 1.74 +++ mandoc/cgi.c 2014/07/19 11:35:12 1.76 @@ -1,4 +1,4 @@ -/* $Id: cgi.c,v 1.74 2014/07/18 14:46:25 schwarze Exp $ */ +/* $Id: cgi.c,v 1.76 2014/07/19 11:35:12 schwarze Exp $ */ /* * Copyright (c) 2011, 2012 Kristaps Dzonsons * Copyright (c) 2014 Ingo Schwarze @@ -79,7 +79,6 @@ static void resp_searchform(const struct req *); static void resp_show(const struct req *, const char *); static const char *scriptname; /* CGI script name */ -static const char *httphost; /* hostname used in the URIs */ static const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9}; static const char *const sec_numbers[] = { @@ -467,6 +466,17 @@ resp_searchform(const struct req *req) puts(""); } +static int +validate_filename(const char *file) +{ + + if ('.' == file[0] && '/' == file[1]) + file += 2; + + return ( ! (strstr(file, "../") || strstr(file, "/..") || + (strncmp(file, "man", 3) && strncmp(file, "cat", 3)))); +} + static void pg_index(const struct req *req) { @@ -524,14 +534,23 @@ pg_searchres(const struct req *req, struct manpage *r, int prio, priouse; char sec; + for (i = 0; i < sz; i++) { + if (validate_filename(r[i].file)) + continue; + fprintf(stderr, "invalid filename %s in %s database\n", + r[i].file, req->q.manpath); + pg_error_internal(); + return; + } + if (1 == sz) { /* * If we have just one result, then jump there now * without any delay. */ printf("Status: 303 See Other\r\n"); - printf("Location: http://%s%s/%s/%s?", - httphost, scriptname, req->q.manpath, r[0].file); + printf("Location: %s/%s/%s?", + scriptname, req->q.manpath, r[0].file); http_printquery(req); printf("\r\n" "Content-Type: text/html; charset=utf-8\r\n" @@ -778,7 +797,8 @@ format(const struct req *req, const char *file) static void resp_show(const struct req *req, const char *file) { - if ('.' == file[0] || '/' == file[1]) + + if ('.' == file[0] && '/' == file[1]) file += 2; if ('c' == *file) @@ -811,6 +831,12 @@ pg_show(const struct req *req, const char *path) return; } + if ( ! validate_filename(sub)) { + pg_error_badrequest( + "You specified an invalid manual file."); + return; + } + resp_begin_html(200, NULL); resp_searchform(req); resp_show(req, sub); @@ -906,9 +932,6 @@ main(void) if (NULL == (scriptname = getenv("SCRIPT_NAME"))) scriptname = ""; - - if (NULL == (httphost = getenv("HTTP_HOST"))) - httphost = "localhost"; /* * First we change directory into the MAN_DIR so that