目錄表

Process Environment

0x00 Outline

0x01 Process start and termination

Process Start

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

Process Termination

atexit and exit Function

int atexit(void (*function)(void));
void exit(int status);
/* atexit example */
#include <stdio.h>      /* puts */
#include <stdlib.h>     /* atexit */
 
void fnExit1 (void)
{
  puts ("Exit function 1.");
}
 
void fnExit2 (void)
{
  puts ("Exit function 2.");
}
 
int main ()
{
  atexit (fnExit1);
  atexit (fnExit2);
  puts ("Main function.");
  return 0;
}
 
/*
result:
Main function.
Exit function 2.
Exit function 1.
*/

0x02 Environment Variables

Environment Variables

Environment List

extern char **environ;
int main(int argc, char *argv[])
{
  int count = 0;
 
  printf("\n");
  while(environ[count] != NULL)
  {
    printf("[%s] :: ", environ[count]);
    count++;
  }
  return 0;
}

Environment Function

#include <stdlib.h>
 
char *getenv(const char *name);
int putenv(char *string);
int setenv(const char *name, const char *value, int overwrite);
int unsetenv(const char *name);
int clearenv(void);

Environment List Operations


0x03 Memory layout


0x04 Shared libraries

shared libraries

Library Injection

//getuid.c
 
int main()
{
  printf("UID = %d\n", getuid());
  return 0;
}
//injected library, inject1.c
 
#include <stdio.h>
#include <sys/types.h>
 
uid_t getuid(void)
{
  fprintf(stderr, "injected getuid, always return 0\n");
  return 0;
}

More on Library Inject

#include <dlfcn.h>
 
void *dlopen(const char *filename, int flag);
char *dlerror(void);
void *dlsym(void *handle, const char *symbol);
int dlclose(void *handle);
/*
inject2.c
gcc -o inject2.so -shared -fPIC inject2.c -ldl
*/
 
static uid_t (*old_getuid)(void) = NULL; /* function pointer */
uid_t getuid(void)
{
  if(old_getuid == NULL)
  {
    void *handle = dlopen("libc.so.6", RTLD_LAZY);
 
    if(handle != NULL)
      old_getuid = dlsym(handle, "getuid");
  }
 
  fprintf(stderr, "injected getuid, always return 0\n");
 
  if(old_getuid != NULL)
    fprintf(stderr, "real uid = %d\n", old_getuid());
 
  return 0;
}

Determine Library Injection Possibility


0x05 Memory allocation

memory allocation functions

#include <stdlib.h>
 
void *malloc(size_t size);
void free(void *ptr);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
 
#include <alloca.h>
 
void *alloca(size_t size);

0x06 Setjmp and longjmp

setjmp and longjmp Function

int setjmp(jmp_buf env);
void longjmp(jmp_buf env, int val);

Restoration of Variables


0x07 Process resource limits

Process resource limits

getrlimit and setrlimit Function

#include <sys/time.h>
#include <sys/resource.h>
 
int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);
 
struct rlimit
{
    rlim_t rlim_cur;  /* Soft limit */
    rlim_t rlim_max;  /* Hard limit (ceiling for rlim_cur) */
};

0x08 參考資料