Thread: C help
View Single Post
Old 05-14-07, 09:10 AM   #12
evilghost
Registered User
 
Join Date: Jul 2005
Posts: 3,606
Default Re: C help

Code:
/* evilghost
 * Thanks wnd for code snippets & help.
 * May 10, 2007
 * SETUID binary to fix permissions with uploaded images if they are invalid.
 * Permissions on compiled binary must be 4770 with uid/gid root:www-data
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#define wwwdata_UID 33
#define shared_GID 5140
#define BASEPATH "/www/dlf/dlf-albums/"

int main(int argc, char **argv){

        FILE *fout;
        time_t curtime;
        struct tm *loctime;
        char t[80];
        t[79] = '\0';
        struct stat s;
        int r;

        //Check initial input.
        if (argc != 2 || argv[1] == NULL || strncmp(argv[1], BASEPATH, strlen(BASEPATH)) != 0 || strstr(argv[1], "/..") != NULL) {
                fprintf(stderr,"Failed:  Invalid file path passed.\n");
                return EXIT_FAILURE;
        }

        //Check for possible abnormal behavior (excessively long parameter)
        if (strlen(argv[1]) > 255){
                fprintf(stderr,"Failed:  Extraordinarily long file path passed, ignoring.\n");
                return EXIT_FAILURE;
        }

        //Check if file exists and adjust permissions
        if (access(argv[1],R_OK) == 0){
                //Check if it's a regular file.
                r = lstat(argv[1], &s);
                if (r != 0){
                        fprintf(stderr,"Failed: Unable to stat file path\n");
                        return EXIT_FAILURE;
                }

                if (! (S_ISREG(s.st_mode))){
                        fprintf(stderr,"Failed:  File path is not a regular file\n");
                        return EXIT_FAILURE;
                }

                // Get the current time & convert to local.
                curtime = time (NULL);
                loctime = localtime (&curtime);
                strftime(t, 79, "%T %D", loctime);

                //Write audit trail.
                fout = fopen ("/www/dlf/fixperms.log", "a+");
                if (fout != NULL){
                        fprintf(fout, "%s\t%s\n", t, argv[1]);
                        fclose(fout);
                }else{
                        fprintf(stderr,"Failed:  Error while opening audit log for writing\n");
                        return EXIT_FAILURE;
                }

                //Adjust file permissions
                chown(argv[1], wwwdata_UID, shared_GID);
                chmod(argv[1], 0770);

                fprintf(stderr,"Success\n");
                return EXIT_SUCCESS;
        }else{
                fprintf(stderr,"Failed:  File path specified does not exist, no action performed.\n");
                return EXIT_FAILURE;
        }
}
evilghost is offline   Reply With Quote