xref: /freebsd/usr.sbin/pw/pw_group.c (revision 4b9d6057)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 1996
5  *	David L. Nugent.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <ctype.h>
30 #include <err.h>
31 #include <grp.h>
32 #include <libutil.h>
33 #include <paths.h>
34 #include <string.h>
35 #include <sysexits.h>
36 #include <termios.h>
37 #include <unistd.h>
38 
39 #include "pw.h"
40 #include "bitmap.h"
41 
42 static struct passwd *lookup_pwent(const char *user);
43 static void	delete_members(struct group *grp, char *list);
44 static int	print_group(struct group * grp, bool pretty);
45 static gid_t	gr_gidpolicy(struct userconf * cnf, intmax_t id);
46 
47 static void
48 grp_set_passwd(struct group *grp, bool update, int fd, bool precrypted)
49 {
50 	int		 b;
51 	int		 istty;
52 	struct termios	 t, n;
53 	static char      line[256];
54 	char		*p;
55 
56 	if (fd == -1)
57 		return;
58 
59 	if (fd == '-') {
60 		grp->gr_passwd = "*";	/* No access */
61 		return;
62 	}
63 
64 	if ((istty = isatty(fd))) {
65 		if (tcgetattr(fd, &t) == -1)
66 			istty = 0;
67 		else {
68 			n = t;
69 			/* Disable echo */
70 			n.c_lflag &= ~(ECHO);
71 			tcsetattr(fd, TCSANOW, &n);
72 			printf("%sassword for group %s:",
73 			    update ? "New p" : "P",
74 			    grp->gr_name);
75 			fflush(stdout);
76 		}
77 	}
78 	b = read(fd, line, sizeof(line) - 1);
79 	if (istty) {	/* Restore state */
80 		tcsetattr(fd, TCSANOW, &t);
81 		fputc('\n', stdout);
82 		fflush(stdout);
83 	}
84 	if (b < 0)
85 		err(EX_OSERR, "-h file descriptor");
86 	line[b] = '\0';
87 	if ((p = strpbrk(line, " \t\r\n")) != NULL)
88 		*p = '\0';
89 	if (!*line)
90 		errx(EX_DATAERR, "empty password read on file descriptor %d",
91 		    conf.fd);
92 	if (precrypted) {
93 		if (strchr(line, ':') != 0)
94 			errx(EX_DATAERR, "wrong encrypted passwrd");
95 		grp->gr_passwd = line;
96 	} else
97 		grp->gr_passwd = pw_pwcrypt(line);
98 }
99 
100 int
101 pw_groupnext(struct userconf *cnf, bool quiet)
102 {
103 	gid_t next = gr_gidpolicy(cnf, -1);
104 
105 	if (quiet)
106 		return (next);
107 	printf("%ju\n", (uintmax_t)next);
108 
109 	return (EXIT_SUCCESS);
110 }
111 
112 static struct group *
113 getgroup(char *name, intmax_t id, bool fatal)
114 {
115 	struct group *grp;
116 
117 	if (id < 0 && name == NULL)
118 		errx(EX_DATAERR, "groupname or id required");
119 	grp = (name != NULL) ? GETGRNAM(name) : GETGRGID(id);
120 	if (grp == NULL) {
121 		if (!fatal)
122 			return (NULL);
123 		if (name == NULL)
124 			errx(EX_DATAERR, "unknown gid `%ju'", id);
125 		errx(EX_DATAERR, "unknown group `%s'", name);
126 	}
127 	return (grp);
128 }
129 
130 /*
131  * Lookup a passwd entry using a name or UID.
132  */
133 static struct passwd *
134 lookup_pwent(const char *user)
135 {
136 	struct passwd *pwd;
137 
138 	if ((pwd = GETPWNAM(user)) == NULL &&
139 	    (!isdigit((unsigned char)*user) ||
140 	    (pwd = getpwuid((uid_t) atoi(user))) == NULL))
141 		errx(EX_NOUSER, "user `%s' does not exist", user);
142 
143 	return (pwd);
144 }
145 
146 
147 /*
148  * Delete requested members from a group.
149  */
150 static void
151 delete_members(struct group *grp, char *list)
152 {
153 	char *p;
154 	int k;
155 
156 	if (grp->gr_mem == NULL)
157 		return;
158 
159 	for (p = strtok(list, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
160 		for (k = 0; grp->gr_mem[k] != NULL; k++) {
161 			if (strcmp(grp->gr_mem[k], p) == 0)
162 				break;
163 		}
164 		if (grp->gr_mem[k] == NULL) /* No match */
165 			continue;
166 
167 		for (; grp->gr_mem[k] != NULL; k++)
168 			grp->gr_mem[k] = grp->gr_mem[k+1];
169 	}
170 }
171 
172 static gid_t
173 gr_gidpolicy(struct userconf * cnf, intmax_t id)
174 {
175 	struct group   *grp;
176 	struct bitmap   bm;
177 	gid_t           gid = (gid_t) - 1;
178 
179 	/*
180 	 * Check the given gid, if any
181 	 */
182 	if (id > 0) {
183 		gid = (gid_t) id;
184 
185 		if ((grp = GETGRGID(gid)) != NULL && conf.checkduplicate)
186 			errx(EX_DATAERR, "gid `%ju' has already been allocated",
187 			    (uintmax_t)grp->gr_gid);
188 		return (gid);
189 	}
190 
191 	/*
192 	 * We need to allocate the next available gid under one of
193 	 * two policies a) Grab the first unused gid b) Grab the
194 	 * highest possible unused gid
195 	 */
196 	if (cnf->min_gid >= cnf->max_gid) {	/* Sanity claus^H^H^H^Hheck */
197 		cnf->min_gid = 1000;
198 		cnf->max_gid = 32000;
199 	}
200 	bm = bm_alloc(cnf->max_gid - cnf->min_gid + 1);
201 
202 	/*
203 	 * Now, let's fill the bitmap from the password file
204 	 */
205 	SETGRENT();
206 	while ((grp = GETGRENT()) != NULL)
207 		if ((gid_t)grp->gr_gid >= (gid_t)cnf->min_gid &&
208 		    (gid_t)grp->gr_gid <= (gid_t)cnf->max_gid)
209 			bm_setbit(&bm, grp->gr_gid - cnf->min_gid);
210 	ENDGRENT();
211 
212 	/*
213 	 * Then apply the policy, with fallback to reuse if necessary
214 	 */
215 	if (cnf->reuse_gids)
216 		gid = (gid_t) (bm_firstunset(&bm) + cnf->min_gid);
217 	else {
218 		gid = (gid_t) (bm_lastset(&bm) + 1);
219 		if (!bm_isset(&bm, gid))
220 			gid += cnf->min_gid;
221 		else
222 			gid = (gid_t) (bm_firstunset(&bm) + cnf->min_gid);
223 	}
224 
225 	/*
226 	 * Another sanity check
227 	 */
228 	if (gid < cnf->min_gid || gid > cnf->max_gid)
229 		errx(EX_SOFTWARE, "unable to allocate a new gid - range fully "
230 		    "used");
231 	bm_dealloc(&bm);
232 	return (gid);
233 }
234 
235 static int
236 print_group(struct group * grp, bool pretty)
237 {
238 	char *buf = NULL;
239 	int i;
240 
241 	if (pretty) {
242 		printf("Group Name: %-15s   #%lu\n"
243 		       "   Members: ",
244 		       grp->gr_name, (long) grp->gr_gid);
245 		if (grp->gr_mem != NULL) {
246 			for (i = 0; grp->gr_mem[i]; i++)
247 				printf("%s%s", i ? "," : "", grp->gr_mem[i]);
248 		}
249 		fputs("\n\n", stdout);
250 		return (EXIT_SUCCESS);
251 	}
252 
253 	buf = gr_make(grp);
254 	printf("%s\n", buf);
255 	free(buf);
256 	return (EXIT_SUCCESS);
257 }
258 
259 int
260 pw_group_next(int argc, char **argv, char *arg1 __unused)
261 {
262 	struct userconf *cnf;
263 	const char *cfg = NULL;
264 	int ch;
265 	bool quiet = false;
266 
267 	while ((ch = getopt(argc, argv, "C:q")) != -1) {
268 		switch (ch) {
269 		case 'C':
270 			cfg = optarg;
271 			break;
272 		case 'q':
273 			quiet = true;
274 			break;
275 		default:
276 			exit(EX_USAGE);
277 		}
278 	}
279 
280 	if (quiet)
281 		freopen(_PATH_DEVNULL, "w", stderr);
282 	cnf = get_userconfig(cfg);
283 	return (pw_groupnext(cnf, quiet));
284 }
285 
286 int
287 pw_group_show(int argc, char **argv, char *arg1)
288 {
289 	struct group *grp = NULL;
290 	char *name = NULL;
291 	intmax_t id = -1;
292 	int ch;
293 	bool all, force, quiet, pretty;
294 
295 	all = force = quiet = pretty = false;
296 
297 	struct group fakegroup = {
298 		"nogroup",
299 		"*",
300 		-1,
301 		NULL
302 	};
303 
304 	if (arg1 != NULL) {
305 		if (arg1[strspn(arg1, "0123456789")] == '\0')
306 			id = pw_checkid(arg1, GID_MAX);
307 		else
308 			name = arg1;
309 	}
310 
311 	while ((ch = getopt(argc, argv, "C:qn:g:FPa")) != -1) {
312 		switch (ch) {
313 		case 'C':
314 			/* ignore compatibility */
315 			break;
316 		case 'q':
317 			quiet = true;
318 			break;
319 		case 'n':
320 			name = optarg;
321 			break;
322 		case 'g':
323 			id = pw_checkid(optarg, GID_MAX);
324 			break;
325 		case 'F':
326 			force = true;
327 			break;
328 		case 'P':
329 			pretty = true;
330 			break;
331 		case 'a':
332 			all = true;
333 			break;
334 		default:
335 			exit(EX_USAGE);
336 		}
337 	}
338 
339 	if (quiet)
340 		freopen(_PATH_DEVNULL, "w", stderr);
341 
342 	if (all) {
343 		SETGRENT();
344 		while ((grp = GETGRENT()) != NULL)
345 			print_group(grp, pretty);
346 		ENDGRENT();
347 		return (EXIT_SUCCESS);
348 	}
349 
350 	grp = getgroup(name, id, !force);
351 	if (grp == NULL)
352 		grp = &fakegroup;
353 
354 	return (print_group(grp, pretty));
355 }
356 
357 int
358 pw_group_del(int argc, char **argv, char *arg1)
359 {
360 	struct userconf *cnf = NULL;
361 	struct group *grp = NULL;
362 	char *name;
363 	const char *cfg = NULL;
364 	intmax_t id = -1;
365 	int ch, rc;
366 	bool quiet = false;
367 	bool nis = false;
368 
369 	if (arg1 != NULL) {
370 		if (arg1[strspn(arg1, "0123456789")] == '\0')
371 			id = pw_checkid(arg1, GID_MAX);
372 		else
373 			name = arg1;
374 	}
375 
376 	while ((ch = getopt(argc, argv, "C:qn:g:Y")) != -1) {
377 		switch (ch) {
378 		case 'C':
379 			cfg = optarg;
380 			break;
381 		case 'q':
382 			quiet = true;
383 			break;
384 		case 'n':
385 			name = optarg;
386 			break;
387 		case 'g':
388 			id = pw_checkid(optarg, GID_MAX);
389 			break;
390 		case 'Y':
391 			nis = true;
392 			break;
393 		default:
394 			exit(EX_USAGE);
395 		}
396 	}
397 
398 	if (quiet)
399 		freopen(_PATH_DEVNULL, "w", stderr);
400 	grp = getgroup(name, id, true);
401 	cnf = get_userconfig(cfg);
402 	rc = delgrent(grp);
403 	if (rc == -1)
404 		err(EX_IOERR, "group '%s' not available (NIS?)", name);
405 	else if (rc != 0)
406 		err(EX_IOERR, "group update");
407 	pw_log(cnf, M_DELETE, W_GROUP, "%s(%ju) removed", name,
408 	    (uintmax_t)id);
409 
410 	if (nis && nis_update() == 0)
411 		pw_log(cnf, M_DELETE, W_GROUP, "NIS maps updated");
412 
413 	return (EXIT_SUCCESS);
414 }
415 
416 bool
417 grp_has_member(struct group *grp, const char *name)
418 {
419 	int j;
420 
421 	for (j = 0; grp->gr_mem != NULL && grp->gr_mem[j] != NULL; j++)
422 		if (strcmp(grp->gr_mem[j], name) == 0)
423 			return (true);
424 	return (false);
425 }
426 
427 static void
428 grp_add_members(struct group **grp, char *members)
429 {
430 	struct passwd *pwd;
431 	char *p;
432 	char tok[] = ", \t";
433 
434 	if (members == NULL)
435 		return;
436 	for (p = strtok(members, tok); p != NULL; p = strtok(NULL, tok)) {
437 		pwd = lookup_pwent(p);
438 		if (grp_has_member(*grp, pwd->pw_name))
439 			continue;
440 		*grp = gr_add(*grp, pwd->pw_name);
441 	}
442 }
443 
444 int
445 groupadd(struct userconf *cnf, char *name, gid_t id, char *members, int fd,
446     bool dryrun, bool pretty, bool precrypted)
447 {
448 	struct group *grp;
449 	int rc;
450 
451 	struct group fakegroup = {
452 		"nogroup",
453 		"*",
454 		-1,
455 		NULL
456 	};
457 
458 	grp = &fakegroup;
459 	grp->gr_name = pw_checkname(name, 0);
460 	grp->gr_passwd = "*";
461 	grp->gr_gid = gr_gidpolicy(cnf, id);
462 	grp->gr_mem = NULL;
463 
464 	/*
465 	 * This allows us to set a group password Group passwords is an
466 	 * antique idea, rarely used and insecure (no secure database) Should
467 	 * be discouraged, but it is apparently still supported by some
468 	 * software.
469 	 */
470 	grp_set_passwd(grp, false, fd, precrypted);
471 	grp_add_members(&grp, members);
472 	if (dryrun)
473 		return (print_group(grp, pretty));
474 
475 	if ((rc = addgrent(grp)) != 0) {
476 		if (rc == -1)
477 			errx(EX_IOERR, "group '%s' already exists",
478 			    grp->gr_name);
479 		else
480 			err(EX_IOERR, "group update");
481 	}
482 
483 	pw_log(cnf, M_ADD, W_GROUP, "%s(%ju)", grp->gr_name,
484 	    (uintmax_t)grp->gr_gid);
485 
486 	return (EXIT_SUCCESS);
487 }
488 
489 int
490 pw_group_add(int argc, char **argv, char *arg1)
491 {
492 	struct userconf *cnf = NULL;
493 	char *name = NULL;
494 	char *members = NULL;
495 	const char *cfg = NULL;
496 	intmax_t id = -1;
497 	int ch, rc, fd = -1;
498 	bool quiet, precrypted, dryrun, pretty, nis;
499 
500 	quiet = precrypted = dryrun = pretty = nis = false;
501 
502 	if (arg1 != NULL) {
503 		if (arg1[strspn(arg1, "0123456789")] == '\0')
504 			id = pw_checkid(arg1, GID_MAX);
505 		else
506 			name = arg1;
507 	}
508 
509 	while ((ch = getopt(argc, argv, "C:qn:g:h:H:M:oNPY")) != -1) {
510 		switch (ch) {
511 		case 'C':
512 			cfg = optarg;
513 			break;
514 		case 'q':
515 			quiet = true;
516 			break;
517 		case 'n':
518 			name = optarg;
519 			break;
520 		case 'g':
521 			id = pw_checkid(optarg, GID_MAX);
522 			break;
523 		case 'H':
524 			if (fd != -1)
525 				errx(EX_USAGE, "'-h' and '-H' are mutually "
526 				    "exclusive options");
527 			fd = pw_checkfd(optarg);
528 			precrypted = true;
529 			if (fd == '-')
530 				errx(EX_USAGE, "-H expects a file descriptor");
531 			break;
532 		case 'h':
533 			if (fd != -1)
534 				errx(EX_USAGE, "'-h' and '-H' are mutually "
535 				    "exclusive options");
536 			fd = pw_checkfd(optarg);
537 			break;
538 		case 'M':
539 			members = optarg;
540 			break;
541 		case 'o':
542 			conf.checkduplicate = false;
543 			break;
544 		case 'N':
545 			dryrun = true;
546 			break;
547 		case 'P':
548 			pretty = true;
549 			break;
550 		case 'Y':
551 			nis = true;
552 			break;
553 		default:
554 			exit(EX_USAGE);
555 		}
556 	}
557 
558 	if (quiet)
559 		freopen(_PATH_DEVNULL, "w", stderr);
560 	if (name == NULL)
561 		errx(EX_DATAERR, "group name required");
562 	if (GETGRNAM(name) != NULL)
563 		errx(EX_DATAERR, "group name `%s' already exists", name);
564 	cnf = get_userconfig(cfg);
565 	rc = groupadd(cnf, name, gr_gidpolicy(cnf, id), members, fd, dryrun,
566 	    pretty, precrypted);
567 	if (nis && rc == EXIT_SUCCESS && nis_update() == 0)
568 		pw_log(cnf, M_ADD, W_GROUP, "NIS maps updated");
569 
570 	return (rc);
571 }
572 
573 int
574 pw_group_mod(int argc, char **argv, char *arg1)
575 {
576 	struct userconf *cnf;
577 	struct group *grp = NULL;
578 	const char *cfg = NULL;
579 	char *oldmembers = NULL;
580 	char *members = NULL;
581 	char *newmembers = NULL;
582 	char *newname = NULL;
583 	char *name = NULL;
584 	intmax_t id = -1;
585 	int ch, rc, fd = -1;
586 	bool quiet, pretty, dryrun, nis, precrypted;
587 
588 	quiet = pretty = dryrun = nis = precrypted = false;
589 
590 	if (arg1 != NULL) {
591 		if (arg1[strspn(arg1, "0123456789")] == '\0')
592 			id = pw_checkid(arg1, GID_MAX);
593 		else
594 			name = arg1;
595 	}
596 
597 	while ((ch = getopt(argc, argv, "C:qn:d:g:l:h:H:M:m:NPY")) != -1) {
598 		switch (ch) {
599 		case 'C':
600 			cfg = optarg;
601 			break;
602 		case 'q':
603 			quiet = true;
604 			break;
605 		case 'n':
606 			name = optarg;
607 			break;
608 		case 'g':
609 			id = pw_checkid(optarg, GID_MAX);
610 			break;
611 		case 'd':
612 			oldmembers = optarg;
613 			break;
614 		case 'l':
615 			newname = optarg;
616 			break;
617 		case 'H':
618 			if (fd != -1)
619 				errx(EX_USAGE, "'-h' and '-H' are mutually "
620 				    "exclusive options");
621 			fd = pw_checkfd(optarg);
622 			precrypted = true;
623 			if (fd == '-')
624 				errx(EX_USAGE, "-H expects a file descriptor");
625 			break;
626 		case 'h':
627 			if (fd != -1)
628 				errx(EX_USAGE, "'-h' and '-H' are mutually "
629 				    "exclusive options");
630 			fd = pw_checkfd(optarg);
631 			break;
632 		case 'M':
633 			members = optarg;
634 			break;
635 		case 'm':
636 			newmembers = optarg;
637 			break;
638 		case 'N':
639 			dryrun = true;
640 			break;
641 		case 'P':
642 			pretty = true;
643 			break;
644 		case 'Y':
645 			nis = true;
646 			break;
647 		default:
648 			exit(EX_USAGE);
649 		}
650 	}
651 	if (quiet)
652 		freopen(_PATH_DEVNULL, "w", stderr);
653 	cnf = get_userconfig(cfg);
654 	grp = getgroup(name, id, true);
655 	if (name == NULL)
656 		name = grp->gr_name;
657 	if (id > 0)
658 		grp->gr_gid = id;
659 
660 	if (newname != NULL)
661 		grp->gr_name = pw_checkname(newname, 0);
662 
663 	grp_set_passwd(grp, true, fd, precrypted);
664 	/*
665 	 * Keep the same logic as old code for now:
666 	 * if -M is passed, -d and -m are ignored
667 	 * then id -d, -m is ignored
668 	 * last is -m
669 	 */
670 
671 	if (members) {
672 		grp->gr_mem = NULL;
673 		grp_add_members(&grp, members);
674 	} else if (oldmembers) {
675 		delete_members(grp, oldmembers);
676 	} else if (newmembers) {
677 		grp_add_members(&grp, newmembers);
678 	}
679 
680 	if (dryrun) {
681 		print_group(grp, pretty);
682 		return (EXIT_SUCCESS);
683 	}
684 
685 	if ((rc = chggrent(name, grp)) != 0) {
686 		if (rc == -1)
687 			errx(EX_IOERR, "group '%s' not available (NIS?)",
688 			    grp->gr_name);
689 		else
690 			err(EX_IOERR, "group update");
691 	}
692 
693 	if (newname)
694 		name = newname;
695 
696 	/* grp may have been invalidated */
697 	if ((grp = GETGRNAM(name)) == NULL)
698 		errx(EX_SOFTWARE, "group disappeared during update");
699 
700 	pw_log(cnf, M_UPDATE, W_GROUP, "%s(%ju)", grp->gr_name,
701 	    (uintmax_t)grp->gr_gid);
702 
703 	if (nis && nis_update() == 0)
704 		pw_log(cnf, M_UPDATE, W_GROUP, "NIS maps updated");
705 
706 	return (EXIT_SUCCESS);
707 }
708