#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* PACISE26 CTF - Format String Leak
 * The flag is loaded onto the stack. Use a format string vulnerability
 * to read it out of memory.
 */

void vuln() {
    char flag[64];
    char buf[128];

    FILE *f = fopen("flag.txt", "r");
    if (!f) { puts("flag.txt missing"); exit(1); }
    fgets(flag, sizeof(flag), f);
    fclose(f);

    /* strip newline */
    flag[strcspn(flag, "\n")] = '\0';

    printf("=== PACISE26 CTF - Format String Leak ===\n");
    printf("I loaded a secret onto my stack...\n");
    printf("Can you leak it?\n\n");
    printf("Enter your format string: ");
    fflush(stdout);

    if (!fgets(buf, sizeof(buf), stdin)) return;
    buf[strcspn(buf, "\n")] = '\0';

    printf("Result: ");
    printf(buf);          /* <-- format string vulnerability */
    printf("\n");
    fflush(stdout);
}

int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stdin,  NULL, _IONBF, 0);
    vuln();
    return 0;
}
