Created
July 1, 2023 18:30
-
-
Save libcrack/4b9756dc369380a9520f7132b2deae1a to your computer and use it in GitHub Desktop.
Execute shellcode from file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Exec shellcode from file (no need of -z execstack) | |
| * gcc ./shellcode_from_file.c -o ./shellcode_from_file | |
| * | |
| * Sat Jul 1 20:21:12 CEST 2023 | |
| * devnull@libcrack.so | |
| * | |
| * 1. Create a payload: | |
| * msfvenom -p osx/x64/exec CMD=/bin/sh -f raw -o osx-exec.raw | |
| * | |
| * 2. Execute it | |
| * $ ./shellcode_from_file osx-exec.raw | |
| * Reading payload from osx-exec.raw | |
| * File size is 31 | |
| * Length of shellcode: 31 | |
| * sh-3.2$ | |
| * | |
| */ | |
| #include <fcntl.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <sys/mman.h> | |
| #include <sys/types.h> | |
| #include <sys/uio.h> | |
| #include <unistd.h> | |
| #include <errno.h> | |
| int (*sc)(); | |
| int main(int argc, char **argv) { | |
| char *shellcode = NULL; | |
| char *filepath = NULL; | |
| short int fd; | |
| size_t offset; | |
| size_t size; | |
| ssize_t result; | |
| if (argc != 2){ | |
| printf("Usage: %s <payload file>\n", argv[0]); | |
| exit(EXIT_FAILURE); | |
| } | |
| filepath = argv[1]; | |
| if ((fd = open(filepath, O_RDONLY)) < 0){ | |
| perror("open() failed"); | |
| exit(EXIT_FAILURE); | |
| } | |
| printf("Reading payload from %s\n", filepath); | |
| if ( (offset = lseek(fd, 0, SEEK_END)) == -1 ){ | |
| perror("lseek() failed"); | |
| close(fd); | |
| exit(EXIT_FAILURE); | |
| } | |
| printf("File size is %ld\n", offset); | |
| if ( (shellcode = malloc(offset)) == NULL){ | |
| perror("malloc() failed"); | |
| close(fd); | |
| exit(EXIT_FAILURE); | |
| } | |
| if (lseek(fd, 0, SEEK_SET) != 0){ | |
| perror("lseek() failed"); | |
| close(fd); | |
| exit(EXIT_FAILURE); | |
| } | |
| while ( (size = read(fd, shellcode, offset) > 0) ){ | |
| if (size < 0) { | |
| if ((EINTR == errno) || (EAGAIN == errno)) | |
| continue; | |
| perror("read() failed"); | |
| break; | |
| } | |
| } | |
| close(fd); | |
| printf("Length of shellcode: %li\n", offset); | |
| ptr = mmap(0, sizeof(shellcode), | |
| PROT_EXEC | PROT_WRITE | PROT_READ, | |
| MAP_ANON | MAP_PRIVATE, -1, 0); | |
| if (ptr == MAP_FAILED) { | |
| perror("mmap"); | |
| exit(-1); | |
| } | |
| memcpy(ptr, shellcode, offset); | |
| free(shellcode); | |
| sc = ptr; | |
| sc(); | |
| exit (EXIT_SUCCESS); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment