diff --git a/configure.ac b/configure.ac index 42cf4b94..23e5bebd 100644 --- a/configure.ac +++ b/configure.ac @@ -172,6 +172,15 @@ AC_LINK_IFELSE( AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no])]) +# closefrom(): glibc 2.34+, BSDs, Solaris; not macOS. +AC_MSG_CHECKING([for closefrom]) +AC_LINK_IFELSE( + [AC_LANG_PROGRAM([[#include ]], + [[closefrom(3);]])], + [AC_DEFINE([HAVE_CLOSEFROM], [1], [closefrom() available and declared]) + AC_MSG_RESULT([yes])], + [AC_MSG_RESULT([no])]) + AC_MSG_CHECKING([for utimensat]) AC_LINK_IFELSE( [AC_LANG_PROGRAM([[#include diff --git a/examples/echoserver/echoserver.c b/examples/echoserver/echoserver.c index 3571e2da..c6ff5e6c 100644 --- a/examples/echoserver/echoserver.c +++ b/examples/echoserver/echoserver.c @@ -85,8 +85,11 @@ #include #endif #ifndef USE_WINDOWS_API + #include #include + #include #include + #include #endif #include #if defined(__QNX__) || defined(__QNXNTO__) @@ -1060,6 +1063,27 @@ static int wsShellStartCb(WOLFSSH_CHANNEL* channel, void* ctx) system("env"); #endif + /* Started as root, the shell runs as the user who logged in, + * or not at all. Otherwise the process has no root to give + * up. */ + if (geteuid() == 0) { + /* Give the user its terminal, so it can reopen it by + * name. */ + if (fchown(STDIN_FILENO, p_passwd->pw_uid, (gid_t)-1) != 0 + || fchmod(STDIN_FILENO, 0620) != 0) { + _exit(EXIT_FAILURE); + } + if (initgroups(p_passwd->pw_name, p_passwd->pw_gid) != 0 + || setgid(p_passwd->pw_gid) != 0 + || setuid(p_passwd->pw_uid) != 0) { + _exit(EXIT_FAILURE); + } + if (p_passwd->pw_uid != 0 + && (setuid(0) == 0 || seteuid(0) == 0)) { + _exit(EXIT_FAILURE); + } + } + setenv("HOME", p_passwd->pw_dir, 1); setenv("LOGNAME", p_passwd->pw_name, 1); rc = chdir(p_passwd->pw_dir); @@ -1069,6 +1093,23 @@ static int wsShellStartCb(WOLFSSH_CHANNEL* channel, void* ctx) _exit(EXIT_FAILURE); } + /* keep only the pty on 0-2; don't leak the server's sockets */ + #ifdef HAVE_CLOSEFROM + closefrom(STDERR_FILENO + 1); + #else + { + long fd; + long maxFd = sysconf(_SC_OPEN_MAX); + + if (maxFd < 0) { + maxFd = 1024; + } + for (fd = STDERR_FILENO + 1; fd < maxFd; fd++) { + (void)close((int)fd); + } + } + #endif + execv("/bin/sh", (char **)args); _exit(EXIT_FAILURE); }