Skip to content

Instantly share code, notes, and snippets.

@danielhenrymantilla
Created July 30, 2018 12:41
Show Gist options
  • Save danielhenrymantilla/127c123639e46b42ced747e73a7e8135 to your computer and use it in GitHub Desktop.
Save danielhenrymantilla/127c123639e46b42ced747e73a7e8135 to your computer and use it in GitHub Desktop.
Hexdump tool to "copy-paste" binaries into a shell. Useful for root-me.org VM challenges.
/* Hexdump tool to "copy-paste" binaries into a shell.
* Useful for root-me.org VM challenges.
* Compile with:
* $ cc -std=c99 -o slice slice.c
*
* By Yandros (https://www.root-me.org/Yandros)
*/
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define DEFAULT_BUFSIZE 200
#define NAME argv[1]
#define PREFIX "printf \""
#define SUFFIX "\" >> %s\n", NAME
#define failwith(s) \
do { close(fd); perror(s); exit(EXIT_FAILURE); } while(0)
int main(int argc, char * argv[]) {
if (argc != 2 && argc != 3) {
fprintf(stderr, "Usage:\t%s filename [bufsize]\n", argv[0]);
exit(EXIT_FAILURE);
}
size_t bufsize =
argc == 3 ?
atoi(argv[2]) :
DEFAULT_BUFSIZE;
fprintf(stderr, "Dumping '%s'...\n", argv[1]);
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
struct stat file_stat;
if (fstat(fd, &file_stat) == -1)
failwith("fstat");
fprintf(stderr, "Length = %ld bytes.\n", file_stat.st_size);
uintptr_t addr = (uintptr_t) mmap(NULL, file_stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if ((void *)addr == MAP_FAILED)
failwith("mmap");
printf("touch %s\n", NAME);
printf("chmod +x %s\n", NAME);
int len;
for(len = file_stat.st_size; len > 0; len -= bufsize) {
size_t size = (len > bufsize ? bufsize : len);
printf(PREFIX);
for (size_t i = 0; i < size; ++i) {
printf("\\x%02x", ((char *) addr)[i] & 0xff);
}
printf(SUFFIX);
addr += bufsize;
}
printf("./%s\n", NAME);
if (munmap((void *)(addr + len - file_stat.st_size), file_stat.st_size) == -1)
failwith("munmap");
close(fd);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment