Skip to content

Instantly share code, notes, and snippets.

@Mufanc
Created May 2, 2023 07:54
Show Gist options
  • Save Mufanc/dd360537ec3cc7b45dce66e5acb29393 to your computer and use it in GitHub Desktop.
Save Mufanc/dd360537ec3cc7b45dce66e5acb29393 to your computer and use it in GitHub Desktop.
// fd-perm $(id -u nobody)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/unistd.h>
#include <sys/wait.h>
int main(int, char *argv[]) {
int fd = open("1.txt", O_CREAT | O_RDWR, 0660);
if (fd == -1) {
perror("open");
return 1;
}
write(fd, "Hello World\n", 12);
if (fork()) {
printf("perent: %d\n", getpid());
wait(nullptr);
close(fd);
} else {
printf("child: %d\n", getpid());
setuid(strtol(argv[1], nullptr, 10));
int fd2 = open("1.txt", O_RDONLY);
if (fd2 == -1) {
perror("open");
printf("child process cannot open file by name.\n");
} else {
close(fd2);
}
char buffer[32] = {0};
lseek(fd, 0, SEEK_SET);
int n = read(fd, buffer, sizeof(buffer));
if (n == -1) {
perror("read");
} else {
printf("file content: %s\n", buffer);
}
close(fd);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment