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