Hacking Linux Exposed

About
Authors
Contents
Reviews
Foreword
Purchase

Articles
Books
Sourcecode
Tools
Errata

Home

 


(view this code in a separate window)


/*
 * dropprivs snippet
 *
 * Example C code to drop root privileges.
 *
 * Copyright 2002, Bri Hatch
 *
 * Released under the GPL.  See COPYING file
 * for more information.
 *
 */


#define bail(s) { perror(s); exit(1); }




  /* Here's the priv-dropping code. */
  /* Insert into your code where    */
  /* appropriate.                   */

  uid_t uid_cur = getuid();
  gid_t gid_cur = getgid();
  
  if ( setgid(gid_cur) < 0)
	  bail("setgid");
  if ( setuid(uid_cur) <0 )
	  bail("setuid");
  execl(" /path/to/program" ...)
	  bail("execl failed")