#include <config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#include <unistd.h>
#include <errno.h>
#include "sudoers.h"
static bool
cmnd_allowed(char *cmnd, size_t cmnd_size, struct stat *cmnd_sbp,
char * const *whitelist)
{
const char *cmnd_base;
char * const *wl;
debug_decl(cmnd_allowed, SUDOERS_DEBUG_UTIL)
if (!sudo_goodpath(cmnd, cmnd_sbp))
debug_return_bool(false);
if (whitelist == NULL)
debug_return_bool(true);
if ((cmnd_base = strrchr(cmnd, '/')) == NULL)
debug_return_bool(false);
cmnd_base++;
for (wl = whitelist; *wl != NULL; wl++) {
struct stat sb;
const char *base;
if ((base = strrchr(*wl, '/')) == NULL)
continue;
base++;
if (strcmp(cmnd_base, base) != 0)
continue;
if (sudo_goodpath(*wl, &sb) &&
sb.st_dev == cmnd_sbp->st_dev && sb.st_ino == cmnd_sbp->st_ino) {
if (strlcpy(cmnd, *wl, cmnd_size) < cmnd_size)
return true;
debug_return_bool(true);
}
}
debug_return_bool(false);
}
int
find_path(const char *infile, char **outfile, struct stat *sbp,
const char *path, int ignore_dot, char * const *whitelist)
{
char command[PATH_MAX];
const char *cp, *ep, *pathend;
bool found = false;
bool checkdot = false;
int len;
debug_decl(find_path, SUDOERS_DEBUG_UTIL)
if (strchr(infile, '/') != NULL) {
if (strlcpy(command, infile, sizeof(command)) >= sizeof(command)) {
errno = ENAMETOOLONG;
debug_return_int(NOT_FOUND_ERROR);
}
found = cmnd_allowed(command, sizeof(command), sbp, whitelist);
goto done;
}
if (path == NULL)
debug_return_int(NOT_FOUND);
pathend = path + strlen(path);
for (cp = sudo_strsplit(path, pathend, ":", &ep); cp != NULL;
cp = sudo_strsplit(NULL, pathend, ":", &ep)) {
if (cp == ep || (*cp == '.' && cp + 1 == ep)) {
checkdot = 1;
continue;
}
len = snprintf(command, sizeof(command), "%.*s/%s",
(int)(ep - cp), cp, infile);
if (len < 0 || len >= ssizeof(command)) {
errno = ENAMETOOLONG;
debug_return_int(NOT_FOUND_ERROR);
}
found = cmnd_allowed(command, sizeof(command), sbp, whitelist);
if (found)
break;
}
if (!found && checkdot) {
len = snprintf(command, sizeof(command), "./%s", infile);
if (len < 0 || len >= ssizeof(command)) {
errno = ENAMETOOLONG;
debug_return_int(NOT_FOUND_ERROR);
}
found = cmnd_allowed(command, sizeof(command), sbp, whitelist);
if (found && ignore_dot)
debug_return_int(NOT_FOUND_DOT);
}
done:
if (found) {
if ((*outfile = strdup(command)) == NULL)
debug_return_int(NOT_FOUND_ERROR);
debug_return_int(FOUND);
}
debug_return_int(NOT_FOUND);
}