/*
 * Simple program prints the effective and real user ids associated 
 * with a process.  It tries to set the effective process id to an 
 * arbitrary uid.  
 *
 * You can experiment with this simple program by setting the owner and
 * setuid bits (chmod u+s testsuid).  Make one suid and owned by non
 * privileged owner.  Make one suid and owned by root.  Invoke each by
 * privieleged and non-priveleged users.  If you are feeling really 
 * ambitious work with the linux capabilities that enable the set uid
 * privilege
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>

main()
{
    uid_t real_id = getuid();
    uid_t eff_id = geteuid();
    uid_t target_id = 503;

    printf("Real uid %d, Effective uid %d\n", real_id, eff_id);

    printf("Attempt to set effecitve uid to %d\n", target_id);
    if (setresuid(real_id, target_id, real_id) < 0) {
         perror("Setting effective uid failed");
         printf("Revert effective to real id and try again\n");
         if (setresuid(real_id, real_id, real_id) < 0) {
             perror("Could not set effective to real id");
         }
         else {
             if (setresuid(real_id, target_id, real_id) < 0) {
                 perror("Could not set effective id after reverting to real id");
             }
             else {
                 printf("Succeeded finally in setting effective id to %d\n", target_id);
             }
         }
    }
    else {
        printf("Setting effective uid succeeded\n");
    }
    exit(0);
}