xref: /openbsd-src/usr.sbin/user/user.c (revision 3a3fbb3f2e2521ab7c4a56b7ff7462ebd9095ec5)
1 /* $OpenBSD: user.c,v 1.29 2001/12/05 18:23:55 millert Exp $ */
2 /* $NetBSD: user.c,v 1.45 2001/08/17 08:29:00 joda Exp $ */
3 
4 /*
5  * Copyright (c) 1999 Alistair G. Crooks.  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  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Alistair G. Crooks.
18  * 4. The name of the author may not be used to endorse or promote
19  *    products derived from this software without specific prior written
20  *    permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
23  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
26  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
28  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/param.h>
36 #include <sys/stat.h>
37 
38 #include <ctype.h>
39 #include <dirent.h>
40 #include <err.h>
41 #include <fcntl.h>
42 #include <grp.h>
43 #include <paths.h>
44 #include <pwd.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <time.h>
50 #include <unistd.h>
51 #include <util.h>
52 
53 #include "defs.h"
54 #include "usermgmt.h"
55 
56 
57 /* this struct describes a uid range */
58 typedef struct range_t {
59 	uid_t	r_from;		/* low uid */
60 	uid_t	r_to;		/* high uid */
61 } range_t;
62 
63 /* this struct encapsulates the user information */
64 typedef struct user_t {
65 	int		u_flags;		/* see below */
66 	uid_t		u_uid;			/* uid of user */
67 	char		*u_password;		/* encrypted password */
68 	char		*u_comment;		/* comment field */
69 	char		*u_home;		/* home directory */
70 	char		*u_primgrp;		/* primary group */
71 	int		u_groupc;		/* # of secondary groups */
72 	char		*u_groupv[NGROUPS_MAX];	/* secondary groups */
73 	char		*u_shell;		/* user's shell */
74 	char		*u_basedir;		/* base directory for home */
75 	char		*u_expire;		/* when password will expire */
76 	int		u_inactive;		/* inactive */
77 	char		*u_skeldir;		/* directory for startup files */
78 	char		*u_class;		/* login class */
79 	unsigned int	u_rsize;		/* size of range array */
80 	unsigned int	u_rc;			/* # of ranges */
81 	range_t		*u_rv;			/* the ranges */
82 	unsigned int	u_defrc;		/* # of ranges in defaults */
83 	int		u_preserve;		/* preserve uids on deletion */
84 } user_t;
85 
86 /* flags for which fields of the user_t replace the passwd entry */
87 enum {
88 	F_COMMENT	= 0x0001,
89 	F_DUPUID	= 0x0002,
90 	F_EXPIRE	= 0x0004,
91 	F_GROUP		= 0x0008,
92 	F_HOMEDIR	= 0x0010,
93 	F_MKDIR		= 0x0020,
94 	F_INACTIVE	= 0x0040,
95 	F_PASSWORD	= 0x0080,
96 	F_SECGROUP	= 0x0100,
97 	F_SHELL		= 0x0200,
98 	F_UID		= 0x0400,
99 	F_USERNAME	= 0x0800,
100 	F_CLASS		= 0x1000
101 };
102 
103 #define CONFFILE	"/etc/usermgmt.conf"
104 
105 #ifndef DEF_GROUP
106 #define DEF_GROUP	"users"
107 #endif
108 
109 #ifndef DEF_BASEDIR
110 #define DEF_BASEDIR	"/home"
111 #endif
112 
113 #ifndef DEF_SKELDIR
114 #define DEF_SKELDIR	"/etc/skel"
115 #endif
116 
117 #ifndef DEF_SHELL
118 #define DEF_SHELL	_PATH_CSHELL
119 #endif
120 
121 #ifndef DEF_COMMENT
122 #define DEF_COMMENT	""
123 #endif
124 
125 #ifndef DEF_LOWUID
126 #define DEF_LOWUID	1000
127 #endif
128 
129 #ifndef DEF_HIGHUID
130 #define DEF_HIGHUID	60000
131 #endif
132 
133 #ifndef DEF_INACTIVE
134 #define DEF_INACTIVE	0
135 #endif
136 
137 #ifndef DEF_EXPIRE
138 #define DEF_EXPIRE	NULL
139 #endif
140 
141 #ifndef DEF_CLASS
142 #define DEF_CLASS	""
143 #endif
144 
145 #ifndef WAITSECS
146 #define WAITSECS	10
147 #endif
148 
149 #ifndef NOBODY_UID
150 #define NOBODY_UID	32767
151 #endif
152 
153 /* some useful constants */
154 enum {
155 	MaxShellNameLen = 256,
156 	MaxFileNameLen = MAXPATHLEN,
157 	MaxUserNameLen = MAXLOGNAME,
158 	MaxCommandLen = 2048,
159 	PasswordLength = _PASSWORD_LEN,
160 
161 	LowGid = DEF_LOWUID,
162 	HighGid = DEF_HIGHUID
163 };
164 
165 /* Full paths of programs used here */
166 #define CHMOD		"/bin/chmod"
167 #define CHOWN		"/sbin/chown"
168 #define MKDIR		"/bin/mkdir"
169 #define MV		"/bin/mv"
170 #define NOLOGIN		"/sbin/nologin"
171 #define PAX		"/bin/pax"
172 #define RM		"/bin/rm"
173 
174 #define UNSET_EXPIRY	"Null (unset)"
175 
176 static int asystem(const char *fmt, ...)
177 	__attribute__((__format__(__printf__, 1, 2)));
178 
179 static int	verbose;
180 
181 /* if *cpp is non-null, free it, then assign `n' chars of `s' to it */
182 static void
183 memsave(char **cpp, char *s, size_t n)
184 {
185 	if (*cpp != NULL) {
186 		FREE(*cpp);
187 	}
188 	NEWARRAY(char, *cpp, n + 1, exit(1));
189 	(void) memcpy(*cpp, s, n);
190 	(*cpp)[n] = '\0';
191 }
192 
193 /* a replacement for system(3) */
194 static int
195 asystem(const char *fmt, ...)
196 {
197 	va_list	vp;
198 	char	buf[MaxCommandLen];
199 	int	ret;
200 
201 	va_start(vp, fmt);
202 	(void) vsnprintf(buf, sizeof(buf), fmt, vp);
203 	va_end(vp);
204 	if (verbose) {
205 		(void) printf("Command: %s\n", buf);
206 	}
207 	if ((ret = system(buf)) != 0) {
208 		warnx("[Warning] can't system `%s'", buf);
209 	}
210 	return ret;
211 }
212 
213 /* remove a users home directory, returning 1 for success (ie, no problems encountered) */
214 static int
215 removehomedir(const char *user, uid_t uid, const char *dir)
216 {
217 	struct stat st;
218 
219 	/* userid not root? */
220 	if (uid == 0) {
221 		warnx("Not deleting home directory `%s'; userid is 0", dir);
222 		return 0;
223 	}
224 
225 	/* directory exists (and is a directory!) */
226 	if (stat(dir, &st) < 0) {
227 		warnx("Home directory `%s' doesn't exist", dir);
228 		return 0;
229 	}
230 	if (!S_ISDIR(st.st_mode)) {
231 		warnx("Home directory `%s' is not a directory", dir);
232 		return 0;
233 	}
234 
235 	/* userid matches directory owner? */
236 	if (st.st_uid != uid) {
237 		warnx("User `%s' doesn't own directory `%s', not removed\n",
238 		    user, dir);
239 		return 0;
240 	}
241 
242 	(void) seteuid(uid);
243 	/* we add the "|| true" to keep asystem() quiet if there is a non-zero exit status. */
244 	(void) asystem("%s -rf %s > /dev/null 2>&1 || true", RM, dir);
245 	(void) seteuid(0);
246 	if (rmdir(dir) < 0) {
247 		warnx("Unable to remove all files in `%s'\n", dir);
248 		return 0;
249 	}
250 	return 1;
251 }
252 
253 /* return 1 if all of `s' is numeric */
254 static int
255 is_number(char *s)
256 {
257 	for ( ; *s ; s++) {
258 		if (!isdigit(*s)) {
259 			return 0;
260 		}
261 	}
262 	return 1;
263 }
264 
265 /*
266  * check that the effective uid is 0 - called from funcs which will
267  * modify data and config files.
268  */
269 static void
270 checkeuid(void)
271 {
272 	if (geteuid() != 0) {
273 		errx(EXIT_FAILURE, "Program must be run as root");
274 	}
275 }
276 
277 /* copy any dot files into the user's home directory */
278 static int
279 copydotfiles(char *skeldir, uid_t uid, gid_t gid, char *dir)
280 {
281 	struct dirent	*dp;
282 	DIR		*dirp;
283 	int		n;
284 
285 	if ((dirp = opendir(skeldir)) == NULL) {
286 		warn("can't open source . files dir `%s'", skeldir);
287 		return 0;
288 	}
289 	for (n = 0; (dp = readdir(dirp)) != NULL && n == 0 ; ) {
290 		if (strcmp(dp->d_name, ".") == 0 ||
291 		    strcmp(dp->d_name, "..") == 0) {
292 			continue;
293 		}
294 		n = 1;
295 	}
296 	(void) closedir(dirp);
297 	if (n == 0) {
298 		warnx("No \"dot\" initialisation files found");
299 	} else {
300 		(void) asystem("cd %s; %s -rw -pe %s . %s",
301 				skeldir, PAX, (verbose) ? "-v" : "", dir);
302 	}
303 	(void) asystem("%s -R -P %u:%u %s", CHOWN, uid, gid, dir);
304 	(void) asystem("%s -R u+w %s", CHMOD, dir);
305 	return n;
306 }
307 
308 /* create a group entry with gid `gid' */
309 static int
310 creategid(char *group, gid_t gid, char *name)
311 {
312 	struct stat	st;
313 	FILE		*from;
314 	FILE		*to;
315 	char		buf[LINE_MAX];
316 	char		f[MaxFileNameLen];
317 	int		fd;
318 	int		cc;
319 
320 	if (getgrnam(group) != NULL) {
321 		warnx("group `%s' already exists", group);
322 		return 0;
323 	}
324 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
325 		warn("can't create gid for %s: can't open %s", group,
326 		    _PATH_GROUP);
327 		return 0;
328 	}
329 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
330 		warn("can't lock `%s'", _PATH_GROUP);
331 	}
332 	(void) fstat(fileno(from), &st);
333 	(void) snprintf(f, sizeof(f), "%s.XXXXXXXX", _PATH_GROUP);
334 	if ((fd = mkstemp(f)) < 0) {
335 		(void) fclose(from);
336 		warn("can't create gid: mkstemp failed");
337 		return 0;
338 	}
339 	if ((to = fdopen(fd, "w")) == NULL) {
340 		(void) fclose(from);
341 		(void) close(fd);
342 		(void) unlink(f);
343 		warn("can't create gid: fdopen `%s' failed", f);
344 		return 0;
345 	}
346 	while ((cc = fread(buf, sizeof(char), sizeof(buf), from)) > 0) {
347 		if (fwrite(buf, cc, 1, to) <= 0) {
348 			(void) fclose(from);
349 			(void) fclose(to);
350 			(void) unlink(f);
351 			warn("can't create gid: short write to `%s'", f);
352 			return 0;
353 		}
354 	}
355 	(void) fprintf(to, "%s:*:%u:%s\n", group, gid, name);
356 	(void) fclose(from);
357 	(void) fclose(to);
358 	if (rename(f, _PATH_GROUP) < 0) {
359 		warn("can't create gid: can't rename `%s' to `%s'", f,
360 		    _PATH_GROUP);
361 		return 0;
362 	}
363 	(void) chmod(_PATH_GROUP, st.st_mode & 07777);
364 	return 1;
365 }
366 
367 /* modify the group entry with name `group' to be newent */
368 static int
369 modify_gid(char *group, char *newent)
370 {
371 	struct stat	st;
372 	FILE		*from;
373 	FILE		*to;
374 	char		buf[LINE_MAX];
375 	char		f[MaxFileNameLen];
376 	char		*colon;
377 	int		groupc;
378 	int		entc;
379 	int		fd;
380 	int		cc;
381 
382 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
383 		warn("can't create gid for %s: can't open %s", group, _PATH_GROUP);
384 		return 0;
385 	}
386 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
387 		warn("can't lock `%s'", _PATH_GROUP);
388 	}
389 	(void) fstat(fileno(from), &st);
390 	(void) snprintf(f, sizeof(f), "%s.XXXXXXXX", _PATH_GROUP);
391 	if ((fd = mkstemp(f)) < 0) {
392 		(void) fclose(from);
393 		warn("can't create gid: mkstemp failed");
394 		return 0;
395 	}
396 	if ((to = fdopen(fd, "w")) == NULL) {
397 		(void) fclose(from);
398 		(void) close(fd);
399 		(void) unlink(f);
400 		warn("can't create gid: fdopen `%s' failed", f);
401 		return 0;
402 	}
403 	groupc = strlen(group);
404 	while (fgets(buf, sizeof(buf), from) != NULL) {
405 		cc = strlen(buf);
406 		if (buf[cc - 1] != '\n') {
407 			while (!feof(from) && fgetc(from) != '\n')
408 				cc++;
409 			warn("line `%s' too long (%d bytes), skipping", buf,
410 			    cc);
411 			continue;
412 		}
413 		if ((colon = strchr(buf, ':')) == NULL) {
414 			warn("badly formed entry `%s'", buf);
415 			continue;
416 		}
417 		entc = (int)(colon - buf);
418 		if (entc == groupc && strncmp(group, buf, entc) == 0) {
419 			if (newent == NULL) {
420 				continue;
421 			} else {
422 				cc = strlen(newent);
423 				(void) strlcpy(buf, newent, sizeof(buf));
424 			}
425 		}
426 		if (fwrite(buf, cc, 1, to) <= 0) {
427 			(void) fclose(from);
428 			(void) fclose(to);
429 			(void) unlink(f);
430 			warn("can't create gid: short write to `%s'", f);
431 			return 0;
432 		}
433 	}
434 	(void) fclose(from);
435 	(void) fclose(to);
436 	if (rename(f, _PATH_GROUP) < 0) {
437 		warn("can't create gid: can't rename `%s' to `%s'", f, _PATH_GROUP);
438 		return 0;
439 	}
440 	(void) chmod(_PATH_GROUP, st.st_mode & 07777);
441 	return 1;
442 }
443 
444 /* modify the group entries for all `groups', by adding `user' */
445 static int
446 append_group(char *user, int ngroups, char **groups)
447 {
448 	struct group	*grp;
449 	struct stat	st;
450 	FILE		*from;
451 	FILE		*to;
452 	char		buf[LINE_MAX];
453 	char		f[MaxFileNameLen];
454 	char		*colon;
455 	int		fd;
456 	int		cc;
457 	int		i;
458 	int		j;
459 
460 	for (i = 0 ; i < ngroups ; i++) {
461 		if ((grp = getgrnam(groups[i])) == NULL) {
462 			warnx("can't append group `%s' for user `%s'",
463 			    groups[i], user);
464 		} else {
465 			for (j = 0 ; grp->gr_mem[j] ; j++) {
466 				if (strcmp(user, grp->gr_mem[j]) == 0) {
467 					/* already in it */
468 					groups[i] = "";
469 				}
470 			}
471 		}
472 	}
473 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
474 		warn("can't append group for %s: can't open %s", user,
475 		    _PATH_GROUP);
476 		return 0;
477 	}
478 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
479 		warn("can't lock `%s'", _PATH_GROUP);
480 	}
481 	(void) fstat(fileno(from), &st);
482 	(void) snprintf(f, sizeof(f), "%s.XXXXXXXX", _PATH_GROUP);
483 	if ((fd = mkstemp(f)) < 0) {
484 		(void) fclose(from);
485 		warn("can't create gid: mkstemp failed");
486 		return 0;
487 	}
488 	if ((to = fdopen(fd, "w")) == NULL) {
489 		(void) fclose(from);
490 		(void) close(fd);
491 		(void) unlink(f);
492 		warn("can't create gid: fdopen `%s' failed", f);
493 		return 0;
494 	}
495 	while (fgets(buf, sizeof(buf), from) != NULL) {
496 		cc = strlen(buf);
497 		if (buf[cc - 1] != '\n') {
498 			while (!feof(from) && fgetc(from) != '\n')
499 				cc++;
500 			warn("line `%s' too long (%d bytes), skipping", buf,
501 			    cc);
502 			continue;
503 		}
504 		if ((colon = strchr(buf, ':')) == NULL) {
505 			warn("badly formed entry `%s'", buf);
506 			continue;
507 		}
508 		for (i = 0 ; i < ngroups ; i++) {
509 			if (strncmp(groups[i], buf, colon - buf) == 0) {
510 				while (isspace(buf[cc - 1]))
511 					cc--;
512 				buf[(j = cc)] = '\0';
513 				if (*(colon + 1) != '\0')
514 					strlcat(buf, ",", sizeof(buf));
515 				cc = strlcat(buf, user, sizeof(buf)) + 1;
516 				if (cc >= sizeof(buf)) {
517 					warnx("Warning: group `%s' would "
518 					    "become too long, not modifying",
519 					    groups[i]);
520 					cc = j + 1;
521 				}
522 				buf[cc - 1] = '\n';
523 				buf[cc] = '\0';
524 			}
525 		}
526 		if (fwrite(buf, cc, 1, to) <= 0) {
527 			(void) fclose(from);
528 			(void) fclose(to);
529 			(void) unlink(f);
530 			warn("can't create gid: short write to `%s'", f);
531 			return 0;
532 		}
533 	}
534 	(void) fclose(from);
535 	(void) fclose(to);
536 	if (rename(f, _PATH_GROUP) < 0) {
537 		warn("can't create gid: can't rename `%s' to `%s'", f, _PATH_GROUP);
538 		return 0;
539 	}
540 	(void) chmod(_PATH_GROUP, st.st_mode & 07777);
541 	return 1;
542 }
543 
544 /* return 1 if `login' is a valid login name */
545 static int
546 valid_login(char *login)
547 {
548 	char	*cp;
549 
550 	for (cp = login ; *cp ; cp++) {
551 		if (!isalnum(*cp) && *cp != '.' && *cp != '_' && *cp != '-') {
552 			return 0;
553 		}
554 	}
555 	return 1;
556 }
557 
558 /* return 1 if `group' is a valid group name */
559 static int
560 valid_group(char *group)
561 {
562 	char	*cp;
563 
564 	for (cp = group ; *cp ; cp++) {
565 		if (!isalnum(*cp)) {
566 			return 0;
567 		}
568 	}
569 	return 1;
570 }
571 
572 /* find the next gid in the range lo .. hi */
573 static int
574 getnextgid(uid_t *gidp, uid_t lo, uid_t hi)
575 {
576 	for (*gidp = lo ; *gidp < hi ; *gidp += 1) {
577 		if (getgrgid((gid_t)*gidp) == NULL) {
578 			return 1;
579 		}
580 	}
581 	return 0;
582 }
583 
584 #ifdef EXTENSIONS
585 /* save a range of uids */
586 static int
587 save_range(user_t *up, char *cp)
588 {
589 	int	from;
590 	int	to;
591 	int	i;
592 
593 	if (up->u_rsize == 0) {
594 		up->u_rsize = 32;
595 		NEWARRAY(range_t, up->u_rv, up->u_rsize, return(0));
596 	} else if (up->u_rc == up->u_rsize) {
597 		up->u_rsize *= 2;
598 		RENEW(range_t, up->u_rv, up->u_rsize, return(0));
599 	}
600 	if (up->u_rv && sscanf(cp, "%d..%d", &from, &to) == 2) {
601 		for (i = up->u_defrc ; i < up->u_rc ; i++) {
602 			if (up->u_rv[i].r_from == from && up->u_rv[i].r_to == to) {
603 				break;
604 			}
605 		}
606 		if (i == up->u_rc) {
607 			up->u_rv[up->u_rc].r_from = from;
608 			up->u_rv[up->u_rc].r_to = to;
609 			up->u_rc += 1;
610 		}
611 	} else {
612 		warnx("Bad range `%s'", cp);
613 		return 0;
614 	}
615 	return 1;
616 }
617 #endif
618 
619 /* set the defaults in the defaults file */
620 static int
621 setdefaults(user_t *up)
622 {
623 	char	template[MaxFileNameLen];
624 	FILE	*fp;
625 	int	ret;
626 	int	fd;
627 #ifdef EXTENSIONS
628 	int	i;
629 #endif
630 
631 	(void) snprintf(template, sizeof(template), "%s.XXXXXXXX", CONFFILE);
632 	if ((fd = mkstemp(template)) < 0) {
633 		warnx("can't mkstemp `%s' for writing", CONFFILE);
634 		return 0;
635 	}
636 	if ((fp = fdopen(fd, "w")) == NULL) {
637 		warn("can't fdopen `%s' for writing", CONFFILE);
638 		return 0;
639 	}
640 	ret = 1;
641 	if (fprintf(fp, "group\t\t%s\n", up->u_primgrp) <= 0 ||
642 	    fprintf(fp, "base_dir\t%s\n", up->u_basedir) <= 0 ||
643 	    fprintf(fp, "skel_dir\t%s\n", up->u_skeldir) <= 0 ||
644 	    fprintf(fp, "shell\t\t%s\n", up->u_shell) <= 0 ||
645 #ifdef EXTENSIONS
646 	    fprintf(fp, "class\t\t%s\n", up->u_class) <= 0 ||
647 #endif
648 	    fprintf(fp, "inactive\t%d\n", up->u_inactive) <= 0 ||
649 	    fprintf(fp, "expire\t\t%s\n", (up->u_expire == NULL) ? UNSET_EXPIRY : up->u_expire) <= 0 ||
650 	    fprintf(fp, "preserve\t%s\n", (up->u_preserve == 0) ? "false" : "true") <= 0) {
651 		warn("can't write to `%s'", CONFFILE);
652 		ret = 0;
653 	}
654 #ifdef EXTENSIONS
655 	for (i = (up->u_defrc != up->u_rc) ? up->u_defrc : 0 ; i < up->u_rc ; i++) {
656 		if (fprintf(fp, "range\t\t%d..%d\n", up->u_rv[i].r_from, up->u_rv[i].r_to) <= 0) {
657 			warn("can't write to `%s'", CONFFILE);
658 			ret = 0;
659 		}
660 	}
661 #endif
662 	(void) fclose(fp);
663 	if (ret) {
664 		ret = ((rename(template, CONFFILE) == 0) && (chmod(CONFFILE, 0644) == 0));
665 	}
666 	return ret;
667 }
668 
669 /* read the defaults file */
670 static void
671 read_defaults(user_t *up)
672 {
673 	struct stat	st;
674 	size_t		lineno;
675 	size_t		len;
676 	FILE		*fp;
677 	char		*cp;
678 	char		*s;
679 
680 	memsave(&up->u_primgrp, DEF_GROUP, strlen(DEF_GROUP));
681 	memsave(&up->u_basedir, DEF_BASEDIR, strlen(DEF_BASEDIR));
682 	memsave(&up->u_skeldir, DEF_SKELDIR, strlen(DEF_SKELDIR));
683 	memsave(&up->u_shell, DEF_SHELL, strlen(DEF_SHELL));
684 	memsave(&up->u_comment, DEF_COMMENT, strlen(DEF_COMMENT));
685 #ifdef EXTENSIONS
686 	memsave(&up->u_class, DEF_CLASS, strlen(DEF_CLASS));
687 #endif
688 	up->u_rsize = 16;
689 	up->u_defrc = 0;
690 	NEWARRAY(range_t, up->u_rv, up->u_rsize, exit(1));
691 	up->u_inactive = DEF_INACTIVE;
692 	up->u_expire = DEF_EXPIRE;
693 	if ((fp = fopen(CONFFILE, "r")) == NULL) {
694 		if (stat(CONFFILE, &st) < 0 && !setdefaults(up)) {
695 			warn("can't create `%s' defaults file", CONFFILE);
696 		}
697 		fp = fopen(CONFFILE, "r");
698 	}
699 	if (fp != NULL) {
700 		while ((s = fparseln(fp, &len, &lineno, NULL, 0)) != NULL) {
701 			if (strncmp(s, "group", 5) == 0) {
702 				for (cp = s + 5 ; *cp && isspace(*cp) ; cp++) {
703 				}
704 				memsave(&up->u_primgrp, cp, strlen(cp));
705 			} else if (strncmp(s, "base_dir", 8) == 0) {
706 				for (cp = s + 8 ; *cp && isspace(*cp) ; cp++) {
707 				}
708 				memsave(&up->u_basedir, cp, strlen(cp));
709 			} else if (strncmp(s, "skel_dir", 8) == 0) {
710 				for (cp = s + 8 ; *cp && isspace(*cp) ; cp++) {
711 				}
712 				memsave(&up->u_skeldir, cp, strlen(cp));
713 			} else if (strncmp(s, "shell", 5) == 0) {
714 				for (cp = s + 5 ; *cp && isspace(*cp) ; cp++) {
715 				}
716 				memsave(&up->u_shell, cp, strlen(cp));
717 			} else if (strncmp(s, "password", 8) == 0) {
718 				for (cp = s + 8 ; *cp && isspace(*cp) ; cp++) {
719 				}
720 				memsave(&up->u_password, cp, strlen(cp));
721 #ifdef EXTENSIONS
722 			} else if (strncmp(s, "class", 5) == 0) {
723 				for (cp = s + 5 ; *cp && isspace(*cp) ; cp++) {
724 				}
725 				memsave(&up->u_class, cp, strlen(cp));
726 #endif
727 			} else if (strncmp(s, "inactive", 8) == 0) {
728 				for (cp = s + 8 ; *cp && isspace(*cp) ; cp++) {
729 				}
730 				up->u_inactive = atoi(cp);
731 #ifdef EXTENSIONS
732 			} else if (strncmp(s, "range", 5) == 0) {
733 				for (cp = s + 5 ; *cp && isspace(*cp) ; cp++) {
734 				}
735 				(void) save_range(up, cp);
736 #endif
737 #ifdef EXTENSIONS
738 			} else if (strncmp(s, "preserve", 8) == 0) {
739 				for (cp = s + 8 ; *cp && isspace(*cp) ; cp++) {
740 				}
741 				up->u_preserve = (strncmp(cp, "true", 4) == 0) ? 1 :
742 						  (strncmp(cp, "yes", 3) == 0) ? 1 :
743 						   atoi(cp);
744 #endif
745 			} else if (strncmp(s, "expire", 6) == 0) {
746 				for (cp = s + 6 ; *cp && isspace(*cp) ; cp++) {
747 				}
748 				if (strcmp(cp, UNSET_EXPIRY) == 0) {
749 					if (up->u_expire) {
750 						FREE(up->u_expire);
751 					}
752 					up->u_expire = NULL;
753 				} else {
754 					memsave(&up->u_expire, cp, strlen(cp));
755 				}
756 			}
757 			(void) free(s);
758 		}
759 		(void) fclose(fp);
760 	}
761 	if (up->u_rc == 0) {
762 		up->u_rv[up->u_rc].r_from = DEF_LOWUID;
763 		up->u_rv[up->u_rc].r_to = DEF_HIGHUID;
764 		up->u_rc += 1;
765 	}
766 	up->u_defrc = up->u_rc;
767 }
768 
769 /* return the next valid unused uid */
770 static int
771 getnextuid(int sync_uid_gid, uid_t *uid, uid_t low_uid, uid_t high_uid)
772 {
773 	for (*uid = low_uid ; *uid <= high_uid ; (*uid)++) {
774 		if (getpwuid((uid_t)(*uid)) == NULL && *uid != NOBODY_UID) {
775 			if (sync_uid_gid) {
776 				if (getgrgid((gid_t)(*uid)) == NULL) {
777 					return 1;
778 				}
779 			} else {
780 				return 1;
781 			}
782 		}
783 	}
784 	return 0;
785 }
786 
787 /* add a user */
788 static int
789 adduser(char *login, user_t *up)
790 {
791 	struct group	*grp;
792 	struct stat	st;
793 	struct tm	tm;
794 	time_t		expire;
795 	char		password[PasswordLength + 1];
796 	char		home[MaxFileNameLen];
797 	char		buf[LINE_MAX];
798 	int		sync_uid_gid;
799 	int		masterfd;
800 	int		ptmpfd;
801 	gid_t		gid;
802 	int		cc;
803 	int		i;
804 
805 	if (!valid_login(login)) {
806 		errx(EXIT_FAILURE, "`%s' is not a valid login name", login);
807 	}
808 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
809 		err(EXIT_FAILURE, "can't open `%s'", _PATH_MASTERPASSWD);
810 	}
811 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
812 		err(EXIT_FAILURE, "can't lock `%s'", _PATH_MASTERPASSWD);
813 	}
814 	pw_init();
815 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
816 		(void) close(masterfd);
817 		err(EXIT_FAILURE, "can't obtain pw_lock");
818 	}
819 	while ((cc = read(masterfd, buf, sizeof(buf))) > 0) {
820 		if (write(ptmpfd, buf, (size_t)(cc)) != cc) {
821 			(void) close(masterfd);
822 			(void) close(ptmpfd);
823 			(void) pw_abort();
824 			err(EXIT_FAILURE, "short write to /etc/ptmp (not %d chars)", cc);
825 		}
826 	}
827 	/* if no uid was specified, get next one in [low_uid..high_uid] range */
828 	sync_uid_gid = (strcmp(up->u_primgrp, "=uid") == 0);
829 	if (up->u_uid == UID_MAX) {
830 		for (i = 0 ; i < up->u_rc ; i++) {
831 			if (getnextuid(sync_uid_gid, &up->u_uid, up->u_rv[i].r_from, up->u_rv[i].r_to)) {
832 				break;
833 			}
834 		}
835 		if (i == up->u_rc) {
836 			(void) close(ptmpfd);
837 			(void) pw_abort();
838 			errx(EXIT_FAILURE, "can't get next uid for %u", up->u_uid);
839 		}
840 	}
841 	/* check uid isn't already allocated */
842 	if (!(up->u_flags & F_DUPUID) && getpwuid((uid_t)(up->u_uid)) != NULL) {
843 		(void) close(ptmpfd);
844 		(void) pw_abort();
845 		errx(EXIT_FAILURE, "uid %u is already in use", up->u_uid);
846 	}
847 	/* if -g=uid was specified, check gid is unused */
848 	if (sync_uid_gid) {
849 		if (getgrgid((gid_t)(up->u_uid)) != NULL) {
850 			(void) close(ptmpfd);
851 			(void) pw_abort();
852 			errx(EXIT_FAILURE, "gid %u is already in use", up->u_uid);
853 		}
854 		gid = up->u_uid;
855 	} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
856 		gid = grp->gr_gid;
857 	} else if (is_number(up->u_primgrp) &&
858 		   (grp = getgrgid((gid_t)atoi(up->u_primgrp))) != NULL) {
859 		gid = grp->gr_gid;
860 	} else {
861 		(void) close(ptmpfd);
862 		(void) pw_abort();
863 		errx(EXIT_FAILURE, "group %s not found", up->u_primgrp);
864 	}
865 	/* check name isn't already in use */
866 	if (!(up->u_flags & F_DUPUID) && getpwnam(login) != NULL) {
867 		(void) close(ptmpfd);
868 		(void) pw_abort();
869 		errx(EXIT_FAILURE, "already a `%s' user", login);
870 	}
871 	if (up->u_flags & F_HOMEDIR) {
872 		(void) strlcpy(home, up->u_home, sizeof(home));
873 	} else {
874 		/* if home directory hasn't been given, make it up */
875 		(void) snprintf(home, sizeof(home), "%s/%s", up->u_basedir, login);
876 	}
877 	expire = 0;
878 	if (up->u_expire != NULL) {
879 		(void) memset(&tm, 0, sizeof(tm));
880 		if (strptime(up->u_expire, "%c", &tm) == NULL) {
881 			warnx("invalid time format `%s'", optarg);
882 		} else {
883 			expire = mktime(&tm);
884 		}
885 	}
886 	if (lstat(home, &st) < 0 && !(up->u_flags & F_MKDIR)) {
887 		warnx("Warning: home directory `%s' doesn't exist, and -m was"
888 		    " not specified", home);
889 	}
890 	if (up->u_password != NULL &&
891 	    strlen(up->u_password) <= PasswordLength) {
892 		(void) strlcpy(password, up->u_password, sizeof(password));
893 	} else {
894 		(void) strlcpy(password, "*", sizeof(password));
895 		if (up->u_password != NULL) {
896 			warnx("Password `%s' is invalid: setting it to `%s'",
897 				up->u_password, password);
898 		}
899 	}
900 
901 	cc = snprintf(buf, sizeof(buf), "%s:%s:%u:%u:%s:%d:%ld:%s:%s:%s\n",
902 			login,
903 			password,
904 			up->u_uid,
905 			gid,
906 #ifdef EXTENSIONS
907 			up->u_class,
908 #else
909 			"",
910 #endif
911 			up->u_inactive,
912 			(long) expire,
913 			up->u_comment,
914 			home,
915 			up->u_shell);
916 	if (cc >= sizeof(buf) || cc == -1 ||
917 	    (strchr(up->u_comment, '&') != NULL &&
918 	     cc + strlen(login) >= sizeof(buf))) {
919 		(void) close(ptmpfd);
920 		(void) pw_abort();
921 		errx(EXIT_FAILURE, "can't add `%s', line too long", buf);
922 	}
923 	if (write(ptmpfd, buf, (size_t) cc) != cc) {
924 		(void) close(ptmpfd);
925 		(void) pw_abort();
926 		err(EXIT_FAILURE, "can't add `%s'", buf);
927 	}
928 	if (up->u_flags & F_MKDIR) {
929 		if (lstat(home, &st) == 0) {
930 			(void) close(ptmpfd);
931 			(void) pw_abort();
932 			errx(EXIT_FAILURE, "home directory `%s' already exists",
933 			    home);
934 		} else {
935 			if (asystem("%s -p %s", MKDIR, home) != 0) {
936 				(void) close(ptmpfd);
937 				(void) pw_abort();
938 				err(EXIT_FAILURE, "can't mkdir `%s'", home);
939 			}
940 			(void) copydotfiles(up->u_skeldir, up->u_uid, gid, home);
941 		}
942 	}
943 	if (strcmp(up->u_primgrp, "=uid") == 0 && getgrnam(login) == NULL &&
944 	    !creategid(login, gid, login)) {
945 		(void) close(ptmpfd);
946 		(void) pw_abort();
947 		errx(EXIT_FAILURE, "can't create gid %d for login name %s",
948 		    gid, login);
949 	}
950 	if (up->u_groupc > 0 && !append_group(login, up->u_groupc, up->u_groupv)) {
951 		(void) close(ptmpfd);
952 		(void) pw_abort();
953 		errx(EXIT_FAILURE, "can't append `%s' to new groups", login);
954 	}
955 	(void) close(ptmpfd);
956 	if (pw_mkdb(login, 0) < 0) {
957 		err(EXIT_FAILURE, "pw_mkdb failed");
958 	}
959 	return 1;
960 }
961 
962 /* modify a user */
963 static int
964 moduser(char *login, char *newlogin, user_t *up)
965 {
966 	struct passwd	*pwp;
967 	struct group	*grp;
968 	struct tm	tm;
969 	const char	*homedir;
970 	char		buf[LINE_MAX];
971 	size_t		colonc, len, loginc;
972 	size_t		cc;
973 	FILE		*master;
974 	char		newdir[MaxFileNameLen];
975 	char		*colon, *line;
976 	int		masterfd;
977 	int		ptmpfd;
978 	int		rval;
979 
980 	if (!valid_login(newlogin)) {
981 		errx(EXIT_FAILURE, "`%s' is not a valid login name", login);
982 	}
983 	if ((pwp = getpwnam(login)) == NULL) {
984 		errx(EXIT_FAILURE, "No such user `%s'", login);
985 	}
986 	/* keep dir name in case we need it for '-m' */
987 	homedir = pwp->pw_dir;
988 
989 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
990 		err(EXIT_FAILURE, "can't open `%s'", _PATH_MASTERPASSWD);
991 	}
992 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
993 		err(EXIT_FAILURE, "can't lock `%s'", _PATH_MASTERPASSWD);
994 	}
995 	pw_init();
996 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
997 		(void) close(masterfd);
998 		err(EXIT_FAILURE, "can't obtain pw_lock");
999 	}
1000 	if ((master = fdopen(masterfd, "r")) == NULL) {
1001 		(void) close(masterfd);
1002 		(void) close(ptmpfd);
1003 		(void) pw_abort();
1004 		err(EXIT_FAILURE, "can't fdopen fd for %s", _PATH_MASTERPASSWD);
1005 	}
1006 	if (up != NULL) {
1007 		if (up->u_flags & F_USERNAME) {
1008 			/* if changing name, check new name isn't already in use */
1009 			if (strcmp(login, newlogin) != 0 && getpwnam(newlogin) != NULL) {
1010 				(void) close(ptmpfd);
1011 				(void) pw_abort();
1012 				errx(EXIT_FAILURE, "already a `%s' user", newlogin);
1013 			}
1014 			pwp->pw_name = newlogin;
1015 
1016 			/*
1017 			 * Provide a new directory name in case the
1018 			 * home directory is to be moved.
1019 			 */
1020 			if (up->u_flags & F_MKDIR) {
1021 				(void) snprintf(newdir, sizeof(newdir),
1022 				    "%s/%s", up->u_basedir, newlogin);
1023 				pwp->pw_dir = newdir;
1024 			}
1025 		}
1026 		if (up->u_flags & F_PASSWORD) {
1027 			if (up->u_password != NULL && strlen(up->u_password) <= PasswordLength)
1028 				pwp->pw_passwd = up->u_password;
1029 		}
1030 		if (up->u_flags & F_UID) {
1031 			/* check uid isn't already allocated */
1032 			if (!(up->u_flags & F_DUPUID) && getpwuid((uid_t)(up->u_uid)) != NULL) {
1033 				(void) close(ptmpfd);
1034 				(void) pw_abort();
1035 				errx(EXIT_FAILURE, "uid %u is already in use", up->u_uid);
1036 			}
1037 			pwp->pw_uid = up->u_uid;
1038 		}
1039 		if (up->u_flags & F_GROUP) {
1040 			/* if -g=uid was specified, check gid is unused */
1041 			if (strcmp(up->u_primgrp, "=uid") == 0) {
1042 				if (getgrgid((gid_t)(up->u_uid)) != NULL) {
1043 					(void) close(ptmpfd);
1044 					(void) pw_abort();
1045 					errx(EXIT_FAILURE, "gid %u is already in use", up->u_uid);
1046 				}
1047 				pwp->pw_gid = up->u_uid;
1048 			} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
1049 				pwp->pw_gid = grp->gr_gid;
1050 			} else if (is_number(up->u_primgrp) &&
1051 				   (grp = getgrgid((gid_t)atoi(up->u_primgrp))) != NULL) {
1052 				pwp->pw_gid = grp->gr_gid;
1053 			} else {
1054 				(void) close(ptmpfd);
1055 				(void) pw_abort();
1056 				errx(EXIT_FAILURE, "group %s not found", up->u_primgrp);
1057 			}
1058 		}
1059 		if (up->u_flags |= F_INACTIVE)
1060 			pwp->pw_change = up->u_inactive;
1061 		if (up->u_flags & F_EXPIRE) {
1062 			(void) memset(&tm, 0, sizeof(tm));
1063 			if (strptime(up->u_expire, "%c", &tm) == NULL)
1064 				warnx("invalid time format `%s'", optarg);
1065 			else
1066 				pwp->pw_expire = mktime(&tm);
1067 		}
1068 		if (up->u_flags & F_COMMENT)
1069 			pwp->pw_gecos = up->u_comment;
1070 		if (up->u_flags & F_HOMEDIR)
1071 			pwp->pw_dir = up->u_home;
1072 		if (up->u_flags & F_SHELL)
1073 			pwp->pw_shell = up->u_shell;
1074 #ifdef EXTENSIONS
1075 		if (up->u_flags & F_CLASS)
1076 			pwp->pw_class = up->u_class;
1077 #endif
1078 	}
1079 	loginc = strlen(login);
1080 	while ((line = fgetln(master, &len)) != NULL) {
1081 		if ((colon = strchr(line, ':')) == NULL) {
1082 			warnx("Malformed entry `%s'. Skipping", line);
1083 			continue;
1084 		}
1085 		colonc = (size_t)(colon - line);
1086 		if (strncmp(login, line, loginc) == 0 && loginc == colonc) {
1087 			if (up != NULL) {
1088 				len = snprintf(buf, sizeof(buf),
1089 					"%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
1090 					newlogin,
1091 					pwp->pw_passwd,
1092 					pwp->pw_uid,
1093 					pwp->pw_gid,
1094 #ifdef EXTENSIONS
1095 					pwp->pw_class,
1096 #else
1097 					"",
1098 #endif
1099 					(long)pwp->pw_change,
1100 					(long)pwp->pw_expire,
1101 					pwp->pw_gecos,
1102 					pwp->pw_dir,
1103 					pwp->pw_shell);
1104 				if (len >= sizeof(buf) ||
1105 				    (strchr(up->u_comment, '&') != NULL &&
1106 				    len + strlen(newlogin) >= sizeof(buf))) {
1107 					(void) close(ptmpfd);
1108 					(void) pw_abort();
1109 					errx(EXIT_FAILURE, "can't add `%s', line too long (%d bytes)", buf, len + strlen(newlogin));
1110 				}
1111 				if (write(ptmpfd, buf, len) != len) {
1112 					(void) close(ptmpfd);
1113 					(void) pw_abort();
1114 					err(EXIT_FAILURE, "can't add `%s'", buf);
1115 				}
1116 			}
1117 		} else if ((cc = write(ptmpfd, line, len)) != len) {
1118 			(void) close(masterfd);
1119 			(void) close(ptmpfd);
1120 			(void) pw_abort();
1121 			err(EXIT_FAILURE, "short write to /etc/ptmp (%lld not %lld chars)",
1122 			    (long long)cc, (long long)len);
1123 		}
1124 	}
1125 	if (up != NULL) {
1126 		if ((up->u_flags & F_MKDIR) &&
1127 		    asystem("%s %s %s", MV, homedir, pwp->pw_dir) != 0) {
1128 			(void) close(ptmpfd);
1129 			(void) pw_abort();
1130 			err(EXIT_FAILURE, "can't move `%s' to `%s'",
1131 			    homedir, pwp->pw_dir);
1132 		}
1133 		if (up->u_groupc > 0 &&
1134 		    !append_group(newlogin, up->u_groupc, up->u_groupv)) {
1135 			(void) close(ptmpfd);
1136 			 (void) pw_abort();
1137 			 errx(EXIT_FAILURE, "can't append `%s' to new groups",
1138 			    newlogin);
1139 		}
1140 	}
1141 	(void) close(ptmpfd);
1142 	if (up != NULL && strcmp(login, newlogin) == 0)
1143 		rval = pw_mkdb(login, 0);
1144 	else
1145 		rval = pw_mkdb(NULL, 0);
1146 	if (rval == -1)
1147 		err(EXIT_FAILURE, "pw_mkdb failed");
1148 
1149 	return 1;
1150 }
1151 
1152 
1153 #ifdef EXTENSIONS
1154 /* see if we can find out the user struct */
1155 static struct passwd *
1156 find_user_info(char *name)
1157 {
1158 	struct passwd	*pwp;
1159 
1160 	if ((pwp = getpwnam(name)) != NULL) {
1161 		return pwp;
1162 	}
1163 	if (is_number(name) && (pwp = getpwuid((uid_t)atoi(name))) != NULL) {
1164 		return pwp;
1165 	}
1166 	return NULL;
1167 }
1168 #endif
1169 
1170 #ifdef EXTENSIONS
1171 /* see if we can find out the group struct */
1172 static struct group *
1173 find_group_info(char *name)
1174 {
1175 	struct group	*grp;
1176 
1177 	if ((grp = getgrnam(name)) != NULL) {
1178 		return grp;
1179 	}
1180 	if (is_number(name) && (grp = getgrgid((gid_t)atoi(name))) != NULL) {
1181 		return grp;
1182 	}
1183 	return NULL;
1184 }
1185 #endif
1186 
1187 /* print out usage message, and then exit */
1188 void
1189 usermgmt_usage(const char *prog)
1190 {
1191 	if (strcmp(prog, "useradd") == 0) {
1192 		(void) fprintf(stderr, "usage: %s -D [-b basedir] [-e expiry] "
1193 		    "[-f changetime] [-g group]\n\t\t[-k skeletondir] "
1194 		    "[-r low..high] [-s shell] [-L class]\n", prog);
1195 		(void) fprintf(stderr, "usage: %s [-mov] [-G group[,group,...]]"
1196 		    " [-b basedir] [-c comment]\n\t\t"
1197 		    "[-d homedir] [-e expiry] [-f changetime] [-g group]\n\t\t"
1198 		    "[-k skeletondir] [-p password] "
1199 		    "[-r lowuid..highuid]\n\t\t[-s shell] [-u uid] [-L class] "
1200 		    "user\n", prog);
1201 	} else if (strcmp(prog, "usermod") == 0) {
1202 		(void) fprintf(stderr, "usage: %s [-mov] [-G group[,group,...]]"
1203 		    " [-c comment] [-d homedir]\n\t\t"
1204 		    "[-e expire] [-f changetime] [-g group] [-l newname]\n\t\t"
1205 		    "[-p password] [-s shell] [-u uid] [-L class] user\n",
1206 		    prog);
1207 	} else if (strcmp(prog, "userdel") == 0) {
1208 		(void) fprintf(stderr, "usage: %s -D [-p preserve]\n", prog);
1209 		(void) fprintf(stderr, "usage: %s [-prv] user\n", prog);
1210 #ifdef EXTENSIONS
1211 	} else if (strcmp(prog, "userinfo") == 0) {
1212 		(void) fprintf(stderr, "usage: %s [-ev] user\n", prog);
1213 #endif
1214 	} else if (strcmp(prog, "groupadd") == 0) {
1215 		(void) fprintf(stderr, "usage: %s [-ov] [-g gid] group\n",
1216 		    prog);
1217 	} else if (strcmp(prog, "groupdel") == 0) {
1218 		(void) fprintf(stderr, "usage: %s [-v] group\n", prog);
1219 	} else if (strcmp(prog, "groupmod") == 0) {
1220 		(void) fprintf(stderr, "usage: %s [-ov] [-g gid] [-n newname] "
1221 		    "group\n", prog);
1222 	} else if (strcmp(prog, "user") == 0 || strcmp(prog, "group") == 0) {
1223 		(void) fprintf(stderr, "usage: %s [ add | del | mod "
1224 #ifdef EXTENSIONS
1225 		"| info "
1226 #endif
1227 		"] ...\n",
1228 		    prog);
1229 #ifdef EXTENSIONS
1230 	} else if (strcmp(prog, "groupinfo") == 0) {
1231 		(void) fprintf(stderr, "usage: %s [-ev] group\n", prog);
1232 #endif
1233 	} else {
1234 		(void) fprintf(stderr, "This program must be called as {user,group}{add,del,mod,info},\n%s is not an understood name.\n", prog);
1235 	}
1236 	exit(EXIT_FAILURE);
1237 	/* NOTREACHED */
1238 }
1239 
1240 #ifdef EXTENSIONS
1241 #define ADD_OPT_EXTENSIONS	"p:r:vL:"
1242 #else
1243 #define ADD_OPT_EXTENSIONS
1244 #endif
1245 
1246 int
1247 useradd(int argc, char **argv)
1248 {
1249 	user_t	u;
1250 	int	defaultfield;
1251 	int	bigD;
1252 	int	c;
1253 #ifdef EXTENSIONS
1254 	int	i;
1255 #endif
1256 
1257 	(void) memset(&u, 0, sizeof(u));
1258 	read_defaults(&u);
1259 	u.u_uid = UID_MAX;
1260 	defaultfield = bigD = 0;
1261 	while ((c = getopt(argc, argv, "DG:b:c:d:e:f:g:k:mou:s:" ADD_OPT_EXTENSIONS)) != -1) {
1262 		switch(c) {
1263 		case 'D':
1264 			bigD = 1;
1265 			break;
1266 		case 'G':
1267 			while ((u.u_groupv[u.u_groupc] = strsep(&optarg, ",")) != NULL &&
1268 			    u.u_groupc < NGROUPS_MAX - 2) {
1269 				if (u.u_groupv[u.u_groupc][0] != 0) {
1270 					u.u_groupc++;
1271 				}
1272 			}
1273 			if (optarg != NULL) {
1274 				warnx("Truncated list of secondary groups to %d entries", NGROUPS_MAX - 2);
1275 			}
1276 			break;
1277 		case 'b':
1278 			defaultfield = 1;
1279 			memsave(&u.u_basedir, optarg, strlen(optarg));
1280 			break;
1281 		case 'c':
1282 			memsave(&u.u_comment, optarg, strlen(optarg));
1283 			break;
1284 		case 'd':
1285 			memsave(&u.u_home, optarg, strlen(optarg));
1286 			u.u_flags |= F_HOMEDIR;
1287 			break;
1288 		case 'e':
1289 			defaultfield = 1;
1290 			memsave(&u.u_expire, optarg, strlen(optarg));
1291 			break;
1292 		case 'f':
1293 			defaultfield = 1;
1294 			u.u_inactive = atoi(optarg);
1295 			break;
1296 		case 'g':
1297 			defaultfield = 1;
1298 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1299 			break;
1300 		case 'k':
1301 			memsave(&u.u_skeldir, optarg, strlen(optarg));
1302 			break;
1303 #ifdef EXTENSIONS
1304 		case 'L':
1305 			defaultfield = 1;
1306 			memsave(&u.u_class, optarg, strlen(optarg));
1307 			break;
1308 #endif
1309 		case 'm':
1310 			u.u_flags |= F_MKDIR;
1311 			break;
1312 		case 'o':
1313 			u.u_flags |= F_DUPUID;
1314 			break;
1315 #ifdef EXTENSIONS
1316 		case 'p':
1317 			memsave(&u.u_password, optarg, strlen(optarg));
1318 			break;
1319 #endif
1320 #ifdef EXTENSIONS
1321 		case 'r':
1322 			defaultfield = 1;
1323 			(void) save_range(&u, optarg);
1324 			break;
1325 #endif
1326 		case 's':
1327 			defaultfield = 1;
1328 			memsave(&u.u_shell, optarg, strlen(optarg));
1329 			break;
1330 		case 'u':
1331 			if (!is_number(optarg)) {
1332 				errx(EXIT_FAILURE, "When using [-u uid], the uid must be numeric");
1333 			}
1334 			u.u_uid = atoi(optarg);
1335 			break;
1336 #ifdef EXTENSIONS
1337 		case 'v':
1338 			verbose = 1;
1339 			break;
1340 #endif
1341 		}
1342 	}
1343 	if (bigD) {
1344 		if (defaultfield) {
1345 			checkeuid();
1346 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
1347 		}
1348 		(void) printf("group\t\t%s\n", u.u_primgrp);
1349 		(void) printf("base_dir\t%s\n", u.u_basedir);
1350 		(void) printf("skel_dir\t%s\n", u.u_skeldir);
1351 		(void) printf("shell\t\t%s\n", u.u_shell);
1352 #ifdef EXTENSIONS
1353 		(void) printf("class\t\t%s\n", u.u_class);
1354 #endif
1355 		(void) printf("inactive\t%d\n", u.u_inactive);
1356 		(void) printf("expire\t\t%s\n", (u.u_expire == NULL) ? UNSET_EXPIRY : u.u_expire);
1357 #ifdef EXTENSIONS
1358 		for (i = 0 ; i < u.u_rc ; i++) {
1359 			(void) printf("range\t\t%d..%d\n", u.u_rv[i].r_from, u.u_rv[i].r_to);
1360 		}
1361 #endif
1362 		return EXIT_SUCCESS;
1363 	}
1364 	argc -= optind;
1365 	argv += optind;
1366 	if (argc != 1) {
1367 		usermgmt_usage("useradd");
1368 	}
1369 	checkeuid();
1370 	return adduser(*argv, &u) ? EXIT_SUCCESS : EXIT_FAILURE;
1371 }
1372 
1373 #ifdef EXTENSIONS
1374 #define MOD_OPT_EXTENSIONS	"p:vL:"
1375 #else
1376 #define MOD_OPT_EXTENSIONS
1377 #endif
1378 
1379 int
1380 usermod(int argc, char **argv)
1381 {
1382 	user_t	u;
1383 	char	newuser[MaxUserNameLen + 1];
1384 	int	c, have_new_user;
1385 
1386 	(void) memset(&u, 0, sizeof(u));
1387 	(void) memset(newuser, 0, sizeof(newuser));
1388 	read_defaults(&u);
1389 	free(u.u_primgrp);
1390 	u.u_primgrp = NULL;
1391 	have_new_user = 0;
1392 	while ((c = getopt(argc, argv, "G:c:d:e:f:g:l:mos:u:" MOD_OPT_EXTENSIONS)) != -1) {
1393 		switch(c) {
1394 		case 'G':
1395 			while ((u.u_groupv[u.u_groupc] = strsep(&optarg, ",")) != NULL &&
1396 			    u.u_groupc < NGROUPS_MAX - 2) {
1397 				if (u.u_groupv[u.u_groupc][0] != 0) {
1398 					u.u_groupc++;
1399 				}
1400 			}
1401 			if (optarg != NULL) {
1402 			  	warnx("Truncated list of secondary groups to %d entries", NGROUPS_MAX - 2);
1403 			}
1404 			u.u_flags |= F_SECGROUP;
1405 			break;
1406 		case 'c':
1407 			memsave(&u.u_comment, optarg, strlen(optarg));
1408 			u.u_flags |= F_COMMENT;
1409 			break;
1410 		case 'd':
1411 			memsave(&u.u_home, optarg, strlen(optarg));
1412 			u.u_flags |= F_HOMEDIR;
1413 			break;
1414 		case 'e':
1415 			memsave(&u.u_expire, optarg, strlen(optarg));
1416 			u.u_flags |= F_EXPIRE;
1417 			break;
1418 		case 'f':
1419 			u.u_inactive = atoi(optarg);
1420 			u.u_flags |= F_INACTIVE;
1421 			break;
1422 		case 'g':
1423 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1424 			u.u_flags |= F_GROUP;
1425 			break;
1426 		case 'l':
1427 			(void) strlcpy(newuser, optarg, sizeof(newuser));
1428 			have_new_user = 1;
1429 			u.u_flags |= F_USERNAME;
1430 			break;
1431 #ifdef EXTENSIONS
1432 		case 'L':
1433 			memsave(&u.u_class, optarg, strlen(optarg));
1434 			u.u_flags |= F_CLASS;
1435 			break;
1436 #endif
1437 		case 'm':
1438 			u.u_flags |= F_MKDIR;
1439 			break;
1440 		case 'o':
1441 			u.u_flags |= F_DUPUID;
1442 			break;
1443 #ifdef EXTENSIONS
1444 		case 'p':
1445 			memsave(&u.u_password, optarg, strlen(optarg));
1446 			u.u_flags |= F_PASSWORD;
1447 			break;
1448 #endif
1449 		case 's':
1450 			memsave(&u.u_shell, optarg, strlen(optarg));
1451 			u.u_flags |= F_SHELL;
1452 			break;
1453 		case 'u':
1454 			if (!is_number(optarg)) {
1455 				errx(EXIT_FAILURE, "When using [-u uid], the uid must be numeric");
1456 			}
1457 			u.u_uid = atoi(optarg);
1458 			u.u_flags |= F_UID;
1459 			break;
1460 #ifdef EXTENSIONS
1461 		case 'v':
1462 			verbose = 1;
1463 			break;
1464 #endif
1465 		}
1466 	}
1467 	if ((u.u_flags & F_MKDIR) && !(u.u_flags & F_HOMEDIR) &&
1468 	    !(u.u_flags & F_USERNAME)) {
1469 		warnx("option 'm' useless without 'd' or 'l' -- ignored");
1470 		u.u_flags &= ~F_MKDIR;
1471 	}
1472 	argc -= optind;
1473 	argv += optind;
1474 	if (argc != 1) {
1475 		usermgmt_usage("usermod");
1476 	}
1477 	checkeuid();
1478 	return moduser(*argv, (have_new_user) ? newuser : *argv, &u) ?
1479 	    EXIT_SUCCESS : EXIT_FAILURE;
1480 }
1481 
1482 #ifdef EXTENSIONS
1483 #define DEL_OPT_EXTENSIONS	"Dp:v"
1484 #else
1485 #define DEL_OPT_EXTENSIONS
1486 #endif
1487 
1488 int
1489 userdel(int argc, char **argv)
1490 {
1491 	struct passwd	*pwp;
1492 	user_t		u;
1493 	char		password[PasswordLength + 1];
1494 	int		defaultfield;
1495 	int		rmhome;
1496 	int		bigD;
1497 	int		c;
1498 
1499 	(void) memset(&u, 0, sizeof(u));
1500 	read_defaults(&u);
1501 	defaultfield = bigD = rmhome = 0;
1502 	while ((c = getopt(argc, argv, "r" DEL_OPT_EXTENSIONS)) != -1) {
1503 		switch(c) {
1504 #ifdef EXTENSIONS
1505 		case 'D':
1506 			bigD = 1;
1507 			break;
1508 #endif
1509 #ifdef EXTENSIONS
1510 		case 'p':
1511 			defaultfield = 1;
1512 			u.u_preserve = (strcmp(optarg, "true") == 0) ? 1 :
1513 					(strcmp(optarg, "yes") == 0) ? 1 :
1514 					 atoi(optarg);
1515 			break;
1516 #endif
1517 		case 'r':
1518 			rmhome = 1;
1519 			break;
1520 #ifdef EXTENSIONS
1521 		case 'v':
1522 			verbose = 1;
1523 			break;
1524 #endif
1525 		}
1526 	}
1527 #ifdef EXTENSIONS
1528 	if (bigD) {
1529 		if (defaultfield) {
1530 			checkeuid();
1531 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
1532 		}
1533 		(void) printf("preserve\t%s\n", (u.u_preserve) ? "true" : "false");
1534 		return EXIT_SUCCESS;
1535 	}
1536 #endif
1537 	argc -= optind;
1538 	argv += optind;
1539 	if (argc != 1) {
1540 		usermgmt_usage("userdel");
1541 	}
1542 	checkeuid();
1543 	if ((pwp = getpwnam(*argv)) == NULL) {
1544 		warnx("No such user `%s'", *argv);
1545 		return EXIT_FAILURE;
1546 	}
1547 	if (rmhome)
1548 		(void)removehomedir(pwp->pw_name, pwp->pw_uid, pwp->pw_dir);
1549 	if (u.u_preserve) {
1550 		u.u_flags |= F_SHELL;
1551 		memsave(&u.u_shell, NOLOGIN, strlen(NOLOGIN));
1552 		(void) strlcpy(password, "*", sizeof(password));
1553 		memsave(&u.u_password, password, PasswordLength);
1554 		u.u_flags |= F_PASSWORD;
1555 		return moduser(*argv, *argv, &u) ? EXIT_SUCCESS : EXIT_FAILURE;
1556 	}
1557 	return moduser(*argv, *argv, NULL) ? EXIT_SUCCESS : EXIT_FAILURE;
1558 }
1559 
1560 #ifdef EXTENSIONS
1561 #define GROUP_ADD_OPT_EXTENSIONS	"v"
1562 #else
1563 #define GROUP_ADD_OPT_EXTENSIONS
1564 #endif
1565 
1566 /* add a group */
1567 int
1568 groupadd(int argc, char **argv)
1569 {
1570 	int	dupgid;
1571 	int	gid;
1572 	int	c;
1573 
1574 	gid = GID_MAX;
1575 	dupgid = 0;
1576 	while ((c = getopt(argc, argv, "g:o" GROUP_ADD_OPT_EXTENSIONS)) != -1) {
1577 		switch(c) {
1578 		case 'g':
1579 			if (!is_number(optarg)) {
1580 				errx(EXIT_FAILURE, "When using [-g gid], the gid must be numeric");
1581 			}
1582 			gid = atoi(optarg);
1583 			break;
1584 		case 'o':
1585 			dupgid = 1;
1586 			break;
1587 #ifdef EXTENSIONS
1588 		case 'v':
1589 			verbose = 1;
1590 			break;
1591 #endif
1592 		}
1593 	}
1594 	argc -= optind;
1595 	argv += optind;
1596 	if (argc != 1) {
1597 		usermgmt_usage("groupadd");
1598 	}
1599 	checkeuid();
1600 	if (gid < 0 && !getnextgid(&gid, LowGid, HighGid)) {
1601 		err(EXIT_FAILURE, "can't add group: can't get next gid");
1602 	}
1603 	if (!dupgid && getgrgid((gid_t) gid) != NULL) {
1604 		errx(EXIT_FAILURE, "can't add group: gid %d is a duplicate", gid);
1605 	}
1606 	if (!valid_group(*argv)) {
1607 		warnx("warning - invalid group name `%s'", *argv);
1608 	}
1609 	if (!creategid(*argv, gid, "")) {
1610 		errx(EXIT_FAILURE, "can't add group: problems with %s file",
1611 		    _PATH_GROUP);
1612 	}
1613 	return EXIT_SUCCESS;
1614 }
1615 
1616 #ifdef EXTENSIONS
1617 #define GROUP_DEL_OPT_EXTENSIONS	"v"
1618 #else
1619 #define GROUP_DEL_OPT_EXTENSIONS
1620 #endif
1621 
1622 /* remove a group */
1623 int
1624 groupdel(int argc, char **argv)
1625 {
1626 	int	c;
1627 
1628 	while ((c = getopt(argc, argv, "" GROUP_DEL_OPT_EXTENSIONS)) != -1) {
1629 		switch(c) {
1630 #ifdef EXTENSIONS
1631 		case 'v':
1632 			verbose = 1;
1633 			break;
1634 #endif
1635 		}
1636 	}
1637 	argc -= optind;
1638 	argv += optind;
1639 	if (argc != 1) {
1640 		usermgmt_usage("groupdel");
1641 	}
1642 	checkeuid();
1643 	if (!modify_gid(*argv, NULL)) {
1644 		err(EXIT_FAILURE, "can't change %s file", _PATH_GROUP);
1645 	}
1646 	return EXIT_SUCCESS;
1647 }
1648 
1649 #ifdef EXTENSIONS
1650 #define GROUP_MOD_OPT_EXTENSIONS	"v"
1651 #else
1652 #define GROUP_MOD_OPT_EXTENSIONS
1653 #endif
1654 
1655 /* modify a group */
1656 int
1657 groupmod(int argc, char **argv)
1658 {
1659 	struct group	*grp;
1660 	char		buf[LINE_MAX];
1661 	char		*newname;
1662 	char		**cpp;
1663 	int		dupgid;
1664 	int		gid;
1665 	int		cc;
1666 	int		c;
1667 
1668 	gid = GID_MAX;
1669 	dupgid = 0;
1670 	newname = NULL;
1671 	while ((c = getopt(argc, argv, "g:on:" GROUP_MOD_OPT_EXTENSIONS)) != -1) {
1672 		switch(c) {
1673 		case 'g':
1674 			if (!is_number(optarg)) {
1675 				errx(EXIT_FAILURE, "When using [-g gid], the gid must be numeric");
1676 			}
1677 			gid = atoi(optarg);
1678 			break;
1679 		case 'o':
1680 			dupgid = 1;
1681 			break;
1682 		case 'n':
1683 			memsave(&newname, optarg, strlen(optarg));
1684 			break;
1685 #ifdef EXTENSIONS
1686 		case 'v':
1687 			verbose = 1;
1688 			break;
1689 #endif
1690 		}
1691 	}
1692 	argc -= optind;
1693 	argv += optind;
1694 	if (argc != 1) {
1695 		usermgmt_usage("groupmod");
1696 	}
1697 	checkeuid();
1698 	if (gid < 0 && newname == NULL) {
1699 		err(EXIT_FAILURE, "Nothing to change");
1700 	}
1701 	if (dupgid && gid < 0) {
1702 		err(EXIT_FAILURE, "Duplicate which gid?");
1703 	}
1704 	if ((grp = getgrnam(*argv)) == NULL) {
1705 		err(EXIT_FAILURE, "can't find group `%s' to modify", *argv);
1706 	}
1707 	if (newname != NULL && !valid_group(newname)) {
1708 		warn("warning - invalid group name `%s'", newname);
1709 	}
1710 	cc = snprintf(buf, sizeof(buf), "%s:%s:%u:",
1711 	    (newname) ? newname : grp->gr_name, grp->gr_passwd,
1712 	    (gid < 0) ? grp->gr_gid : gid);
1713 	if (cc >= sizeof(buf) || cc == -1)
1714 		err(EXIT_FAILURE, "group `%s' entry too long", grp->gr_name);
1715 
1716 	for (cpp = grp->gr_mem ; *cpp ; cpp++) {
1717 		cc = strlcat(buf, *cpp, sizeof(buf)) + 1;
1718 		if (cc >= sizeof(buf))
1719 			err(EXIT_FAILURE, "group `%s' entry too long",
1720 			    grp->gr_name);
1721 		if (cpp[1] == NULL)
1722 			buf[cc - 1] = '\n';
1723 		else
1724 			buf[cc - 1] = ',';
1725 		buf[cc] = '\0';
1726 	}
1727 
1728 	if (!modify_gid(*argv, buf))
1729 		err(EXIT_FAILURE, "can't change %s file", _PATH_GROUP);
1730 	return EXIT_SUCCESS;
1731 }
1732 
1733 #ifdef EXTENSIONS
1734 /* display user information */
1735 int
1736 userinfo(int argc, char **argv)
1737 {
1738 	struct passwd	*pwp;
1739 	struct group	*grp;
1740 	char		**cpp;
1741 	int		exists;
1742 	int		i;
1743 
1744 	exists = 0;
1745 	while ((i = getopt(argc, argv, "ev")) != -1) {
1746 		switch(i) {
1747 		case 'e':
1748 			exists = 1;
1749 			break;
1750 		case 'v':
1751 			verbose = 1;
1752 			break;
1753 		}
1754 	}
1755 	argc -= optind;
1756 	argv += optind;
1757 	if (argc != 1) {
1758 		usermgmt_usage("userinfo");
1759 	}
1760 	pwp = find_user_info(*argv);
1761 	if (exists) {
1762 		exit((pwp) ? EXIT_SUCCESS : EXIT_FAILURE);
1763 	}
1764 	if (pwp == NULL) {
1765 		errx(EXIT_FAILURE, "can't find user `%s'", *argv);
1766 	}
1767 	(void) printf("login\t%s\n", pwp->pw_name);
1768 	(void) printf("passwd\t%s\n", pwp->pw_passwd);
1769 	(void) printf("uid\t%u\n", pwp->pw_uid);
1770 	if ((grp = getgrgid(pwp->pw_gid)) == NULL)
1771 		(void) printf("groups\t%u", pwp->pw_gid);
1772 	else
1773 		(void) printf("groups\t%s", grp->gr_name);
1774 	while ((grp = getgrent()) != NULL) {
1775 		for (cpp = grp->gr_mem ; *cpp ; cpp++) {
1776 			if (strcmp(*cpp, *argv) == 0 && grp->gr_gid != pwp->pw_gid)
1777 				(void) printf(" %s", grp->gr_name);
1778 		}
1779 	}
1780 	(void) fputc('\n', stdout);
1781 	(void) printf("change\t%s", pwp->pw_change ? ctime(&pwp->pw_change) : "NEVER\n");
1782 #ifdef EXTENSIONS
1783 	(void) printf("class\t%s\n", pwp->pw_class);
1784 #endif
1785 	(void) printf("gecos\t%s\n", pwp->pw_gecos);
1786 	(void) printf("dir\t%s\n", pwp->pw_dir);
1787 	(void) printf("shell\t%s\n", pwp->pw_shell);
1788 	(void) printf("expire\t%s", pwp->pw_expire ? ctime(&pwp->pw_expire) : "NEVER\n");
1789 	return EXIT_SUCCESS;
1790 }
1791 #endif
1792 
1793 #ifdef EXTENSIONS
1794 /* display user information */
1795 int
1796 groupinfo(int argc, char **argv)
1797 {
1798 	struct group	*grp;
1799 	char		**cpp;
1800 	int		exists;
1801 	int		i;
1802 
1803 	exists = 0;
1804 	while ((i = getopt(argc, argv, "ev")) != -1) {
1805 		switch(i) {
1806 		case 'e':
1807 			exists = 1;
1808 			break;
1809 		case 'v':
1810 			verbose = 1;
1811 			break;
1812 		}
1813 	}
1814 	argc -= optind;
1815 	argv += optind;
1816 	if (argc != 1) {
1817 		usermgmt_usage("groupinfo");
1818 	}
1819 	grp = find_group_info(*argv);
1820 	if (exists) {
1821 		exit((grp) ? EXIT_SUCCESS : EXIT_FAILURE);
1822 	}
1823 	if (grp == NULL) {
1824 		errx(EXIT_FAILURE, "can't find group `%s'", *argv);
1825 	}
1826 	(void) printf("name\t%s\n", grp->gr_name);
1827 	(void) printf("passwd\t%s\n", grp->gr_passwd);
1828 	(void) printf("gid\t%u\n", grp->gr_gid);
1829 	(void) printf("members\t");
1830 	for (cpp = grp->gr_mem ; *cpp ; cpp++) {
1831 		(void) printf("%s ", *cpp);
1832 	}
1833 	(void) fputc('\n', stdout);
1834 	return EXIT_SUCCESS;
1835 }
1836 #endif
1837