home *** CD-ROM | disk | FTP | other *** search
/ Chip 1995 March / CHIP3.mdf / slackwar / a / util / util-lin.10 / util-lin / util-linux-1.10 / newgrp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-02-09  |  2.0 KB  |  95 lines

  1. /* setgrp.c - by Michael Haardt. Set the gid if possible */
  2. /* Added a bit more error recovery/reporting - poe */
  3. /* Vesa Roukonen added code for asking password */
  4.  
  5. #include <unistd.h>
  6. #include <pwd.h>
  7. #include <grp.h>
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <errno.h>
  11. #include "pathnames.h"
  12.  
  13. #ifndef TRUE
  14. # define TRUE 1
  15. #endif
  16.  
  17. #ifndef FALSE
  18. # define FALSE 0
  19. #endif
  20.  
  21. static int
  22. allow_setgid(struct passwd *pe, struct group *ge) 
  23. {
  24.     char **look;
  25.     int notfound = 1;
  26.     
  27.     if (getuid() == 0) return TRUE;    /* root may do anything */
  28.  
  29.     look = ge->gr_mem;
  30.     while (*look && (notfound = strcmp(*look++,pe->pw_name)));
  31.  
  32.     if(!notfound) return TRUE;        /* member of group => OK */
  33.  
  34.     /* Ask for password. Often there is no password in /etc/group, so
  35.        contrary to login et al. we let an empty password mean the same
  36.        as * in /etc/passwd */
  37.  
  38.     if(ge->gr_passwd && ge->gr_passwd[0] != 0) {
  39.     if(strcmp(ge->gr_passwd, 
  40.           crypt(getpass("Password: "), ge->gr_passwd)) == 0) {
  41.         return TRUE;        /* password accepted */
  42.     }
  43.     }
  44.  
  45.     return FALSE;            /* default to denial */
  46. }
  47.  
  48. int 
  49. main(int argc, char *argv[])
  50. {
  51.     struct passwd *pw_entry;
  52.     struct group *gr_entry;
  53.     char *shell;
  54.     
  55.     if (!(pw_entry = getpwuid(getuid()))) {
  56.     perror("newgrp: Who are you?");
  57.     exit(1);
  58.     }
  59.     
  60.     shell = (pw_entry->pw_shell[0] ? pw_entry->pw_shell : _PATH_BSHELL);
  61.     
  62.     if (argc < 2) {
  63.     if(setgid(pw_entry->pw_gid) < 0) {
  64.         perror("newgrp: setgid");
  65.         exit(1);
  66.     }
  67.     } else {
  68.     if (!(gr_entry = getgrnam(argv[1]))) {
  69.         perror("newgrp: No such group.");
  70.         exit(1);
  71.     } else {
  72.         if(allow_setgid(pw_entry, gr_entry)) {
  73.         if(setgid(gr_entry->gr_gid) < 0) {
  74.             perror("newgrp: setgid");
  75.             exit(1);
  76.         }
  77.         } else {
  78.         puts("newgrp: Permission denied");
  79.         exit(1);
  80.         }
  81.     }
  82.     }
  83.  
  84.     if(setuid(getuid()) < 0) {
  85.     perror("newgrp: setuid");
  86.     exit(1);
  87.     }
  88.  
  89.     fflush(stdout); fflush(stderr);
  90.     execl(shell,shell,(char*)0);
  91.     perror("No shell");
  92.     fflush(stderr);
  93.     exit(1);
  94. }
  95.