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