scripts

misc scripts and tools
git clone git://git.2f30.org/scripts.git
Log | Files | Refs

mindblow.c (1417B)


      1 #include <sys/stat.h>
      2 #include <sys/mman.h>
      3 #include <fcntl.h>
      4 #include <unistd.h>
      5 #include <errno.h>
      6 #include <stdarg.h>
      7 #include <stdio.h>
      8 #include <stdlib.h>
      9 #include <string.h>
     10 
     11 static void
     12 die(const char *s)
     13 {
     14 	fprintf(stderr, "%s: %s\n", s, strerror(errno));
     15 	exit(EXIT_FAILURE);
     16 }
     17 
     18 int
     19 main(int argc, char *argv[])
     20 {
     21 	int pflag, eflag;
     22 	int fd;
     23 	int c;
     24 	unsigned char *base;
     25 	struct stat buf;
     26 	off_t i;
     27 	int flag;
     28 	int (*fn)(void);
     29 
     30 	pflag = eflag = 0;
     31 	while ((c = getopt(argc, argv, "pe")) != -1) {
     32 		switch (c) {
     33 		case 'p':
     34 			pflag = 1;
     35 			break;
     36 		case 'e':
     37 			eflag = 1;
     38 			break;
     39 		default:
     40 			return EXIT_FAILURE;
     41 		}
     42 	}
     43 
     44 	if (argc - optind != 1) {
     45 		fprintf(stderr, "usage: %s [-pe] bin\n", *argv);
     46 		return EXIT_FAILURE;
     47 	}
     48 
     49 	fd = open(argv[optind], O_RDONLY);
     50 	if (fd < 0)
     51 		die("open");
     52 
     53 	if (fstat(fd, &buf) < 0)
     54 		die("fstat");
     55 
     56 	base = mmap(0, buf.st_size, PROT_EXEC | PROT_READ,
     57 		    MAP_PRIVATE, fd, 0);
     58 	if (base == MAP_FAILED)
     59 		die("mmap");
     60 
     61 	flag = 0;
     62 	setbuf(stdout, NULL);
     63 	if (pflag) {
     64 		printf("char shellcode[] = \n\t\"");
     65 		for (i = 0; i < buf.st_size; ++i) {
     66 			if (i && !(i % 8)) {
     67 				printf("\"\n");
     68 				flag = 1;
     69 			}
     70 			if (flag) {
     71 				printf("\t\"");
     72 				flag = 0;
     73 			}
     74 			printf("\\x%02x", base[i]);
     75 		}
     76 		printf("\";\n");
     77 	}
     78 
     79 	if (eflag) {
     80 		fn = (int (*)(void))base;
     81 		fn();
     82 	}
     83 
     84 	if (munmap(base, buf.st_size) < 0)
     85 		die("munmap");
     86 
     87 	close(fd);
     88 
     89 	return EXIT_SUCCESS;
     90 }
     91