progs/read.c
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Tue, 30 Dec 2014 21:59:47 +0000
changeset 365 942205605c30
parent 364 e4a879d442d5
permissions -rw-r--r--
updated

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

FILE *f; //file pointer

//tests return errno = 13 for permission denied
void read_test(char *name) 
{
    if ((f = fopen(name, "r")) == NULL) {
      printf("%s is not readable, errno = %d\n", name, errno);
    } else {
      printf("%s is readable\n", name); fclose(f);
    }
}

void write_test(char *name) 
{
    if ((f = fopen(name, "r+")) == NULL) {
      printf("%s is not writable, errno = %d\n", name, errno);
    } else {
      printf("%s is writable\n", name); fclose(f);
    }
}

int main(int argc, char *argv[])
{   
    printf("Real UID = %d\n", getuid());
    printf("Effective UID = %d\n", geteuid());
    
    read_test(argv[1]);
    write_test(argv[1]);

    //lowering the access rights to the caller
    if (setuid(getuid())) {  
      printf("could not reset setuid, errno = %d\n", errno); 
      return 1;
    }
        
    printf("Real UID = %d\n", getuid());
    printf("Effective UID = %d\n", geteuid());      

    read_test(argv[1]);
    write_test(argv[1]);

    return 0;
}