pw_group.c revision 124382
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
28static const char rcsid[] =
29  "$FreeBSD: head/usr.sbin/pw/pw_group.c 124382 2004-01-11 18:28:08Z iedowse $";
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
41static int      print_group(struct group * grp, int pretty);
42static gid_t    gr_gidpolicy(struct userconf * cnf, struct cargs * args);
43
44int
45pw_group(struct userconf * cnf, int mode, struct cargs * args)
46{
47	int		rc;
48	struct carg    *a_name = getarg(args, 'n');
49	struct carg    *a_gid = getarg(args, 'g');
50	struct carg    *arg;
51	struct group   *grp = NULL;
52	int	        grmembers = 0;
53	char           **members = NULL;
54
55	static struct group fakegroup =
56	{
57		"nogroup",
58		"*",
59		-1,
60		NULL
61	};
62
63	if (mode == M_LOCK || mode == M_UNLOCK)
64		errx(EX_USAGE, "'lock' command is not available for groups");
65
66	/*
67	 * With M_NEXT, we only need to return the
68	 * next gid to stdout
69	 */
70	if (mode == M_NEXT) {
71		gid_t next = gr_gidpolicy(cnf, args);
72		if (getarg(args, 'q'))
73			return next;
74		printf("%ld\n", (long)next);
75		return EXIT_SUCCESS;
76	}
77
78	if (mode == M_PRINT && getarg(args, 'a')) {
79		int             pretty = getarg(args, 'P') != NULL;
80
81		SETGRENT();
82		while ((grp = GETGRENT()) != NULL)
83			print_group(grp, pretty);
84		ENDGRENT();
85		return EXIT_SUCCESS;
86	}
87	if (a_gid == NULL) {
88		if (a_name == NULL)
89			errx(EX_DATAERR, "group name or id required");
90
91		if (mode != M_ADD && grp == NULL && isdigit((unsigned char)*a_name->val)) {
92			(a_gid = a_name)->ch = 'g';
93			a_name = NULL;
94		}
95	}
96	grp = (a_name != NULL) ? GETGRNAM(a_name->val) : GETGRGID((gid_t) atoi(a_gid->val));
97
98	if (mode == M_UPDATE || mode == M_DELETE || mode == M_PRINT) {
99		if (a_name == NULL && grp == NULL)	/* Try harder */
100			grp = GETGRGID(atoi(a_gid->val));
101
102		if (grp == NULL) {
103			if (mode == M_PRINT && getarg(args, 'F')) {
104				char	*fmems[1];
105				fmems[0] = NULL;
106				fakegroup.gr_name = a_name ? a_name->val : "nogroup";
107				fakegroup.gr_gid = a_gid ? (gid_t) atol(a_gid->val) : -1;
108				fakegroup.gr_mem = fmems;
109				return print_group(&fakegroup, getarg(args, 'P') != NULL);
110			}
111			errx(EX_DATAERR, "unknown group `%s'", a_name ? a_name->val : a_gid->val);
112		}
113		if (a_name == NULL)	/* Needed later */
114			a_name = addarg(args, 'n', grp->gr_name);
115
116		/*
117		 * Handle deletions now
118		 */
119		if (mode == M_DELETE) {
120			gid_t           gid = grp->gr_gid;
121
122			rc = delgrent(grp);
123			if (rc == -1)
124				err(EX_IOERR, "group '%s' not available (NIS?)", grp->gr_name);
125			else if (rc != 0) {
126				warn("group update");
127				return EX_IOERR;
128			}
129			pw_log(cnf, mode, W_GROUP, "%s(%ld) removed", a_name->val, (long) gid);
130			return EXIT_SUCCESS;
131		} else if (mode == M_PRINT)
132			return print_group(grp, getarg(args, 'P') != NULL);
133
134		if (a_gid)
135			grp->gr_gid = (gid_t) atoi(a_gid->val);
136
137		if ((arg = getarg(args, 'l')) != NULL)
138			grp->gr_name = pw_checkname((u_char *)arg->val, 0);
139	} else {
140		if (a_name == NULL)	/* Required */
141			errx(EX_DATAERR, "group name required");
142		else if (grp != NULL)	/* Exists */
143			errx(EX_DATAERR, "group name `%s' already exists", a_name->val);
144
145		extendarray(&members, &grmembers, 200);
146		members[0] = NULL;
147		grp = &fakegroup;
148		grp->gr_name = pw_checkname((u_char *)a_name->val, 0);
149		grp->gr_passwd = "*";
150		grp->gr_gid = gr_gidpolicy(cnf, args);
151		grp->gr_mem = members;
152	}
153
154	/*
155	 * This allows us to set a group password Group passwords is an
156	 * antique idea, rarely used and insecure (no secure database) Should
157	 * be discouraged, but it is apparently still supported by some
158	 * software.
159	 */
160
161	if ((arg = getarg(args, 'h')) != NULL ||
162	    (arg = getarg(args, 'H')) != NULL) {
163		if (strcmp(arg->val, "-") == 0)
164			grp->gr_passwd = "*";	/* No access */
165		else {
166			int             fd = atoi(arg->val);
167			int		precrypt = (arg->ch == 'H');
168			int             b;
169			int             istty = isatty(fd);
170			struct termios  t;
171			char           *p, line[256];
172
173			if (istty) {
174				if (tcgetattr(fd, &t) == -1)
175					istty = 0;
176				else {
177					struct termios  n = t;
178
179					/* Disable echo */
180					n.c_lflag &= ~(ECHO);
181					tcsetattr(fd, TCSANOW, &n);
182					printf("%sassword for group %s:", (mode == M_UPDATE) ? "New p" : "P", grp->gr_name);
183					fflush(stdout);
184				}
185			}
186			b = read(fd, line, sizeof(line) - 1);
187			if (istty) {	/* Restore state */
188				tcsetattr(fd, TCSANOW, &t);
189				fputc('\n', stdout);
190				fflush(stdout);
191			}
192			if (b < 0) {
193				warn("-h file descriptor");
194				return EX_OSERR;
195			}
196			line[b] = '\0';
197			if ((p = strpbrk(line, " \t\r\n")) != NULL)
198				*p = '\0';
199			if (!*line)
200				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
201			if (precrypt) {
202				if (strchr(line, ':') != NULL)
203					return EX_DATAERR;
204				grp->gr_passwd = line;
205			} else
206				grp->gr_passwd = pw_pwcrypt(line);
207		}
208	}
209
210	if (((arg = getarg(args, 'M')) != NULL || (arg = getarg(args, 'm')) != NULL) && arg->val) {
211		int	i = 0;
212		char   *p;
213		struct passwd	*pwd;
214
215		/* Make sure this is not stay NULL with -M "" */
216		extendarray(&members, &grmembers, 200);
217		if (arg->ch == 'm') {
218			int	k = 0;
219
220			while (grp->gr_mem[k] != NULL) {
221				if (extendarray(&members, &grmembers, i + 2) != -1) {
222					members[i++] = grp->gr_mem[k];
223				}
224				k++;
225			}
226		}
227		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
228			int     j;
229			if ((pwd = GETPWNAM(p)) == NULL) {
230				if (!isdigit((unsigned char)*p) || (pwd = getpwuid((uid_t) atoi(p))) == NULL)
231					errx(EX_NOUSER, "user `%s' does not exist", p);
232			}
233			/*
234			 * Check for duplicates
235			 */
236			for (j = 0; j < i && strcmp(members[j], pwd->pw_name)!=0; j++)
237				;
238			if (j == i && extendarray(&members, &grmembers, i + 2) != -1)
239				members[i++] = newstr(pwd->pw_name);
240		}
241		while (i < grmembers)
242			members[i++] = NULL;
243		grp->gr_mem = members;
244	}
245
246	if (getarg(args, 'N') != NULL)
247		return print_group(grp, getarg(args, 'P') != NULL);
248
249	if (mode == M_ADD && (rc = addgrent(grp)) != 0) {
250		if (rc == -1)
251			warnx("group '%s' already exists", grp->gr_name);
252		else
253			warn("group update");
254		return EX_IOERR;
255	} else if (mode == M_UPDATE && (rc = chggrent(a_name->val, grp)) != 0) {
256		if (rc == -1)
257			warnx("group '%s' not available (NIS?)", grp->gr_name);
258		else
259			warn("group update");
260		return EX_IOERR;
261	}
262	/* grp may have been invalidated */
263	if ((grp = GETGRNAM(a_name->val)) == NULL)
264		errx(EX_SOFTWARE, "group disappeared during update");
265
266	pw_log(cnf, mode, W_GROUP, "%s(%ld)", grp->gr_name, (long) grp->gr_gid);
267
268	if (members)
269		free(members);
270
271	return EXIT_SUCCESS;
272}
273
274
275static          gid_t
276gr_gidpolicy(struct userconf * cnf, struct cargs * args)
277{
278	struct group   *grp;
279	gid_t           gid = (gid_t) - 1;
280	struct carg    *a_gid = getarg(args, 'g');
281
282	/*
283	 * Check the given gid, if any
284	 */
285	if (a_gid != NULL) {
286		gid = (gid_t) atol(a_gid->val);
287
288		if ((grp = GETGRGID(gid)) != NULL && getarg(args, 'o') == NULL)
289			errx(EX_DATAERR, "gid `%ld' has already been allocated", (long) grp->gr_gid);
290	} else {
291		struct bitmap   bm;
292
293		/*
294		 * We need to allocate the next available gid under one of
295		 * two policies a) Grab the first unused gid b) Grab the
296		 * highest possible unused gid
297		 */
298		if (cnf->min_gid >= cnf->max_gid) {	/* Sanity claus^H^H^H^Hheck */
299			cnf->min_gid = 1000;
300			cnf->max_gid = 32000;
301		}
302		bm = bm_alloc(cnf->max_gid - cnf->min_gid + 1);
303
304		/*
305		 * Now, let's fill the bitmap from the password file
306		 */
307		SETGRENT();
308		while ((grp = GETGRENT()) != NULL)
309			if ((gid_t)grp->gr_gid >= (gid_t)cnf->min_gid &&
310                            (gid_t)grp->gr_gid <= (gid_t)cnf->max_gid)
311				bm_setbit(&bm, grp->gr_gid - cnf->min_gid);
312		ENDGRENT();
313
314		/*
315		 * Then apply the policy, with fallback to reuse if necessary
316		 */
317		if (cnf->reuse_gids)
318			gid = (gid_t) (bm_firstunset(&bm) + cnf->min_gid);
319		else {
320			gid = (gid_t) (bm_lastset(&bm) + 1);
321			if (!bm_isset(&bm, gid))
322				gid += cnf->min_gid;
323			else
324				gid = (gid_t) (bm_firstunset(&bm) + cnf->min_gid);
325		}
326
327		/*
328		 * Another sanity check
329		 */
330		if (gid < cnf->min_gid || gid > cnf->max_gid)
331			errx(EX_SOFTWARE, "unable to allocate a new gid - range fully used");
332		bm_dealloc(&bm);
333	}
334	return gid;
335}
336
337
338static int
339print_group(struct group * grp, int pretty)
340{
341	if (!pretty) {
342		int		buflen = 0;
343		char           *buf = NULL;
344
345		fmtgrent(&buf, &buflen, grp);
346		fputs(buf, stdout);
347		free(buf);
348	} else {
349		int             i;
350
351		printf("Group Name: %-15s   #%lu\n"
352		       "   Members: ",
353		       grp->gr_name, (long) grp->gr_gid);
354		for (i = 0; grp->gr_mem[i]; i++)
355			printf("%s%s", i ? "," : "", grp->gr_mem[i]);
356		fputs("\n\n", stdout);
357	}
358	return EXIT_SUCCESS;
359}
360