Skip to content

Instantly share code, notes, and snippets.

@yellowbyte
Last active March 25, 2023 13:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save yellowbyte/ec470d75ba7c14ebefed271c6fe58e9e to your computer and use it in GitHub Desktop.
Save yellowbyte/ec470d75ba7c14ebefed271c6fe58e9e to your computer and use it in GitHub Desktop.
example of using dlopen and dlsym to dynamically resolve call to `puts`. String reference to `puts` is also obfuscated.
// how to compile: gcc dynamic_loading.c -o dynamic_loading -ldl
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <string.h>
int main(int argc, char **argv) {
void *handle;
void (*go)(char *);
// get a handle to the library that contains 'puts' function
handle = dlopen ("/lib/x86_64-linux-gnu/libc.so.6", RTLD_LAZY);
// each character in 'otsr' plus 1 in ascii is 'puts'
char *encoded = "otsr";
int encoded_length = strlen(encoded);
char *decoded = (char*)malloc((encoded_length+1) * sizeof(char));
for (int i = 0; i < encoded_length; i++){
decoded[i] = encoded[i]+1;
}
*decoded += '\0';
// reference to the dynamically-resolved function 'puts'
go = dlsym(handle, decoded);
go("hi"); // == puts("hi");
// cleanup
free(decoded);
dlclose(handle);
}
@michalliu
Copy link

Why not just dlsym(handle, "puts");??

@yellowbyte
Copy link
Author

It is to also obfuscate string reference to "puts". Otherwise, the string "puts" can easily be uncovered by the strings utility since it will simply be placed in the .data section of the executable binary.

@PandyYang
Copy link

PandyYang commented Nov 21, 2022

why can't i pass the paramter to cgo so file...

#cgo LDFLAGS: -ldl
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>

static void cmd_read(const char *c) {
    void (*fn)(char *);
	void *h;

	h = dlopen("./cgo_cmd.so", RTLD_LAZY);
    if (!h) {
        fprintf(stderr, "Error: %s\n", dlerror());
        return;
    }

    fn = dlsym(h, "ReadFromCMD");

    fn(c);
    dlclose(h);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment