#include "sbox.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if SET_LIMITS #include #endif /* DESCRIPTION sbox is designed to allow untrusted users to run CGI scripts without endangering the security of the site as a whole. $Revision: 1.2 $ Call as "http://your.site.com/cgi-bin/sbox/path/to/end_user/script" 1. sbox does a series of checks to confirm that it has been called in correct context a. user ID is WEB_USER b. group ID is WEB_GROUP c. neither of these is root 2. sbox fetches the target script named in PATH_TRANSLATED a. actually, it walks down the path until it finds the first executable file 3. sbox performs checks on the target script a. script is not SUID or SGID b. script is executable c. script is not writable by WEB_USER or WEB_GROUP d. directory that script lives in is not writable by WEB_USER or WEB_GROUP 4. sbox determines user and group of owner of the script file or its enclosing directory 5. sbox changes its uid and gid to match the script's file or directory 6. sbox checks that the script is within the owner's home directory 7. sbox chroots to the new root directory 8. sbox fixes PATH_TRANSLATED and SCRIPT_NAME for chroot change 9. sbox sets resource limits 10. sbox logs everything 11. sbox execs script */ /* Copyright info: * Copyright 1997, Lincoln D. Stein * * Parts of this code are derived from suexec.c, Copyright 1995-1997 The Apache Group */ #ifndef MAXPATHLEN #ifdef PATH_MAX #define MAXPATHLEN PATH_MAX #else #define MAXPATHLEN 8192 #endif #endif #ifndef NAME_MAX #define NAME_MAX 512 #endif #define AP_ENVBUF 256 extern char **environ; /* needed to compile with -ansi */ #ifndef strdup extern char *strdup (const char *); #endif #ifndef chroot extern int chroot (const char *path); #endif static char **cleanenv = NULL; static FILE *log; static void open_log(); static void log_error(const char* fmt, ...); static void fatal_error(const char* fmt, ...); static void check_consistency(); static char* fetch_target(char *root,char** additional_info, struct stat* targ,struct stat* dir); static char* to_abs(char* directory); static char* document_root (); static void check_target(const char* newroot, const char* target, const struct stat *file_stats, const struct stat *dir_stats); static char* fetch_newroot(char* docroot); static char* shave(char* newroot, char* target); static void clean_env(); static void tweak_environment(char* newroot, char* root, char* target, char* additional_info); static int set_env(const char *name, const char *value, int overwrite); static char* escape(const char* str); static void chdir_fix(char* newroot, char* target); #if SET_LIMITS static void set_limits(); #endif static char *safe_env_lst[] = { "AUTH_TYPE", "CONTENT_LENGTH", "CONTENT_TYPE", "DATE_GMT", "DATE_LOCAL", "DOCUMENT_NAME", "DOCUMENT_PATH_INFO", "DOCUMENT_URI", "FILEPATH_INFO", "GATEWAY_INTERFACE", "LAST_MODIFIED", "QUERY_STRING", "QUERY_STRING_UNESCAPED", "REMOTE_ADDR", "REMOTE_HOST", "REMOTE_IDENT", "REMOTE_PORT", "REMOTE_USER", "REDIRECT_QUERY_STRING", "REDIRECT_STATUS", "REDIRECT_URL", "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_URI", "SCRIPT_URL", "SERVER_ADMIN", "SERVER_NAME", "SERVER_PORT", "SERVER_PROTOCOL", "SERVER_SOFTWARE", "USER_NAME", "TZ", #if !DO_CHROOT "SCRIPT_NAME", "PATH_INFO", "PATH_TRANSLATED", "DOCUMENT_ROOT", "SCRIPT_FILENAME", #endif NULL }; /***************** START OF CODE ****************/ int main (int argc, char* argv[]) { struct stat target_stat,dir_stat; char *target,*newroot,*root,*additional_info,*cmd; int gid,uid,i,return_int; open_log(); check_consistency(); /* figure out the base of the user's HTML document tree */ root = document_root(); /* resolve the additional path information correctly */ target = fetch_target(root,&additional_info,&target_stat,&dir_stat); #if DO_CHROOT /* find the absolute path name of the root */ to_abs(root); /* calculate the new root for chroot*/ newroot = fetch_newroot(root); #endif /* check that the target is OK */ check_target(newroot,target,&target_stat,&dir_stat); #if DO_CHROOT /* fix the environment */ tweak_environment(newroot,root,target,additional_info); #if !defined(DEBUG) /* change to the owner's root */ if (chroot(newroot) < 0) fatal_error("couldn't chroot to %s (%s)\n",escape(newroot),strerror(errno)); #endif #endif #if DO_CHROOT && !defined(DEBUG) cmd = shave(newroot,target); #else cmd = target; #endif clean_env(); /* set to the owner's uid and gid */ #if DO_SGID || DO_SUID gid = SID_MODE == DIRECTORY ? dir_stat.st_gid : target_stat.st_gid; uid = SID_MODE == DIRECTORY ? dir_stat.st_uid : target_stat.st_uid; #if DO_SGID && !defined(DEBUG) if (setgid(gid) < 0) { fatal_error("couldn't setgid() to %d (%s)\n",dir_stat.st_gid,strerror(errno)); } #else /* give up our sgid privileges if any*/ if (setgid(getgid()) < 0) { fatal_error("couldn't setgid() to %d (%s)\n",getgid(),strerror(errno)); } #endif #if DO_SUID && !defined(DEBUG) if (setuid(uid) < 0) { fatal_error("couldn't setuid() to %d (%s)\n",dir_stat.st_uid,strerror(errno)); } #endif #endif /* give up our root privileges now */ if (setuid(getuid()) < 0) { fatal_error("couldn't setuid() to %d (%s)\n",getuid(),strerror(errno)); } #ifdef LOG_FILE log_error("executing %s for uid %d, gid %d\n",target,getuid(),getgid()); #endif /* set hard and soft limits on resource usage */ /* important to do this after log is closed because otherwise the log file size will be restricted by the LIMIT_FSIZE_SOFT value */ #if SET_LIMITS set_limits(); #endif #ifdef LOG_FILE log_error("after set_limits() call\n"); #endif /* fix up argv[] array */ argv[0] = cmd; /* chdir() to new directory */ chdir_fix(newroot,target); #ifdef LOG_FILE log_error("after chdir_fix() call\n"); log_error("Going to try this: %s , %s, %s\n", cmd, argv[1], cleanenv[0]); #endif //if (log && log != stderr) // fclose(log); /* execute the target */ return_int = execve(cmd,argv,cleanenv); #ifdef LOG_FILE log_error("after execve() %d \n", return_int); #endif /* if we get here, then something went wrong -- we won't be able to reopen the log file because we've given up privileges, logging to stderr causes an Apache "Premature end of script" error because it's expecting a Content-Type header, so disable logging via write_log entirely by setting log to NULL. */ log = NULL; fatal_error("exec of %s failed (%s)\n",escape(cmd),strerror(errno)); return -1; } /* Will error out if one of the consistency checks fails. */ void check_consistency() { struct passwd *pass; struct group *grp; int uid,gid; #if !defined(DEBUG) /* get our group and user ids */ uid = getuid(); if ((pass = getpwuid(uid)) == NULL) fatal_error("invalid uid: (%ld)\n", uid); gid = getgid(); if ((grp = getgrgid(gid)) == NULL) fatal_error("invalid gid: (%ld)\n", gid); /* exit if either the uid or gid are zero */ if (uid == 0) fatal_error("cannot be run as root\n"); if (gid == 0) fatal_error("cannot be run as the root group\n"); /* Make sure that we were invoked by the Web user and group */ if (strcmp(WEB_USER,pass->pw_name)) fatal_error("invoked by %s, but must be run by %s\n",escape(pass->pw_name),escape(WEB_USER)); if (strcmp(WEB_GROUP,grp->gr_name)) fatal_error("invoked by group %s, but must be run by group %s\n",escape(grp->gr_name),escape(WEB_GROUP)); #endif } void open_log () { #ifdef LOG_FILE if (strlen(LOG_FILE) > 0) { if ((log = fopen(LOG_FILE, "a")) == NULL) { fprintf(stderr, "sbox failed to open log file. Falling back to stderr.\n"); log = stderr; } } else { log = stderr; } #else log = NULL; #endif } static void write_log(const char* fmt, va_list ap) { time_t timevar; char* timestr; if (log == NULL) return; timevar = time(NULL); timestr = ctime(&timevar); timestr[strlen(timestr)-1]='\0'; fprintf(log,"[%s] sbox: ",timestr); vfprintf(log, fmt, ap); fflush(log); return; } void log_error(const char* fmt, ...) { va_list ap; va_start(ap, fmt); write_log(fmt,ap); va_end(ap); } void fatal_error(const char* fmt, ...) { va_list ap; char* webmaster; va_start(ap, fmt); write_log(fmt,ap); #if ECHO_FAILURES webmaster = (char*)getenv("SERVER_ADMIN"); fprintf(stdout,"Content-type: text/html\n\n"); fprintf(stdout,webmaster ? "%s (%s).": "%s", CANNED_ERROR_TOP,webmaster,webmaster); fprintf(stdout,"
"); vprintf(fmt, ap); fprintf(stdout,"
%s",CANNED_ERROR_BOTTOM); fprintf(stdout,"

sbox version %3.2f
%s


",VERSION,"$Id: sbox.c,v 1.2 2005/02/03 02:39:13 thomas Exp $"); #else fprintf(stdout,"Content-type: text/html\n\n%s",CANNED_ERROR); #endif fflush(stdout); va_end(ap); exit(-1); } /* Find the physical path of a directory, following symbolic and hard links. This transforms the argument in place, so it must be at least MAXPATHLEN in size! */ static char* to_abs(char* directory) { if (chdir(directory) < 0) fatal_error("Can't chdir() to %s: %s\n",escape(directory),strerror(errno)); if (!getcwd(directory,MAXPATHLEN)) fatal_error("Error during getcwd(): %s\n",strerror(errno)); return directory; } #ifdef USE_ABSOLUTE_ROOT char* document_root () { char *document_root; int pathlen; if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1))) fatal_error("out of memory while allocating space for document root string\n"); pathlen = strlen(USE_ABSOLUTE_ROOT); strncpy(document_root,USE_ABSOLUTE_ROOT, pathlen+1); document_root[pathlen+1] = '\0'; return document_root; } #else /* Find the document root by subtracting PATH_INFO from PATH_TRANSLATED */ char* document_root () { char *path_info,*path_translated,*document_root; int p,v,common; /* fetch the PATH_TRANSLATED environment variable */ /* should print out usage information, actually */ path_translated = (char*) getenv("PATH_TRANSLATED"); if (path_translated == NULL) fatal_error("Please specify the script to run with the format: \"%s/script/to/run\".\n", escape((char*)getenv("SCRIPT_NAME"))); /* fetch the PATH_TRANSLATED environment variable */ /* should print out usage information, actually */ path_info = (char*) getenv("PATH_INFO"); if (path_info == NULL) fatal_error("please specify the script to run \"%s/script/to/run\"\n", escape((char*)getenv("SCRIPT_NAME"))); /* find the document root by proceeding from right to left */ for (common=p=strlen(path_translated),v=strlen(path_info); p>=0 && v>=0; p--,v--) { if (path_translated[p] != path_info[v]) break; if (path_translated[p] == '/') common = p; } if (path_translated[common] == '/') common--; /* now common points to the end of the document root */ if (common+2 > MAXPATHLEN) fatal_error("path translated is larger than MAXPATHLEN: \"%s\"",path_translated); /* at this point, common points to the end of the document root */ if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1))) fatal_error("out of memory while allocating space for document root string\n"); strncpy(document_root,path_translated,common+1); document_root[common+1] = '\0'; return document_root; } #endif /* Find the path to the target script and return it, along * with the additional path info, if any. Also returns stat * structures for the target and its directory. * A side-effect is that the target's directory is made the current * working directory. */ char* fetch_target(char* root,char** additional,struct stat* starg,struct stat* sdir) { char *path_info,*path_translated,*dir=NULL,*path,*p; char *raw,*shaved,target[MAXPATHLEN+1],directory[MAXPATHLEN+1]; int valid = 0; int additional_length,max; /* fetch the PATH_{TRANSLATED,INFO} environment variables */ /* we will have errored out before this if these are undefined or zero length */ path_translated = (char*) getenv("PATH_TRANSLATED"); path_info = (char*) getenv("PATH_INFO"); if (path_info[0] != '/') fatal_error("PATH_INFO does not begin with a '/'\n"); /* if this is the /~user type of path info, then the translated path is the root, appended to CGI_BIN, appended to the shaved path */ if (path_info[1] == '~') shaved = shave(root,path_translated); else shaved = path_info; if (strlen(root)+1+strlen(CGI_BIN) > MAXPATHLEN) fatal_error("Script directory path larger than MAXPATHLEN\n"); strncpy(directory,root,MAXPATHLEN); directory[MAXPATHLEN] = '\0'; strncat(directory,"/",1); strncat(directory,CGI_BIN,strlen(CGI_BIN)); /* resolve symbolic links and relative paths */ to_abs(directory); max = strlen(directory) + strlen(shaved) + 1; if (!(raw = (char*)calloc(sizeof(char),max))) fatal_error("Unable to allocate memory for path to CGI script: %s\n",strerror(errno)); strncpy(raw,directory,max); strncat(raw,shaved,strlen(shaved)); raw[max-1] = '\0'; /* step down the path until we find the directory and the executable */ p = raw+1; while ((p = strchr(p,'/'))) { if ( (p-raw) > MAXPATHLEN) fatal_error("path_info too long\n"); strncpy(target,raw,p-raw); target[p-raw] = '\0'; /* make sure there are no ".." path components!!!! */ if (strncmp(p,"/..",3) == 0) fatal_error("path to CGI script (%s) must not contain relative path components\n",escape(raw)); if (stat(target,starg) < 0) fatal_error("Stat failed. %s: %s\n",escape(target),strerror(errno)); /* if it's a directory, then copy it into dir for safe keeping */ if (S_ISDIR(starg->st_mode)) memcpy((void*)sdir,(void*)starg,sizeof(struct stat)); else if ((valid = S_ISREG(starg->st_mode)) == TRUE ) break; dir = p; p++; } /* If the executable is the last item on the path, then we will not have found a valid partial path. Stat the whole thing. */ if (!valid) { if (stat(raw,starg) < 0) fatal_error("Stat failed. %s: %s\n",escape(raw),strerror(errno)); if (!S_ISREG(starg->st_mode)) fatal_error("Couldn't find a valid script to execute in %s\n",escape(raw)); p = raw + strlen(raw); strncpy(target,raw,MAXPATHLEN); target[MAXPATHLEN] = '\0'; } /* Everything to the right of the end of target is additional path info */ additional_length = strlen(raw) - strlen(target); if (!(*additional = (char*) calloc(sizeof(char),additional_length+1))) fatal_error("Unable to allocate memory for additional path info.\n"); strncpy(*additional,raw+strlen(target),additional_length); (*additional)[additional_length] = '\0'; /* turn the directory part of the target into a real directory, resolving symbolic paths */ strncpy(directory,target,dir-raw); directory[dir-raw]='\0'; to_abs(directory); max = strlen(directory)+(p-dir)+1; if (!(path = (char*)calloc(sizeof(char),max))) fatal_error("unable to allocate memory during calloc() of physical path: %s\n",strerror(errno)); strncpy(path,directory,max); strncat(path,dir,p-dir); path[max-1] = '\0'; if (raw != NULL) free((void*)raw); return path; } /* implement a variety of checks on the script before executing it */ void check_target(const char* newroot, const char* target, const struct stat *file_stats, const struct stat *dir_stats) { struct passwd *pass; struct group *grp; #if !defined(DEBUG) /* 1) script must not be SUID or SGID*/ if (file_stats->st_mode & S_ISUID) fatal_error("cannot run suid scripts (%s)\n",escape(target)); if (file_stats->st_mode & S_ISGID) fatal_error("cannot run sgid scripts (%s)\n",escape(target)); /* 2) script must be executable by other */ if (!( (file_stats->st_mode & S_IXOTH))) fatal_error("%s not world executable\n",escape(target)); /* 3) script is not owned by WEB_USER or WEB_GROUP */ if ((pass = getpwuid(file_stats->st_uid)) == NULL) fatal_error("%s is owned by an unknown user (%ld)\n",escape(target),file_stats->st_uid); #if !defined(ALLOW_WEB_OWNED_SCRIPTS) if (!(strcmp(pass->pw_name,WEB_USER))) fatal_error("%s is owned by the Web user (%s)\n",escape(target),WEB_USER); #endif if ((grp = getgrgid(file_stats->st_gid)) == NULL) fatal_error("%s is owned by an unknown group (%ld)\n",escape(target),file_stats->st_gid); #if !defined(ALLOW_WEB_OWNED_SCRIPTS) if (!(strcmp(grp->gr_name,WEB_GROUP))) fatal_error("%s is owned by the Web group (%s)\n",escape(target),WEB_GROUP); #endif /* 4) directory is not owned by WEB_USER or WEB_GROUP */ if ((pass = getpwuid(dir_stats->st_uid)) == NULL) fatal_error("the directory containing %s is owned by an unknown user (%ld)\n", escape(target),dir_stats->st_uid); #if !defined(ALLOW_WEB_OWNED_SCRIPTS) if (!(strcmp(pass->pw_name,WEB_USER))) fatal_error("the directory containing %s is owned by the Web user (%s)\n",escape(target),WEB_USER); #endif if ((grp = getgrgid(dir_stats->st_gid)) == NULL) fatal_error("the directory containing %s is owned by an unknown group (%ld)\n", escape(target),dir_stats->st_gid); #if !defined(ALLOW_WEB_OWNED_SCRIPTS) if (!(strcmp(grp->gr_name,WEB_GROUP))) fatal_error("the directory containing %s is owned by the Web group (%s)\n",escape(target),WEB_GROUP); #endif /* 5) Neither file nor the directory are writable by other */ if (file_stats->st_mode & S_IWOTH) fatal_error("%s is world writable\n",escape(target)); if (dir_stats->st_mode & S_IWOTH) fatal_error("the directory containing %s is world writable\n",escape(target)); #if DO_CHROOT /* 6) target must be located within the new root */ if (strstr(target,newroot) != target) fatal_error("%s is not contained within the chroot directory %s\n",escape(target),newroot); #endif /* 7) owner and group must not be less than UID_MIN, GID_MIN */ #if DO_SUID #if SID_MODE == DIRECTORY if (dir_stats->st_uid < UID_MIN) fatal_error("the directory containing %s must not be owned by a UID less than %d\n",escape(target),UID_MIN); #else if (file_stats->st_uid < UID_MIN) fatal_error("the file containing %s must not be owned by a UID less than %d\n",escape(target),UID_MIN); #endif #endif #if DO_SGID #if SID_MODE == DIRECTORY if (dir_stats->st_gid < GID_MIN) fatal_error("the directory containing %s must not be owned by a GID less than %d\n",escape(target),GID_MIN); #else if (file_stats->st_gid < GID_MIN) fatal_error("the file containing %s must not be owned by a GID less than %d\n",escape(target),GID_MIN); #endif #endif /* 8) owner and group must not be greater than UID_MAX, GID_MAX */ #if DO_SUID #if SID_MODE == DIRECTORY if (dir_stats->st_uid > UID_MAX) fatal_error("the directory containing %s must not be owned by a UID greater than %d\n",escape(target),UID_MAX); #else if (file_stats->st_uid > UID_MAX) fatal_error("the file containing %s must not be owned by a UID greater than %d\n",escape(target),UID_MAX); #endif #endif #if DO_SGID #if SID_MODE == DIRECTORY if (dir_stats->st_gid > GID_MAX) fatal_error("the directory containing %s must not be owned by a GID greater than %d\n",escape(target),GID_MAX); #else if (file_stats->st_gid > GID_MAX) fatal_error("the file containing %s must not be owned by a GID greater than %d\n",escape(target),GID_MAX); #endif #endif #endif } char* fetch_newroot(char* docroot) { char newd[MAXPATHLEN+1],*newroot; int max; max = strlen(docroot) + 1 + strlen(ROOT); if ( max > MAXPATHLEN) fatal_error("document root is too large: \"%s\"",docroot); strncpy(newd,docroot,max); strncat(newd,"/",1); strncat(newd,ROOT,strlen(ROOT)); /* tack on the new root component */ newd[MAXPATHLEN] = '\0'; if ((newroot = strdup(to_abs(newd))) == NULL) fatal_error("unable to allocate memory while making copy of new root directory path: %s\n", strerror(errno)); return newroot; } char* shave(char* newroot, char* target) { char* shaved = target; char* h = newroot; if (!newroot) return target; if (!target) return ""; while (*shaved && *h) { if (*shaved++ != *h++) break; } if (*h) return "/"; return shaved; } /* modify the environment in the following ways: * DOCUMENT_ROOT => shave(DOCUMENT_ROOT) * PATH_INFO => path_info * PATH_TRANSLATED => "DOCUMENT_ROOT/path_info" * SCRIPT_FILENAME => shave(target) * SCRIPT_NAME => "$SCRIPT_NAME/shave(target)" */ static void tweak_environment(char* newroot, char* root, char* target, char* additional_info) { char *s,*t,*path_info,*script_name; int r,max; /* the SCRIPT_NAME needs to be the URL that we invoke to get at the script again. */ path_info = (char*) getenv("PATH_INFO"); script_name = (char*) getenv("SCRIPT_NAME"); if (script_name == NULL) fatal_error("expect SCRIPT_NAME environment variable to be set, but null found\n"); /* set the script name -- it should be existing SCRIPT_NAME concatenated to the path info, less the additional info. SCRIPT_NAME can be used to reinvoke the script in virtual name space*/ max = strlen(script_name) + strlen(path_info) - strlen(additional_info) + 1; s = (char*) calloc(sizeof(char),max); if (s == NULL) fatal_error("failed to allocate memory for SCRIPT_NAME: %s\n",strerror(errno)); strncpy(s,script_name,max); strncat(s,path_info,strlen(path_info)-strlen(additional_info)); s[max-1] = '\0'; r = set_env("SCRIPT_NAME",s,1); if (r < 0) fatal_error("no room for SCRIPT_NAME environment variable"); free((void*)s); if (*additional_info) { /* set the path info */ r = set_env("PATH_INFO",additional_info,1); if (r < 0) fatal_error("no room for PATH_INFO environment variable"); t = shave(newroot,root); max = strlen(t)+strlen(additional_info)+1; if (!(s = (char*) calloc(sizeof(char),max))) fatal_error("unable to allocate string for path translated: %s\n",strerror(errno)); /* set the path translated */ strncpy(s,t,max); if (t[strlen(t)-1] == '/') strncat(s,additional_info+1,strlen(additional_info)-1); else strncat(s,additional_info,strlen(additional_info)); s[max-1] = '\0'; r = set_env("PATH_TRANSLATED",s,1); if (r < 0) fatal_error("no room for PATH_TRANSLATED environment variable"); free((void*)s); } /* Shave the chroot directory off the target. Will error out if the target is not contained within the new root. */ s = shave(newroot,target); r = set_env("SCRIPT_FILENAME",s,1); if (r < 0) fatal_error("no room for SCRIPT_FILENAME environment variable"); s = shave(newroot,root); r = set_env("DOCUMENT_ROOT",s,1); if (r < 0) fatal_error("no room for DOCUMENT_ROOT environment variable"); } /* set_env() is a replacement for the BSD setenv() function. */ static int set_env(const char *name, const char *value, int overwrite) { char **ep,**var,*d; /* initialize cleanenv global if necessary */ if (cleanenv == NULL) { if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL) return -1; } /* search for the string in the existing environment */ ep = cleanenv; while (((var = ep++) != NULL) && *var) { d = (char*) strchr(*var,'='); /* look for the "=" sign */ if (!d) continue; /* malformed entry */ if ((int)strlen(name) != abs(d-*var)) continue; if (0 != strncmp(*var,name,d-*var)) /* compare to target string */ continue; /* if we get here, we found the environment variable */ if (!overwrite) return 0; /* not allowed to overwrite the variable */ /* clear out the previous value */ free((void*) *var); *var = NULL; } /* when we get here var points to the place in the environment string for the new value */ /* First make sure we haven't run off the end of the buffer. Must be a terminal NULL in the array */ if (var - cleanenv >= AP_ENVBUF - 1) return -1; if ( (*var = (char*)calloc(strlen(name)+1+strlen(value)+1,sizeof(char))) == NULL) return -1; /* out of space */ /* copy */ if (sprintf(*var,"%s=%s",name,value) <= 0) return -1; /* don't know when this would happen */ return 0; } /* clean_env() is derived from similar routine in suexec.c, part of the Apache distribution */ void clean_env() { char pathbuf[NAME_MAX]; char **ep; int cidx = 0; int idx; /* initialize cleanenv global if necessary */ if (cleanenv == NULL) { if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL) fatal_error("failed to malloc env mem\n"); } /* position to first NULL entry in cleanenv */ for (cidx = 0; cleanenv[cidx] && cidx < AP_ENVBUF; cidx++) ; /* copy the environment */ for (ep = environ; *ep && cidx < AP_ENVBUF; ep++) { if (!strncmp(*ep, "HTTP_", 5)) { cleanenv[cidx] = *ep; cidx++; } else { for (idx = 0; safe_env_lst[idx]; idx++) { if (!strncmp(*ep, safe_env_lst[idx], strlen(safe_env_lst[idx]))) { cleanenv[cidx] = *ep; cidx++; break; } } } } if (strlen(SAFE_PATH)+strlen("PATH=")+1 > NAME_MAX) fatal_error("value of SAFE_PATH (%s) is too large (max %d bytes)\n",escape(SAFE_PATH),NAME_MAX); sprintf(pathbuf, "PATH=%s", SAFE_PATH); cleanenv[cidx] = strdup(pathbuf); cleanenv[++cidx] = NULL; } char* escape (const char* str) { char *escaped,*s,c; int count = 0; if (str == NULL) return NULL; #if ECHO_FAILURES s = (char*) str; count = strlen(str); while (c = *s++) { if (c == '<' || c == '>') { count += 4; } else if (c == '&') { count += 5; } } escaped = (char*) calloc(sizeof(char),count+1); s = escaped; while (c = *str++) { if (c == '<') { strcat(s,"<"); s+=4; } else if (c == '>') { strcat(s,">"); s+=4; } else if (c== '&') { strcat(s,"&"); s+=5; } else { *s++ = c; } } return escaped; #else return (char*) str; #endif } /* chdir() to the directory where CGI script is located so that most e.g. Perl scripts that use relative paths work. the function gets the the full path to the chroot() directory (newroot) and full path (target) to the CGI script and extracts the correct subdirectory where the script resides on and does chdir() there. */ static void chdir_fix(char* newroot, char* target) { char *chdir_path; int i,j; int start=0; int end=0; chdir_path = (char*) calloc(sizeof(char),MAXPATHLEN); if (chdir_path == NULL) fatal_error("failed to allocate memory for chdir path: %s\n",strerror(errno)); for (i=0; target[i]!='\0' && newroot[i]!='\0'; i++) { if (target[i] == newroot[i]) start++; else continue; } for (i=0; target[i]!='\0'; i++) if (target[i] == '/') end=i; j = 0; if (start>0 && end>0 && start