Skip to content

Instantly share code, notes, and snippets.

@BZHugs
Last active June 12, 2018 13:55
Show Gist options
  • Save BZHugs/a7da6cf9b2c822660a3bd0bf39bbf83f to your computer and use it in GitHub Desktop.
Save BZHugs/a7da6cf9b2c822660a3bd0bf39bbf83f to your computer and use it in GitHub Desktop.
Example of code optimisation (remove libc)
root@laptop [02:00:10] [~/Documents/pentest/cours] 
-> # ls -alh opti printf-libc
-rwxr-xr-x 1 root root 1,5K juin  12 14:00 opti
-rwxr-xr-x 1 root root 726K juin  12 14:00 printf-libc

root@laptop [02:00:26] [~/Documents/pentest/cours] 
-> # ./opti arg1 arg2 arg3    
./opti
arg1
arg2
arg3

root@laptop [02:00:42] [~/Documents/pentest/cours] 
-> # ./printf-libc arg1 arg2 arg3
./printf-libc
arg1
arg2
arg3
/*
gcc opti.c -o opti -nostdlib -nostdinc -static -fno-asynchronous-unwind-tables -O1
ls -alh opti -> 1,5K
// strip --strip-all ./a.out // -> remove debug symbols (func name, etc) -> 928
*/
#define STDOUT 1
#define WRITE 1
#define EXIT 60
int main_perso(int argc, char *argv[]);
static inline long syscall1(long syscall, long arg1);
static inline long syscall3(long syscall, long arg1, long arg2, long arg3);
int write(int fd, char *str);
int print(char *str);
void exit(int status);
/*
void _start(){
int *argc = getArgcPtr();
int *argv = argc + 8;
int ret = main_perso(argc, argv);
exit(ret);
}
*/
asm(
".global _start\n"
"_start:\n"
" xorl %ebp,%ebp\n" // mark outermost stack frame
" movq 0(%rsp),%rdi\n" // get argc
" lea 8(%rsp),%rsi\n" // argv = %rbp + 8
" call main_perso\n" // call our main_perso
" movq %rax,%rdi\n" // take the main return code and use it as first argument for...
" call exit\n");
int main_perso(int argc, char *argv[]) {
for(int i = 0; i < argc; ++i) {
print(argv[i]);
print("\n");
}
return 0;
}
int slen(char *str){
int count = 0;
while(str[count++] != 0);
return count-1;
}
static inline long syscall1(long syscall, long arg1) {
long ret;
__asm__ __volatile__("syscall"
: "=a" (ret)
: "0" (syscall), "D" (arg1)
: "memory");
return ret;
}
static inline long syscall3(long syscall, long arg1, long arg2, long arg3) {
long ret;
__asm__ __volatile__("syscall"
: "=a" (ret)
: "0" (syscall), "D" (arg1), "S"(arg2), "d"(arg3)
: "cc", "rcx", "r11", "memory");
return ret;
}
int write(int fd, char *str){
return syscall3(WRITE, fd, (long)str, slen(str));
}
int print(char *str){
return write(STDOUT, str);
}
void exit(int status) {
syscall1(EXIT, status);
}
/*
gcc printf-libc.c -o printf-libc -static
ls -alh printf-libc -> 726K
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
for (int i = 0; i < argc; ++i)
{
printf("%s\n", argv[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment