xref: /freebsd/usr.sbin/pw/pw_group.c (revision 4cf49a43559ed9fdad601bdcccd2c55963008675)
1 /*-
2  * Copyright (C) 1996
3  *	David L. Nugent.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #ifndef lint
28 static const char rcsid[] =
29   "$FreeBSD$";
30 #endif /* not lint */
31 
32 #include <ctype.h>
33 #include <err.h>
34 #include <termios.h>
35 #include <unistd.h>
36 
37 #include "pw.h"
38 #include "bitmap.h"
39 
40 
41 static int      print_group(struct group * grp, int pretty);
42 static gid_t    gr_gidpolicy(struct userconf * cnf, struct cargs * args);
43 
44 int
45 pw_group(struct userconf * cnf, int mode, struct cargs * args)
46 {
47 	struct carg    *a_name = getarg(args, 'n');
48 	struct carg    *a_gid = getarg(args, 'g');
49 	struct carg    *arg;
50 	struct group   *grp = NULL;
51 	int	        grmembers = 0;
52 	char          **members = NULL;
53 
54 	static struct group fakegroup =
55 	{
56 		"nogroup",
57 		"*",
58 		-1,
59 		NULL
60 	};
61 
62 	/*
63 	 * With M_NEXT, we only need to return the
64 	 * next gid to stdout
65 	 */
66 	if (mode == M_NEXT)
67 	{
68 		gid_t next = gr_gidpolicy(cnf, args);
69 		if (getarg(args, 'q'))
70 			return next;
71 		printf("%ld\n", (long)next);
72 		return EXIT_SUCCESS;
73 	}
74 
75 	if (mode == M_PRINT && getarg(args, 'a')) {
76 		int             pretty = getarg(args, 'P') != NULL;
77 
78 		SETGRENT();
79 		while ((grp = GETGRENT()) != NULL)
80 			print_group(grp, pretty);
81 		ENDGRENT();
82 		return EXIT_SUCCESS;
83 	}
84 	if (a_gid == NULL) {
85 		if (a_name == NULL)
86 			errx(EX_DATAERR, "group name or id required");
87 
88 		if (mode != M_ADD && grp == NULL && isdigit(*a_name->val)) {
89 			(a_gid = a_name)->ch = 'g';
90 			a_name = NULL;
91 		}
92 	}
93 	grp = (a_name != NULL) ? GETGRNAM(a_name->val) : GETGRGID((gid_t) atoi(a_gid->val));
94 
95 	if (mode == M_UPDATE || mode == M_DELETE || mode == M_PRINT) {
96 		if (a_name == NULL && grp == NULL)	/* Try harder */
97 			grp = GETGRGID(atoi(a_gid->val));
98 
99 		if (grp == NULL) {
100 			if (mode == M_PRINT && getarg(args, 'F')) {
101 				char	*fmems[1];
102 				fmems[0] = NULL;
103 				fakegroup.gr_name = a_name ? a_name->val : "nogroup";
104 				fakegroup.gr_gid = a_gid ? (gid_t) atol(a_gid->val) : -1;
105 				fakegroup.gr_mem = fmems;
106 				return print_group(&fakegroup, getarg(args, 'P') != NULL);
107 			}
108 			errx(EX_DATAERR, "unknown group `%s'", a_name ? a_name->val : a_gid->val);
109 		}
110 		if (a_name == NULL)	/* Needed later */
111 			a_name = addarg(args, 'n', grp->gr_name);
112 
113 		/*
114 		 * Handle deletions now
115 		 */
116 		if (mode == M_DELETE) {
117 			gid_t           gid = grp->gr_gid;
118 
119 			if (delgrent(grp) == -1)
120 				err(EX_IOERR, "error updating group file");
121 			pw_log(cnf, mode, W_GROUP, "%s(%ld) removed", a_name->val, (long) gid);
122 			return EXIT_SUCCESS;
123 		} else if (mode == M_PRINT)
124 			return print_group(grp, getarg(args, 'P') != NULL);
125 
126 		if (a_gid)
127 			grp->gr_gid = (gid_t) atoi(a_gid->val);
128 
129 		if ((arg = getarg(args, 'l')) != NULL)
130 			grp->gr_name = pw_checkname((u_char *)arg->val, 0);
131 	} else {
132 		if (a_name == NULL)	/* Required */
133 			errx(EX_DATAERR, "group name required");
134 		else if (grp != NULL)	/* Exists */
135 			errx(EX_DATAERR, "group name `%s' already exists", a_name->val);
136 
137 		extendarray(&members, &grmembers, 200);
138 		members[0] = NULL;
139 		grp = &fakegroup;
140 		grp->gr_name = pw_checkname((u_char *)a_name->val, 0);
141 		grp->gr_passwd = "*";
142 		grp->gr_gid = gr_gidpolicy(cnf, args);
143 		grp->gr_mem = members;
144 	}
145 
146 	/*
147 	 * This allows us to set a group password Group passwords is an
148 	 * antique idea, rarely used and insecure (no secure database) Should
149 	 * be discouraged, but it is apparently still supported by some
150 	 * software.
151 	 */
152 
153 	if ((arg = getarg(args, 'h')) != NULL) {
154 		if (strcmp(arg->val, "-") == 0)
155 			grp->gr_passwd = "*";	/* No access */
156 		else {
157 			int             fd = atoi(arg->val);
158 			int             b;
159 			int             istty = isatty(fd);
160 			struct termios  t;
161 			char           *p, line[256];
162 
163 			if (istty) {
164 				if (tcgetattr(fd, &t) == -1)
165 					istty = 0;
166 				else {
167 					struct termios  n = t;
168 
169 					/* Disable echo */
170 					n.c_lflag &= ~(ECHO);
171 					tcsetattr(fd, TCSANOW, &n);
172 					printf("%sassword for group %s:", (mode == M_UPDATE) ? "New p" : "P", grp->gr_name);
173 					fflush(stdout);
174 				}
175 			}
176 			b = read(fd, line, sizeof(line) - 1);
177 			if (istty) {	/* Restore state */
178 				tcsetattr(fd, TCSANOW, &t);
179 				fputc('\n', stdout);
180 				fflush(stdout);
181 			}
182 			if (b < 0) {
183 				warn("-h file descriptor");
184 				return EX_OSERR;
185 			}
186 			line[b] = '\0';
187 			if ((p = strpbrk(line, " \t\r\n")) != NULL)
188 				*p = '\0';
189 			if (!*line)
190 				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
191 			grp->gr_passwd = pw_pwcrypt(line);
192 		}
193 	}
194 
195 	if (((arg = getarg(args, 'M')) != NULL || (arg = getarg(args, 'm')) != NULL) && arg->val) {
196 		int	i = 0;
197 		char   *p;
198 		struct passwd	*pwd;
199 
200 		/* Make sure this is not stay NULL with -M "" */
201 		extendarray(&members, &grmembers, 200);
202 		if (arg->ch == 'm') {
203 			int	k = 0;
204 
205 			while (grp->gr_mem[k] != NULL) {
206 				if (extendarray(&members, &grmembers, i + 2) != -1) {
207 					members[i++] = grp->gr_mem[k];
208 				}
209 				k++;
210 			}
211 		}
212 		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
213 			int     j;
214 			if ((pwd = GETPWNAM(p)) == NULL) {
215 				if (!isdigit(*p) || (pwd = getpwuid((uid_t) atoi(p))) == NULL)
216 					errx(EX_NOUSER, "user `%s' does not exist", p);
217 			}
218 			/*
219 			 * Check for duplicates
220 			 */
221 			for (j = 0; j < i && strcmp(members[j], pwd->pw_name)!=0; j++)
222 				;
223 			if (j == i && extendarray(&members, &grmembers, i + 2) != -1)
224 				members[i++] = newstr(pwd->pw_name);
225 		}
226 		while (i < grmembers)
227 			members[i++] = NULL;
228 		grp->gr_mem = members;
229 	}
230 
231 	if (getarg(args, 'N') != NULL)
232 		return print_group(grp, getarg(args, 'P') != NULL);
233 
234 	if ((mode == M_ADD && !addgrent(grp)) || (mode == M_UPDATE && !chggrent(a_name->val, grp))) {
235 		warn("group update");
236 		return EX_IOERR;
237 	}
238 	/* grp may have been invalidated */
239 	if ((grp = GETGRNAM(a_name->val)) == NULL)
240 		errx(EX_SOFTWARE, "group disappeared during update");
241 
242 	pw_log(cnf, mode, W_GROUP, "%s(%ld)", grp->gr_name, (long) grp->gr_gid);
243 
244 	if (members)
245 		free(members);
246 
247 	return EXIT_SUCCESS;
248 }
249 
250 
251 static          gid_t
252 gr_gidpolicy(struct userconf * cnf, struct cargs * args)
253 {
254 	struct group   *grp;
255 	gid_t           gid = (gid_t) - 1;
256 	struct carg    *a_gid = getarg(args, 'g');
257 
258 	/*
259 	 * Check the given gid, if any
260 	 */
261 	if (a_gid != NULL) {
262 		gid = (gid_t) atol(a_gid->val);
263 
264 		if ((grp = GETGRGID(gid)) != NULL && getarg(args, 'o') == NULL)
265 			errx(EX_DATAERR, "gid `%ld' has already been allocated", (long) grp->gr_gid);
266 	} else {
267 		struct bitmap   bm;
268 
269 		/*
270 		 * We need to allocate the next available gid under one of
271 		 * two policies a) Grab the first unused gid b) Grab the
272 		 * highest possible unused gid
273 		 */
274 		if (cnf->min_gid >= cnf->max_gid) {	/* Sanity claus^H^H^H^Hheck */
275 			cnf->min_gid = 1000;
276 			cnf->max_gid = 32000;
277 		}
278 		bm = bm_alloc(cnf->max_gid - cnf->min_gid + 1);
279 
280 		/*
281 		 * Now, let's fill the bitmap from the password file
282 		 */
283 		SETGRENT();
284 		while ((grp = GETGRENT()) != NULL)
285 			if (grp->gr_gid >= (int) cnf->min_gid && grp->gr_gid <= (int) cnf->max_gid)
286 				bm_setbit(&bm, grp->gr_gid - cnf->min_gid);
287 		ENDGRENT();
288 
289 		/*
290 		 * Then apply the policy, with fallback to reuse if necessary
291 		 */
292 		if (cnf->reuse_gids)
293 			gid = (gid_t) (bm_firstunset(&bm) + cnf->min_gid);
294 		else {
295 			gid = (gid_t) (bm_lastset(&bm) + 1);
296 			if (!bm_isset(&bm, gid))
297 				gid += cnf->min_gid;
298 			else
299 				gid = (gid_t) (bm_firstunset(&bm) + cnf->min_gid);
300 		}
301 
302 		/*
303 		 * Another sanity check
304 		 */
305 		if (gid < cnf->min_gid || gid > cnf->max_gid)
306 			errx(EX_SOFTWARE, "unable to allocate a new gid - range fully used");
307 		bm_dealloc(&bm);
308 	}
309 	return gid;
310 }
311 
312 
313 static int
314 print_group(struct group * grp, int pretty)
315 {
316 	if (!pretty) {
317 		int		buflen = 0;
318 		char           *buf = NULL;
319 
320 		fmtgrent(&buf, &buflen, grp);
321 		fputs(buf, stdout);
322 		free(buf);
323 	} else {
324 		int             i;
325 
326 		printf("Group Name: %-15s   #%lu\n"
327 		       "   Members: ",
328 		       grp->gr_name, (long) grp->gr_gid);
329 		for (i = 0; grp->gr_mem[i]; i++)
330 			printf("%s%s", i ? "," : "", grp->gr_mem[i]);
331 		fputs("\n\n", stdout);
332 	}
333 	return EXIT_SUCCESS;
334 }
335