#define _CRT_SECURE_NO_DEPRECATE #include #include #include #define USERPASS "pentest:midterm" // VS2005: cl /GS- /MD htpasswd.c // gcc: rename _snprintf -> snprintf int verbose = 0; static char authbuf[512]; static int authenticated = 0; int authenticate(char *username, char *password){ _snprintf(authbuf, sizeof(authbuf)+1, "%s:%s", username, password); if (!authenticated) { // If the user is not already authenticated, try and authenticate them now authenticated = !strncmp(authbuf, USERPASS, strlen(USERPASS)); } return authenticated; } void debugprint(char* str) { char debugbuf[522]; _snprintf(debugbuf, strlen(str)+10, "DEBUG: %s\n", str); fprintf(stderr, debugbuf); } void debug(char *username, char *password) { char pass[512]; char user[512]; strncpy(user, username, sizeof(user)); strncpy(pass, password, sizeof(pass)); debugprint(user); debugprint(pass); } void update_file(char *new, char *outfile) { char s_buffer[512]; unsigned char f; f = strlen(new); if(f > sizeof(s_buffer)-10){ fprintf(stderr, "new username too long!\n"); exit(1); } strcpy(s_buffer, new); fprintf(stdout, "Username: %s added to %s!\n", s_buffer, outfile); } void usage(void) { fprintf(stderr,"Usage: adduser [options]\n"); fprintf(stderr,"Options\n"); fprintf(stderr," -v verbose\n"); fprintf(stderr," -u Your username\n"); fprintf(stderr," -p Your password\n"); fprintf(stderr," -f htpasswd file to update\n"); fprintf(stderr," -n New username to add to htpasswd file\n"); exit (8); } int main(int argc, char *argv[]) { char *username = NULL, *password = NULL, *outfile = NULL, *newuser = NULL; __asm int 3 /* loop for each option. * Stop if we run out of arguments * or we get an argument without a dash. */ while ((argc > 1) && (argv[1][0] == '-')) { /* argv[1][1] is the actual option character. */ switch (argv[1][1]) { case 'v': verbose = 1; printf("DEBUG: verbose set\n"); break; /* -f output file * [0] is the dash * [1] is the "f" * [2] starts the name */ case 'f': outfile = &argv[1][2]; break; case 'u': username = &argv[1][2]; break; case 'p': password = &argv[1][2]; break; case 'n': newuser = &argv[1][2]; break; default: fprintf(stderr,"Bad option %s\n", argv[1]); usage(); } /* move the argument list up one * move the count down one */ ++argv; --argc; } if (!username || !password || !outfile || !newuser) { usage(); } if(verbose) debug(username, password); if(authenticate(username, password)) { fprintf(stdout, "You correctly authenticated!\nAdding new user to %s...\n", outfile); update_file(newuser, outfile); } return 0; }