1 /* 2 ** This program checks to see if your version of setuid works. 3 ** Compile it, make it setuid root, and run it as yourself (NOT as 4 ** root). 5 ** 6 ** NOTE: This should work everywhere, but Linux has the ability 7 ** to use the undocumented setcap() call to make this break. 8 ** 9 ** Compilation is trivial -- just "cc t_setuid.c". Make it setuid, 10 ** root and then execute it as a non-root user. 11 */ 12 13 #include <sys/types.h> 14 #include <unistd.h> 15 #include <stdio.h> 16 17 #ifndef lint 18 static char id[] = "@(#)$Id: t_setuid.c,v 8.2.2.1 2000/05/31 00:29:47 gshapiro Exp $"; 19 #endif /* ! lint */ 20 21 static void 22 printuids(str, r, e) 23 char *str; 24 int r, e; 25 { 26 printf("%s (should be %d/%d): r/euid=%d/%d\n", str, r, e, 27 getuid(), geteuid()); 28 } 29 30 int 31 main(argc, argv) 32 int argc; 33 char **argv; 34 { 35 int fail = 0; 36 uid_t realuid = getuid(); 37 38 printuids("initial uids", realuid, 0); 39 40 if (geteuid() != 0) 41 { 42 printf("SETUP ERROR: re-run setuid root\n"); 43 exit(1); 44 } 45 46 if (getuid() == 0) 47 { 48 printf("SETUP ERROR: must be run by a non-root user\n"); 49 exit(1); 50 } 51 52 if (setuid(1) < 0) 53 printf("setuid(1) failure\n"); 54 printuids("after setuid(1)", 1, 1); 55 56 if (geteuid() != 1) 57 { 58 fail++; 59 printf("MAYDAY! Wrong effective uid\n"); 60 } 61 62 if (getuid() != 1) 63 { 64 fail++; 65 printf("MAYDAY! Wrong real uid\n"); 66 } 67 68 69 /* do activity here */ 70 if (setuid(0) == 0) 71 { 72 fail++; 73 printf("MAYDAY! setuid(0) succeeded (should have failed)\n"); 74 } 75 else 76 { 77 printf("setuid(0) failed (this is correct)\n"); 78 } 79 printuids("after setuid(0)", 1, 1); 80 81 if (geteuid() != 1) 82 { 83 fail++; 84 printf("MAYDAY! Wrong effective uid\n"); 85 } 86 if (getuid() != 1) 87 { 88 fail++; 89 printf("MAYDAY! Wrong real uid\n"); 90 } 91 printf("\n"); 92 93 if (fail) 94 { 95 printf("\nThis system cannot use setuid (maybe use setreuid)\n"); 96 exit(1); 97 } 98 99 printf("\nIt is safe to use setuid on this system\n"); 100 exit(0); 101 } 102