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

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

int main(int argc, char *argv[])
{   
    FILE *f; //file pointer

    printf("Real UID = %d\n", getuid());
    printf("Effective UID = %d\n", geteuid());
    
    //read test (error 13 is permission denied)
    if ((f = fopen(argv[1], "r")) == NULL) {
      fprintf(stderr, "%s is not readable, errno = %d\n", argv[1], errno);
    } else {
      fprintf(stderr, "%s is readable\n", argv[1]); fclose(f);
    }

    //write test
    if ((f = fopen(argv[1], "r+")) == NULL) {
      fprintf(stderr, "%s is not writable, errno = %d\n", argv[1], errno);
    } else {
      fprintf(stderr, "%s is writable\n", argv[1]); fclose(f);
    }

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

    //read test
    if ((f = fopen(argv[1], "r")) == NULL) {
      fprintf(stderr, "%s is not readable, errno = %d\n", argv[1], errno);
    } else {
      fprintf(stderr, "%s is readable\n", argv[1]); fclose(f);
    }

    //write test
    if ((f = fopen(argv[1], "w")) == NULL) {
      fprintf(stderr, "%s is not writable, errno = %d\n", argv[1], errno);
    } else {
      fprintf(stderr, "%s is writable\n", argv[1]); fclose(f);
    }

    return 0;
}