xref: /freebsd/usr.sbin/pw/pw.c (revision ca2e4ecd7395ba655ab4bebe7262a06e634216ce)
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 <err.h>
33 #include <fcntl.h>
34 #include <locale.h>
35 #include <paths.h>
36 #include <stdbool.h>
37 #include <sys/wait.h>
38 #include "pw.h"
39 
40 #if !defined(_PATH_YP)
41 #define	_PATH_YP	"/var/yp/"
42 #endif
43 const char     *Modes[] = {
44   "add", "del", "mod", "show", "next",
45   NULL};
46 const char     *Which[] = {"user", "group", NULL};
47 static const char *Combo1[] = {
48   "useradd", "userdel", "usermod", "usershow", "usernext",
49   "lock", "unlock",
50   "groupadd", "groupdel", "groupmod", "groupshow", "groupnext",
51   NULL};
52 static const char *Combo2[] = {
53   "adduser", "deluser", "moduser", "showuser", "nextuser",
54   "lock", "unlock",
55   "addgroup", "delgroup", "modgroup", "showgroup", "nextgroup",
56   NULL};
57 
58 struct pwf PWF =
59 {
60 	PWF_REGULAR,
61 	setpwent,
62 	endpwent,
63 	getpwent,
64 	getpwuid,
65 	getpwnam,
66 	setgrent,
67 	endgrent,
68 	getgrent,
69 	getgrgid,
70 	getgrnam,
71 
72 };
73 struct pwf VPWF =
74 {
75 	PWF_ALT,
76 	vsetpwent,
77 	vendpwent,
78 	vgetpwent,
79 	vgetpwuid,
80 	vgetpwnam,
81 	vsetgrent,
82 	vendgrent,
83 	vgetgrent,
84 	vgetgrgid,
85 	vgetgrnam,
86 };
87 
88 struct pwconf conf;
89 
90 static struct cargs arglist;
91 
92 static int      getindex(const char *words[], const char *word);
93 static void     cmdhelp(int mode, int which);
94 
95 
96 int
97 main(int argc, char *argv[])
98 {
99 	int             ch;
100 	int             mode = -1;
101 	int             which = -1;
102 	long		id = -1;
103 	char		*config = NULL;
104 	struct stat	st;
105 	const char	*errstr;
106 	char		arg, *name;
107 	bool		relocated, nis;
108 
109 	static const char *opts[W_NUM][M_NUM] =
110 	{
111 		{ /* user */
112 			"R:V:C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y",
113 			"R:V:C:qn:u:rY",
114 			"R:V:C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:FNPY",
115 			"R:V:C:qn:u:FPa7",
116 			"R:V:C:q",
117 			"R:V:C:q",
118 			"R:V:C:q"
119 		},
120 		{ /* grp  */
121 			"R:V:C:qn:g:h:H:M:opNPY",
122 			"R:V:C:qn:g:Y",
123 			"R:V:C:qn:d:g:l:h:H:FM:m:NPY",
124 			"R:V:C:qn:g:FPa",
125 			"R:V:C:q"
126 		 }
127 	};
128 
129 	static int      (*funcs[W_NUM]) (int _mode, char *_name, long _id,
130 	    struct cargs * _args) =
131 	{			/* Request handlers */
132 		pw_user,
133 		pw_group
134 	};
135 
136 	name = NULL;
137 	relocated = nis = false;
138 	memset(&conf, 0, sizeof(conf));
139 	strlcpy(conf.rootdir, "/", sizeof(conf.rootdir));
140 	strlcpy(conf.etcpath, _PATH_PWD, sizeof(conf.etcpath));
141 	conf.fd = -1;
142 	conf.checkduplicate = true;
143 
144 	LIST_INIT(&arglist);
145 
146 	(void)setlocale(LC_ALL, "");
147 
148 	/*
149 	 * Break off the first couple of words to determine what exactly
150 	 * we're being asked to do
151 	 */
152 	while (argc > 1) {
153 		int             tmp;
154 
155 		if (*argv[1] == '-') {
156 			/*
157 			 * Special case, allow pw -V<dir> <operation> [args] for scripts etc.
158 			 */
159 			arg = argv[1][1];
160 			if (arg == 'V' || arg == 'R') {
161 				if (relocated)
162 					errx(EXIT_FAILURE, "Both '-R' and '-V' "
163 					    "specified, only one accepted");
164 				relocated = true;
165 				optarg = &argv[1][2];
166 				if (*optarg == '\0') {
167 					if (stat(argv[2], &st) != 0)
168 						errx(EX_OSFILE, \
169 						    "no such directory `%s'",
170 						    argv[2]);
171 					if (!S_ISDIR(st.st_mode))
172 						errx(EX_OSFILE, "`%s' not a "
173 						    "directory", argv[2]);
174 					optarg = argv[2];
175 					++argv;
176 					--argc;
177 				}
178 				memcpy(&PWF, &VPWF, sizeof PWF);
179 				if (arg == 'R') {
180 					strlcpy(conf.rootdir, optarg,
181 					    sizeof(conf.rootdir));
182 					PWF._altdir = PWF_ROOTDIR;
183 				}
184 				snprintf(conf.etcpath, sizeof(conf.etcpath),
185 				    "%s%s", optarg, arg == 'R' ? "/etc" : "");
186 			} else
187 				break;
188 		}
189 		else if (mode == -1 && (tmp = getindex(Modes, argv[1])) != -1)
190 			mode = tmp;
191 		else if (which == -1 && (tmp = getindex(Which, argv[1])) != -1)
192 			which = tmp;
193 		else if ((mode == -1 && which == -1) &&
194 			 ((tmp = getindex(Combo1, argv[1])) != -1 ||
195 			  (tmp = getindex(Combo2, argv[1])) != -1)) {
196 			which = tmp / M_NUM;
197 			mode = tmp % M_NUM;
198 		} else if (strcmp(argv[1], "help") == 0 && argv[2] == NULL)
199 			cmdhelp(mode, which);
200 		else if (which != -1 && mode != -1) {
201 			if (strspn(argv[1], "0123456789") == strlen(argv[1])) {
202 				id = strtonum(argv[1], 0, LONG_MAX, &errstr);
203 				if (errstr != NULL)
204 					errx(EX_USAGE, "Bad id '%s': %s",
205 					    argv[1], errstr);
206 			} else
207 				name = argv[1];
208 		} else
209 			errx(EX_USAGE, "unknown keyword `%s'", argv[1]);
210 		++argv;
211 		--argc;
212 	}
213 
214 	/*
215 	 * Bail out unless the user is specific!
216 	 */
217 	if (mode == -1 || which == -1)
218 		cmdhelp(mode, which);
219 
220 	conf.rootfd = open(conf.rootdir, O_DIRECTORY|O_CLOEXEC);
221 	if (conf.rootfd == -1)
222 		errx(EXIT_FAILURE, "Unable to open '%s'", conf.rootdir);
223 	conf.which = which;
224 	/*
225 	 * We know which mode we're in and what we're about to do, so now
226 	 * let's dispatch the remaining command line args in a genric way.
227 	 */
228 	optarg = NULL;
229 
230 	while ((ch = getopt(argc, argv, opts[which][mode])) != -1) {
231 		switch (ch) {
232 		case '?':
233 			errx(EX_USAGE, "unknown switch");
234 			break;
235 		case '7':
236 			conf.v7 = true;
237 			break;
238 		case 'C':
239 			conf.config = optarg;
240 			config = conf.config;
241 			break;
242 		case 'F':
243 			conf.force = true;
244 			break;
245 		case 'N':
246 			conf.dryrun = true;
247 			break;
248 		case 'l':
249 			if (strlen(optarg) >= MAXLOGNAME)
250 				errx(EX_USAGE, "new name too long: %s", optarg);
251 			conf.newname = optarg;
252 			break;
253 		case 'P':
254 			conf.pretty = true;
255 			break;
256 		case 'Y':
257 			nis = true;
258 			break;
259 		case 'a':
260 			conf.all = true;
261 			break;
262 		case 'c':
263 			conf.gecos = pw_checkname(optarg, 1);
264 			break;
265 		case 'g':
266 			if (which == 0) { /* for user* */
267 				addarg(&arglist, 'g', optarg);
268 				break;
269 			}
270 			if (strspn(optarg, "0123456789") != strlen(optarg))
271 				errx(EX_USAGE, "-g expects a number");
272 			id = strtonum(optarg, 0, LONG_MAX, &errstr);
273 			if (errstr != NULL)
274 				errx(EX_USAGE, "Bad id '%s': %s", optarg,
275 				    errstr);
276 			break;
277 		case 'u':
278 			if (strspn(optarg, "0123456789,") != strlen(optarg))
279 				errx(EX_USAGE, "-u expects a number");
280 			if (strchr(optarg, ',') != NULL) {
281 				addarg(&arglist, 'u', optarg);
282 				break;
283 			}
284 			id = strtonum(optarg, 0, LONG_MAX, &errstr);
285 			if (errstr != NULL)
286 				errx(EX_USAGE, "Bad id '%s': %s", optarg,
287 				    errstr);
288 			break;
289 		case 'n':
290 			if (strspn(optarg, "0123456789") != strlen(optarg)) {
291 				name = optarg;
292 				break;
293 			}
294 			id = strtonum(optarg, 0, LONG_MAX, &errstr);
295 			if (errstr != NULL)
296 				errx(EX_USAGE, "Bad id '%s': %s", optarg,
297 				    errstr);
298 			break;
299 		case 'H':
300 			if (conf.fd != -1)
301 				errx(EX_USAGE, "'-h' and '-H' are mutually "
302 				    "exclusive options");
303 			conf.precrypted = true;
304 			if (strspn(optarg, "0123456789") != strlen(optarg))
305 				errx(EX_USAGE, "'-H' expects a file descriptor");
306 
307 			conf.fd = strtonum(optarg, 0, INT_MAX, &errstr);
308 			if (errstr != NULL)
309 				errx(EX_USAGE, "Bad file descriptor '%s': %s",
310 				    optarg, errstr);
311 			break;
312 		case 'h':
313 			if (conf.fd != -1)
314 				errx(EX_USAGE, "'-h' and '-H' are mutually "
315 				    "exclusive options");
316 
317 			if (strcmp(optarg, "-") == 0)
318 				conf.fd = '-';
319 			else if (strspn(optarg, "0123456789") == strlen(optarg)) {
320 				conf.fd = strtonum(optarg, 0, INT_MAX, &errstr);
321 				if (errstr != NULL)
322 					errx(EX_USAGE, "'-h' expects a "
323 					    "file descriptor or '-'");
324 			} else
325 				errx(EX_USAGE, "'-h' expects a file "
326 				    "descriptor or '-'");
327 			break;
328 		case 'o':
329 			conf.checkduplicate = false;
330 			break;
331 		case 'q':
332 			conf.quiet = true;
333 			break;
334 		case 'r':
335 			conf.deletehome = true;
336 			break;
337 		default:
338 			addarg(&arglist, ch, optarg);
339 			break;
340 		}
341 		optarg = NULL;
342 	}
343 
344 	if (name != NULL && strlen(name) >= MAXLOGNAME)
345 		errx(EX_USAGE, "name too long: %s", name);
346 
347 	/*
348 	 * Must be root to attempt an update
349 	 */
350 	if (geteuid() != 0 && mode != M_PRINT && mode != M_NEXT && !conf.dryrun)
351 		errx(EX_NOPERM, "you must be root to run this program");
352 
353 	/*
354 	 * We should immediately look for the -q 'quiet' switch so that we
355 	 * don't bother with extraneous errors
356 	 */
357 	if (conf.quiet)
358 		freopen(_PATH_DEVNULL, "w", stderr);
359 
360 	/*
361 	 * Set our base working path if not overridden
362 	 */
363 
364 	if (config == NULL) {	/* Only override config location if -C not specified */
365 		asprintf(&config, "%s/pw.conf", conf.etcpath);
366 		if (config == NULL)
367 			errx(EX_OSERR, "out of memory");
368 	}
369 
370 	/*
371 	 * Now, let's do the common initialisation
372 	 */
373 	conf.userconf = read_userconfig(config);
374 
375 	ch = funcs[which] (mode, name, id, &arglist);
376 
377 	/*
378 	 * If everything went ok, and we've been asked to update
379 	 * the NIS maps, then do it now
380 	 */
381 	if (ch == EXIT_SUCCESS && nis) {
382 		pid_t	pid;
383 
384 		fflush(NULL);
385 		if (chdir(_PATH_YP) == -1)
386 			warn("chdir(" _PATH_YP ")");
387 		else if ((pid = fork()) == -1)
388 			warn("fork()");
389 		else if (pid == 0) {
390 			/* Is make anywhere else? */
391 			execlp("/usr/bin/make", "make", (char *)NULL);
392 			_exit(1);
393 		} else {
394 			int   i;
395 			waitpid(pid, &i, 0);
396 			if ((i = WEXITSTATUS(i)) != 0)
397 				errx(ch, "make exited with status %d", i);
398 			else
399 				pw_log(conf.userconf, mode, which, "NIS maps updated");
400 		}
401 	}
402 	return ch;
403 }
404 
405 
406 static int
407 getindex(const char *words[], const char *word)
408 {
409 	int             i = 0;
410 
411 	while (words[i]) {
412 		if (strcmp(words[i], word) == 0)
413 			return i;
414 		i++;
415 	}
416 	return -1;
417 }
418 
419 
420 /*
421  * This is probably an overkill for a cmdline help system, but it reflects
422  * the complexity of the command line.
423  */
424 
425 static void
426 cmdhelp(int mode, int which)
427 {
428 	if (which == -1)
429 		fprintf(stderr, "usage:\n  pw [user|group|lock|unlock] [add|del|mod|show|next] [help|switches/values]\n");
430 	else if (mode == -1)
431 		fprintf(stderr, "usage:\n  pw %s [add|del|mod|show|next] [help|switches/values]\n", Which[which]);
432 	else {
433 
434 		/*
435 		 * We need to give mode specific help
436 		 */
437 		static const char *help[W_NUM][M_NUM] =
438 		{
439 			{
440 				"usage: pw useradd [name] [switches]\n"
441 				"\t-V etcdir      alternate /etc location\n"
442 				"\t-R rootir      alternate root directory\n"
443 				"\t-C config      configuration file\n"
444 				"\t-q             quiet operation\n"
445 				"  Adding users:\n"
446 				"\t-n name        login name\n"
447 				"\t-u uid         user id\n"
448 				"\t-c comment     user name/comment\n"
449 				"\t-d directory   home directory\n"
450 				"\t-e date        account expiry date\n"
451 				"\t-p date        password expiry date\n"
452 				"\t-g grp         initial group\n"
453 				"\t-G grp1,grp2   additional groups\n"
454 				"\t-m [ -k dir ]  create and set up home\n"
455 				"\t-M mode        home directory permissions\n"
456 				"\t-s shell       name of login shell\n"
457 				"\t-o             duplicate uid ok\n"
458 				"\t-L class       user class\n"
459 				"\t-h fd          read password on fd\n"
460 				"\t-H fd          read encrypted password on fd\n"
461 				"\t-Y             update NIS maps\n"
462 				"\t-N             no update\n"
463 				"  Setting defaults:\n"
464 				"\t-V etcdir      alternate /etc location\n"
465 				"\t-R rootir      alternate root directory\n"
466 			        "\t-D             set user defaults\n"
467 				"\t-b dir         default home root dir\n"
468 				"\t-e period      default expiry period\n"
469 				"\t-p period      default password change period\n"
470 				"\t-g group       default group\n"
471 				"\t-G grp1,grp2   additional groups\n"
472 				"\t-L class       default user class\n"
473 				"\t-k dir         default home skeleton\n"
474 				"\t-M mode        home directory permissions\n"
475 				"\t-u min,max     set min,max uids\n"
476 				"\t-i min,max     set min,max gids\n"
477 				"\t-w method      set default password method\n"
478 				"\t-s shell       default shell\n"
479 				"\t-y path        set NIS passwd file path\n",
480 				"usage: pw userdel [uid|name] [switches]\n"
481 				"\t-V etcdir      alternate /etc location\n"
482 				"\t-R rootir      alternate root directory\n"
483 				"\t-n name        login name\n"
484 				"\t-u uid         user id\n"
485 				"\t-Y             update NIS maps\n"
486 				"\t-r             remove home & contents\n",
487 				"usage: pw usermod [uid|name] [switches]\n"
488 				"\t-V etcdir      alternate /etc location\n"
489 				"\t-R rootir      alternate root directory\n"
490 				"\t-C config      configuration file\n"
491 				"\t-q             quiet operation\n"
492 				"\t-F             force add if no user\n"
493 				"\t-n name        login name\n"
494 				"\t-u uid         user id\n"
495 				"\t-c comment     user name/comment\n"
496 				"\t-d directory   home directory\n"
497 				"\t-e date        account expiry date\n"
498 				"\t-p date        password expiry date\n"
499 				"\t-g grp         initial group\n"
500 				"\t-G grp1,grp2   additional groups\n"
501 				"\t-l name        new login name\n"
502 				"\t-L class       user class\n"
503 				"\t-m [ -k dir ]  create and set up home\n"
504 				"\t-M mode        home directory permissions\n"
505 				"\t-s shell       name of login shell\n"
506 				"\t-w method      set new password using method\n"
507 				"\t-h fd          read password on fd\n"
508 				"\t-H fd          read encrypted password on fd\n"
509 				"\t-Y             update NIS maps\n"
510 				"\t-N             no update\n",
511 				"usage: pw usershow [uid|name] [switches]\n"
512 				"\t-V etcdir      alternate /etc location\n"
513 				"\t-R rootir      alternate root directory\n"
514 				"\t-n name        login name\n"
515 				"\t-u uid         user id\n"
516 				"\t-F             force print\n"
517 				"\t-P             prettier format\n"
518 				"\t-a             print all users\n"
519 				"\t-7             print in v7 format\n",
520 				"usage: pw usernext [switches]\n"
521 				"\t-V etcdir      alternate /etc location\n"
522 				"\t-R rootir      alternate root directory\n"
523 				"\t-C config      configuration file\n"
524 				"\t-q             quiet operation\n",
525 				"usage pw: lock [switches]\n"
526 				"\t-V etcdir      alternate /etc locations\n"
527 				"\t-C config      configuration file\n"
528 				"\t-q             quiet operation\n",
529 				"usage pw: unlock [switches]\n"
530 				"\t-V etcdir      alternate /etc locations\n"
531 				"\t-C config      configuration file\n"
532 				"\t-q             quiet operation\n"
533 			},
534 			{
535 				"usage: pw groupadd [group|gid] [switches]\n"
536 				"\t-V etcdir      alternate /etc location\n"
537 				"\t-R rootir      alternate root directory\n"
538 				"\t-C config      configuration file\n"
539 				"\t-q             quiet operation\n"
540 				"\t-n group       group name\n"
541 				"\t-g gid         group id\n"
542 				"\t-M usr1,usr2   add users as group members\n"
543 				"\t-o             duplicate gid ok\n"
544 				"\t-Y             update NIS maps\n"
545 				"\t-N             no update\n",
546 				"usage: pw groupdel [group|gid] [switches]\n"
547 				"\t-V etcdir      alternate /etc location\n"
548 				"\t-R rootir      alternate root directory\n"
549 				"\t-n name        group name\n"
550 				"\t-g gid         group id\n"
551 				"\t-Y             update NIS maps\n",
552 				"usage: pw groupmod [group|gid] [switches]\n"
553 				"\t-V etcdir      alternate /etc location\n"
554 				"\t-R rootir      alternate root directory\n"
555 				"\t-C config      configuration file\n"
556 				"\t-q             quiet operation\n"
557 				"\t-F             force add if not exists\n"
558 				"\t-n name        group name\n"
559 				"\t-g gid         group id\n"
560 				"\t-M usr1,usr2   replaces users as group members\n"
561 				"\t-m usr1,usr2   add users as group members\n"
562 				"\t-d usr1,usr2   delete users as group members\n"
563 				"\t-l name        new group name\n"
564 				"\t-Y             update NIS maps\n"
565 				"\t-N             no update\n",
566 				"usage: pw groupshow [group|gid] [switches]\n"
567 				"\t-V etcdir      alternate /etc location\n"
568 				"\t-R rootir      alternate root directory\n"
569 				"\t-n name        group name\n"
570 				"\t-g gid         group id\n"
571 				"\t-F             force print\n"
572 				"\t-P             prettier format\n"
573 				"\t-a             print all accounting groups\n",
574 				"usage: pw groupnext [switches]\n"
575 				"\t-V etcdir      alternate /etc location\n"
576 				"\t-R rootir      alternate root directory\n"
577 				"\t-C config      configuration file\n"
578 				"\t-q             quiet operation\n"
579 			}
580 		};
581 
582 		fprintf(stderr, "%s", help[which][mode]);
583 	}
584 	exit(EXIT_FAILURE);
585 }
586 
587 struct carg    *
588 getarg(struct cargs * _args, int ch)
589 {
590 	struct carg    *c;
591 
592 	if (_args == NULL)
593 		return (NULL);
594 
595 	c = LIST_FIRST(_args);
596 
597 	while (c != NULL && c->ch != ch)
598 		c = LIST_NEXT(c, list);
599 	return c;
600 }
601 
602 struct carg    *
603 addarg(struct cargs * _args, int ch, char *argstr)
604 {
605 	struct carg    *ca = malloc(sizeof(struct carg));
606 
607 	if (ca == NULL)
608 		errx(EX_OSERR, "out of memory");
609 	ca->ch = ch;
610 	ca->val = argstr;
611 	LIST_INSERT_HEAD(_args, ca, list);
612 	return ca;
613 }
614