progs/read.c
author cu
Sun, 15 Oct 2017 21:23:16 +0100
changeset 550 58c3536c5a08
parent 365 942205605c30
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;
}