progs/read.c
author Christian Urban <urbanc@in.tum.de>
Tue, 26 Sep 2017 12:47:25 +0100
changeset 538 456d1d6676f9
parent 365 942205605c30
permissions -rw-r--r--
update

#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;
}