pw_user.c revision 283961
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
28#ifndef lint
29static const char rcsid[] =
30  "$FreeBSD: head/usr.sbin/pw/pw_user.c 283961 2015-06-03 19:08:25Z bapt $";
31#endif /* not lint */
32
33#include <ctype.h>
34#include <err.h>
35#include <fcntl.h>
36#include <sys/param.h>
37#include <dirent.h>
38#include <paths.h>
39#include <termios.h>
40#include <sys/types.h>
41#include <sys/time.h>
42#include <sys/resource.h>
43#include <login_cap.h>
44#include <pwd.h>
45#include <grp.h>
46#include <libutil.h>
47#include "pw.h"
48#include "bitmap.h"
49
50#define LOGNAMESIZE (MAXLOGNAME-1)
51
52static		char locked_str[] = "*LOCKED*";
53
54static int      print_user(struct passwd * pwd, int pretty, int v7);
55static uid_t    pw_uidpolicy(struct userconf * cnf, struct cargs * args);
56static uid_t    pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
57static time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
58static time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
59static char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
60static char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
61static char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
62static char    *shell_path(char const * path, char *shells[], char *sh);
63static void     rmat(uid_t uid);
64static void     rmopie(char const * name);
65
66static void
67create_and_populate_homedir(int mode, struct cargs *args, struct passwd *pwd,
68    struct userconf *cnf)
69{
70	char *homedir, *dotdir;
71	struct carg	*arg;
72
73	homedir = dotdir = NULL;
74
75	if ((arg = getarg(args, 'R'))) {
76		asprintf(&homedir, "%s/%s", arg->val, pwd->pw_dir);
77		if (homedir == NULL)
78			errx(EX_OSERR, "out of memory");
79		asprintf(&dotdir, "%s/%s", arg->val, cnf->dotdir);
80	}
81
82	copymkdir(homedir ? homedir : pwd->pw_dir, dotdir ? dotdir: cnf->dotdir,
83	    cnf->homemode, pwd->pw_uid, pwd->pw_gid);
84	pw_log(cnf, mode, W_USER, "%s(%u) home %s made", pwd->pw_name,
85	    pwd->pw_uid, pwd->pw_dir);
86}
87
88/*-
89 * -C config      configuration file
90 * -q             quiet operation
91 * -n name        login name
92 * -u uid         user id
93 * -c comment     user name/comment
94 * -d directory   home directory
95 * -e date        account expiry date
96 * -p date        password expiry date
97 * -g grp         primary group
98 * -G grp1,grp2   additional groups
99 * -m [ -k dir ]  create and set up home
100 * -s shell       name of login shell
101 * -o             duplicate uid ok
102 * -L class       user class
103 * -l name        new login name
104 * -h fd          password filehandle
105 * -H fd          encrypted password filehandle
106 * -F             force print or add
107 *   Setting defaults:
108 * -D             set user defaults
109 * -b dir         default home root dir
110 * -e period      default expiry period
111 * -p period      default password change period
112 * -g group       default group
113 * -G             grp1,grp2.. default additional groups
114 * -L class       default login class
115 * -k dir         default home skeleton
116 * -s shell       default shell
117 * -w method      default password method
118 */
119
120int
121pw_user(struct userconf * cnf, int mode, struct cargs * args)
122{
123	int	        rc, edited = 0;
124	char           *p = NULL;
125	char					 *passtmp;
126	struct carg    *a_name;
127	struct carg    *a_uid;
128	struct carg    *arg;
129	struct passwd  *pwd = NULL;
130	struct group   *grp;
131	struct stat     st;
132	char            line[_PASSWORD_LEN+1];
133	char		path[MAXPATHLEN];
134	FILE	       *fp;
135	char *dmode_c;
136	void *set = NULL;
137
138	static struct passwd fakeuser =
139	{
140		NULL,
141		"*",
142		-1,
143		-1,
144		0,
145		"",
146		"User &",
147		"/nonexistent",
148		"/bin/sh",
149		0
150#if defined(__FreeBSD__)
151		,0
152#endif
153	};
154
155
156	/*
157	 * With M_NEXT, we only need to return the
158	 * next uid to stdout
159	 */
160	if (mode == M_NEXT)
161	{
162		uid_t next = pw_uidpolicy(cnf, args);
163		if (getarg(args, 'q'))
164			return next;
165		printf("%u:", next);
166		pw_group(cnf, mode, args);
167		return EXIT_SUCCESS;
168	}
169
170	/*
171	 * We can do all of the common legwork here
172	 */
173
174	if ((arg = getarg(args, 'b')) != NULL) {
175		cnf->home = arg->val;
176	}
177
178	if ((arg = getarg(args, 'M')) != NULL) {
179		dmode_c = arg->val;
180		if ((set = setmode(dmode_c)) == NULL)
181			errx(EX_DATAERR, "invalid directory creation mode '%s'",
182			    dmode_c);
183		cnf->homemode = getmode(set, _DEF_DIRMODE);
184		free(set);
185	}
186
187	/*
188	 * If we'll need to use it or we're updating it,
189	 * then create the base home directory if necessary
190	 */
191	if (arg != NULL || getarg(args, 'm') != NULL) {
192		int	l = strlen(cnf->home);
193
194		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
195			cnf->home[--l] = '\0';
196
197		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
198			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
199
200		if (stat(cnf->home, &st) == -1) {
201			char	dbuf[MAXPATHLEN];
202
203			/*
204			 * This is a kludge especially for Joerg :)
205			 * If the home directory would be created in the root partition, then
206			 * we really create it under /usr which is likely to have more space.
207			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
208			 */
209			if (strchr(cnf->home+1, '/') == NULL) {
210				snprintf(dbuf, MAXPATHLEN, "/usr%s", cnf->home);
211				if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
212					chown(dbuf, 0, 0);
213					/*
214					 * Skip first "/" and create symlink:
215					 * /home -> usr/home
216					 */
217					symlink(dbuf+1, cnf->home);
218				}
219				/* If this falls, fall back to old method */
220			}
221			strlcpy(dbuf, cnf->home, sizeof(dbuf));
222			p = dbuf;
223			if (stat(dbuf, &st) == -1) {
224				while ((p = strchr(p + 1, '/')) != NULL) {
225					*p = '\0';
226					if (stat(dbuf, &st) == -1) {
227						if (mkdir(dbuf, _DEF_DIRMODE) == -1)
228							goto direrr;
229						chown(dbuf, 0, 0);
230					} else if (!S_ISDIR(st.st_mode))
231						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
232					*p = '/';
233				}
234			}
235			if (stat(dbuf, &st) == -1) {
236				if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
237				direrr:	err(EX_OSFILE, "mkdir '%s'", dbuf);
238				}
239				chown(dbuf, 0, 0);
240			}
241		} else if (!S_ISDIR(st.st_mode))
242			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
243	}
244
245	if ((arg = getarg(args, 'e')) != NULL)
246		cnf->expire_days = atoi(arg->val);
247
248	if ((arg = getarg(args, 'y')) != NULL)
249		cnf->nispasswd = arg->val;
250
251	if ((arg = getarg(args, 'p')) != NULL && arg->val)
252		cnf->password_days = atoi(arg->val);
253
254	if ((arg = getarg(args, 'g')) != NULL) {
255		if (!*(p = arg->val))	/* Handle empty group list specially */
256			cnf->default_group = "";
257		else {
258			if ((grp = GETGRNAM(p)) == NULL) {
259				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
260					errx(EX_NOUSER, "group `%s' does not exist", p);
261			}
262			cnf->default_group = newstr(grp->gr_name);
263		}
264	}
265	if ((arg = getarg(args, 'L')) != NULL)
266		cnf->default_class = pw_checkname((u_char *)arg->val, 0);
267
268	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
269		int i = 0;
270
271		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
272			if ((grp = GETGRNAM(p)) == NULL) {
273				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
274					errx(EX_NOUSER, "group `%s' does not exist", p);
275			}
276			if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
277				cnf->groups[i++] = newstr(grp->gr_name);
278		}
279		while (i < cnf->numgroups)
280			cnf->groups[i++] = NULL;
281	}
282
283	if ((arg = getarg(args, 'k')) != NULL) {
284		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
285			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
286	}
287
288	if ((arg = getarg(args, 's')) != NULL)
289		cnf->shell_default = arg->val;
290
291	if ((arg = getarg(args, 'w')) != NULL)
292		cnf->default_password = boolean_val(arg->val, cnf->default_password);
293	if (mode == M_ADD && getarg(args, 'D')) {
294		if (getarg(args, 'n') != NULL)
295			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
296		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
297			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
298				cnf->min_uid = 1000;
299			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
300				cnf->max_uid = 32000;
301		}
302		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
303			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
304				cnf->min_gid = 1000;
305			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
306				cnf->max_gid = 32000;
307		}
308
309		arg = getarg(args, 'C');
310		if (write_userconfig(arg ? arg->val : NULL))
311			return EXIT_SUCCESS;
312		err(EX_IOERR, "config udpate");
313	}
314
315	if (mode == M_PRINT && getarg(args, 'a')) {
316		int             pretty = getarg(args, 'P') != NULL;
317		int		v7 = getarg(args, '7') != NULL;
318		SETPWENT();
319		while ((pwd = GETPWENT()) != NULL)
320			print_user(pwd, pretty, v7);
321		ENDPWENT();
322		return EXIT_SUCCESS;
323	}
324
325	if ((a_name = getarg(args, 'n')) != NULL)
326		pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
327	a_uid = getarg(args, 'u');
328
329	if (a_uid == NULL) {
330		if (a_name == NULL)
331			errx(EX_DATAERR, "user name or id required");
332
333		/*
334		 * Determine whether 'n' switch is name or uid - we don't
335		 * really don't really care which we have, but we need to
336		 * know.
337		 */
338		if (mode != M_ADD && pwd == NULL
339		    && strspn(a_name->val, "0123456789") == strlen(a_name->val)
340		    && *a_name->val) {
341			(a_uid = a_name)->ch = 'u';
342			a_name = NULL;
343		}
344	} else {
345		if (strspn(a_uid->val, "0123456789") != strlen(a_uid->val))
346			errx(EX_USAGE, "-u expects a number");
347	}
348
349	/*
350	 * Update, delete & print require that the user exists
351	 */
352	if (mode == M_UPDATE || mode == M_DELETE ||
353	    mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
354
355		if (a_name == NULL && pwd == NULL)	/* Try harder */
356			pwd = GETPWUID(atoi(a_uid->val));
357
358		if (pwd == NULL) {
359			if (mode == M_PRINT && getarg(args, 'F')) {
360				fakeuser.pw_name = a_name ? a_name->val : "nouser";
361				fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : (uid_t) -1;
362				return print_user(&fakeuser,
363						  getarg(args, 'P') != NULL,
364						  getarg(args, '7') != NULL);
365			}
366			if (a_name == NULL)
367				errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
368			errx(EX_NOUSER, "no such user `%s'", a_name->val);
369		}
370
371		if (a_name == NULL)	/* May be needed later */
372			a_name = addarg(args, 'n', newstr(pwd->pw_name));
373
374		/*
375		 * The M_LOCK and M_UNLOCK functions simply add or remove
376		 * a "*LOCKED*" prefix from in front of the password to
377		 * prevent it decoding correctly, and therefore prevents
378		 * access. Of course, this only prevents access via
379		 * password authentication (not ssh, kerberos or any
380		 * other method that does not use the UNIX password) but
381		 * that is a known limitation.
382		 */
383
384		if (mode == M_LOCK) {
385			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
386				errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
387			asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
388			if (passtmp == NULL)	/* disaster */
389				errx(EX_UNAVAILABLE, "out of memory");
390			pwd->pw_passwd = passtmp;
391			edited = 1;
392		} else if (mode == M_UNLOCK) {
393			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
394				errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
395			pwd->pw_passwd += sizeof(locked_str)-1;
396			edited = 1;
397		} else if (mode == M_DELETE) {
398			/*
399			 * Handle deletions now
400			 */
401			char            file[MAXPATHLEN];
402			char            home[MAXPATHLEN];
403			uid_t           uid = pwd->pw_uid;
404			struct group    *gr;
405			char            grname[LOGNAMESIZE];
406
407			if (strcmp(pwd->pw_name, "root") == 0)
408				errx(EX_DATAERR, "cannot remove user 'root'");
409
410			if (!PWALTDIR()) {
411				/*
412				 * Remove opie record from /etc/opiekeys
413		        	 */
414
415				rmopie(pwd->pw_name);
416
417				/*
418				 * Remove crontabs
419				 */
420				snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
421				if (access(file, F_OK) == 0) {
422					snprintf(file, sizeof(file), "crontab -u %s -r", pwd->pw_name);
423					system(file);
424				}
425			}
426			/*
427			 * Save these for later, since contents of pwd may be
428			 * invalidated by deletion
429			 */
430			snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
431			strlcpy(home, pwd->pw_dir, sizeof(home));
432			gr = GETGRGID(pwd->pw_gid);
433			if (gr != NULL)
434				strlcpy(grname, gr->gr_name, LOGNAMESIZE);
435			else
436				grname[0] = '\0';
437
438			rc = delpwent(pwd);
439			if (rc == -1)
440				err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
441			else if (rc != 0)
442				err(EX_IOERR, "passwd update");
443
444			if (cnf->nispasswd && *cnf->nispasswd=='/') {
445				rc = delnispwent(cnf->nispasswd, a_name->val);
446				if (rc == -1)
447					warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
448				else if (rc != 0)
449					warn("WARNING: NIS passwd update");
450				/* non-fatal */
451			}
452
453			grp = GETGRNAM(a_name->val);
454			if (grp != NULL &&
455			    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
456			    strcmp(a_name->val, grname) == 0)
457				delgrent(GETGRNAM(a_name->val));
458			SETGRENT();
459			while ((grp = GETGRENT()) != NULL) {
460				int i, j;
461				char group[MAXLOGNAME];
462				if (grp->gr_mem != NULL) {
463					for (i = 0; grp->gr_mem[i] != NULL; i++) {
464						if (!strcmp(grp->gr_mem[i], a_name->val)) {
465							for (j = i; grp->gr_mem[j] != NULL; j++)
466								grp->gr_mem[j] = grp->gr_mem[j+1];
467							strlcpy(group, grp->gr_name, MAXLOGNAME);
468							chggrent(group, grp);
469						}
470					}
471				}
472			}
473			ENDGRENT();
474
475			pw_log(cnf, mode, W_USER, "%s(%u) account removed", a_name->val, uid);
476
477			if (PWALTDIR()) {
478				/*
479				 * Remove mail file
480				 */
481				remove(file);
482
483				/*
484				 * Remove at jobs
485				 */
486				if (getpwuid(uid) == NULL)
487					rmat(uid);
488
489				/*
490				 * Remove home directory and contents
491				 */
492				if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
493					if (stat(home, &st) != -1) {
494						rm_r(home, uid);
495						pw_log(cnf, mode, W_USER, "%s(%u) home '%s' %sremoved",
496						       a_name->val, uid, home,
497						       stat(home, &st) == -1 ? "" : "not completely ");
498					}
499				}
500			}
501			return EXIT_SUCCESS;
502		} else if (mode == M_PRINT)
503			return print_user(pwd,
504					  getarg(args, 'P') != NULL,
505					  getarg(args, '7') != NULL);
506
507		/*
508		 * The rest is edit code
509		 */
510		if ((arg = getarg(args, 'l')) != NULL) {
511			if (strcmp(pwd->pw_name, "root") == 0)
512				errx(EX_DATAERR, "can't rename `root' account");
513			pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
514			edited = 1;
515		}
516
517		if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
518			pwd->pw_uid = (uid_t) atol(arg->val);
519			edited = 1;
520			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
521				errx(EX_DATAERR, "can't change uid of `root' account");
522			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
523				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
524		}
525
526		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
527			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
528			if (newgid != pwd->pw_gid) {
529				edited = 1;
530				pwd->pw_gid = newgid;
531			}
532		}
533
534		if ((arg = getarg(args, 'p')) != NULL) {
535			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
536				if (pwd->pw_change != 0) {
537					pwd->pw_change = 0;
538					edited = 1;
539				}
540			}
541			else {
542				time_t          now = time(NULL);
543				time_t          expire = parse_date(now, arg->val);
544
545				if (pwd->pw_change != expire) {
546					pwd->pw_change = expire;
547					edited = 1;
548				}
549			}
550		}
551
552		if ((arg = getarg(args, 'e')) != NULL) {
553			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
554				if (pwd->pw_expire != 0) {
555					pwd->pw_expire = 0;
556					edited = 1;
557				}
558			}
559			else {
560				time_t          now = time(NULL);
561				time_t          expire = parse_date(now, arg->val);
562
563				if (pwd->pw_expire != expire) {
564					pwd->pw_expire = expire;
565					edited = 1;
566				}
567			}
568		}
569
570		if ((arg = getarg(args, 's')) != NULL) {
571			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
572			if (shell == NULL)
573				shell = "";
574			if (strcmp(shell, pwd->pw_shell) != 0) {
575				pwd->pw_shell = shell;
576				edited = 1;
577			}
578		}
579
580		if (getarg(args, 'L')) {
581			if (cnf->default_class == NULL)
582				cnf->default_class = "";
583			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
584				pwd->pw_class = cnf->default_class;
585				edited = 1;
586			}
587		}
588
589		if ((arg  = getarg(args, 'd')) != NULL) {
590			if (strcmp(pwd->pw_dir, arg->val))
591				edited = 1;
592			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
593				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
594				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
595			} else if (!S_ISDIR(st.st_mode))
596				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
597		}
598
599		if ((arg = getarg(args, 'w')) != NULL &&
600		    getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
601			login_cap_t *lc;
602
603			lc = login_getpwclass(pwd);
604			if (lc == NULL ||
605			    login_setcryptfmt(lc, "sha512", NULL) == NULL)
606				warn("setting crypt(3) format");
607			login_close(lc);
608			pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
609			edited = 1;
610		}
611
612	} else {
613		login_cap_t *lc;
614
615		/*
616		 * Add code
617		 */
618
619		if (a_name == NULL)	/* Required */
620			errx(EX_DATAERR, "login name required");
621		else if ((pwd = GETPWNAM(a_name->val)) != NULL)	/* Exists */
622			errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
623
624		/*
625		 * Now, set up defaults for a new user
626		 */
627		pwd = &fakeuser;
628		pwd->pw_name = a_name->val;
629		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
630		pwd->pw_uid = pw_uidpolicy(cnf, args);
631		pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
632		pwd->pw_change = pw_pwdpolicy(cnf, args);
633		pwd->pw_expire = pw_exppolicy(cnf, args);
634		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
635		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
636		lc = login_getpwclass(pwd);
637		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
638			warn("setting crypt(3) format");
639		login_close(lc);
640		pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
641		edited = 1;
642
643		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
644			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
645	}
646
647	/*
648	 * Shared add/edit code
649	 */
650	if ((arg = getarg(args, 'c')) != NULL) {
651		char	*gecos = pw_checkname((u_char *)arg->val, 1);
652		if (strcmp(pwd->pw_gecos, gecos) != 0) {
653			pwd->pw_gecos = gecos;
654			edited = 1;
655		}
656	}
657
658	if ((arg = getarg(args, 'h')) != NULL ||
659	    (arg = getarg(args, 'H')) != NULL) {
660		if (strcmp(arg->val, "-") == 0) {
661			if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
662				pwd->pw_passwd = "*";	/* No access */
663				edited = 1;
664			}
665		} else {
666			int             fd = atoi(arg->val);
667			int		precrypt = (arg->ch == 'H');
668			int             b;
669			int             istty = isatty(fd);
670			struct termios  t;
671			login_cap_t	*lc;
672
673			if (istty) {
674				if (tcgetattr(fd, &t) == -1)
675					istty = 0;
676				else {
677					struct termios  n = t;
678
679					/* Disable echo */
680					n.c_lflag &= ~(ECHO);
681					tcsetattr(fd, TCSANOW, &n);
682					printf("%s%spassword for user %s:",
683					     (mode == M_UPDATE) ? "new " : "",
684					     precrypt ? "encrypted " : "",
685					     pwd->pw_name);
686					fflush(stdout);
687				}
688			}
689			b = read(fd, line, sizeof(line) - 1);
690			if (istty) {	/* Restore state */
691				tcsetattr(fd, TCSANOW, &t);
692				fputc('\n', stdout);
693				fflush(stdout);
694			}
695			if (b < 0)
696				err(EX_IOERR, "-%c file descriptor",
697				    precrypt ? 'H' : 'h');
698			line[b] = '\0';
699			if ((p = strpbrk(line, "\r\n")) != NULL)
700				*p = '\0';
701			if (!*line)
702				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
703			if (precrypt) {
704				if (strchr(line, ':') != NULL)
705					return EX_DATAERR;
706				pwd->pw_passwd = line;
707			} else {
708				lc = login_getpwclass(pwd);
709				if (lc == NULL ||
710				    login_setcryptfmt(lc, "sha512", NULL) == NULL)
711					warn("setting crypt(3) format");
712				login_close(lc);
713				pwd->pw_passwd = pw_pwcrypt(line);
714			}
715			edited = 1;
716		}
717	}
718
719	/*
720	 * Special case: -N only displays & exits
721	 */
722	if (getarg(args, 'N') != NULL)
723		return print_user(pwd,
724				  getarg(args, 'P') != NULL,
725				  getarg(args, '7') != NULL);
726
727	if (mode == M_ADD) {
728		edited = 1;	/* Always */
729		rc = addpwent(pwd);
730		if (rc == -1)
731			errx(EX_IOERR, "user '%s' already exists",
732			    pwd->pw_name);
733		else if (rc != 0)
734			err(EX_IOERR, "passwd file update");
735		if (cnf->nispasswd && *cnf->nispasswd=='/') {
736			rc = addnispwent(cnf->nispasswd, pwd);
737			if (rc == -1)
738				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
739			else
740				warn("NIS passwd update");
741			/* NOTE: we treat NIS-only update errors as non-fatal */
742		}
743	} else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
744		if (edited) {	/* Only updated this if required */
745			rc = chgpwent(a_name->val, pwd);
746			if (rc == -1)
747				errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
748			else if (rc != 0)
749				err(EX_IOERR, "passwd file update");
750			if ( cnf->nispasswd && *cnf->nispasswd=='/') {
751				rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
752				if (rc == -1)
753					warn("User '%s' not found in NIS passwd", pwd->pw_name);
754				else
755					warn("NIS passwd update");
756				/* NOTE: NIS-only update errors are not fatal */
757			}
758		}
759	}
760
761	/*
762	 * Ok, user is created or changed - now edit group file
763	 */
764
765	if (mode == M_ADD || getarg(args, 'G') != NULL) {
766		int i, j;
767		/* First remove the user from all group */
768		SETGRENT();
769		while ((grp = GETGRENT()) != NULL) {
770			char group[MAXLOGNAME];
771			if (grp->gr_mem == NULL)
772				continue;
773			for (i = 0; grp->gr_mem[i] != NULL; i++) {
774				if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0)
775					continue;
776				for (j = i; grp->gr_mem[j] != NULL ; j++)
777					grp->gr_mem[j] = grp->gr_mem[j+1];
778				strlcpy(group, grp->gr_name, MAXLOGNAME);
779				chggrent(group, grp);
780			}
781		}
782		ENDGRENT();
783
784		/* now add to group where needed */
785		for (i = 0; cnf->groups[i] != NULL; i++) {
786			grp = GETGRNAM(cnf->groups[i]);
787			grp = gr_add(grp, pwd->pw_name);
788			/*
789			 * grp can only be NULL in 2 cases:
790			 * - the new member is already a member
791			 * - a problem with memory occurs
792			 * in both cases we want to skip now.
793			 */
794			if (grp == NULL)
795				continue;
796			chggrent(cnf->groups[i], grp);
797			free(grp);
798		}
799	}
800
801
802	/* go get a current version of pwd */
803	pwd = GETPWNAM(a_name->val);
804	if (pwd == NULL) {
805		/* This will fail when we rename, so special case that */
806		if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
807			a_name->val = arg->val;		/* update new name */
808			pwd = GETPWNAM(a_name->val);	/* refetch renamed rec */
809		}
810	}
811	if (pwd == NULL)	/* can't go on without this */
812		errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
813
814	grp = GETGRGID(pwd->pw_gid);
815	pw_log(cnf, mode, W_USER, "%s(%u):%s(%u):%s:%s:%s",
816	       pwd->pw_name, pwd->pw_uid,
817	    grp ? grp->gr_name : "unknown", (grp ? grp->gr_gid : (uid_t)-1),
818	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
819
820	/*
821	 * If adding, let's touch and chown the user's mail file. This is not
822	 * strictly necessary under BSD with a 0755 maildir but it also
823	 * doesn't hurt anything to create the empty mailfile
824	 */
825	if (mode == M_ADD) {
826		if (PWALTDIR() != PWF_ALT) {
827			arg = getarg(args, 'R');
828			snprintf(path, sizeof(path), "%s%s/%s",
829			    arg ? arg->val : "", _PATH_MAILDIR, pwd->pw_name);
830			close(open(path, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
831									 * mtime */
832			chown(path, pwd->pw_uid, pwd->pw_gid);
833		}
834	}
835
836	/*
837	 * Let's create and populate the user's home directory. Note
838	 * that this also `works' for editing users if -m is used, but
839	 * existing files will *not* be overwritten.
840	 */
841	if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir &&
842	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
843		create_and_populate_homedir(mode, args, pwd, cnf);
844
845	/*
846	 * Finally, send mail to the new user as well, if we are asked to
847	 */
848	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
849		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
850
851		if (pfp == NULL)
852			warn("sendmail");
853		else {
854			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
855			while (fgets(line, sizeof(line), fp) != NULL) {
856				/* Do substitutions? */
857				fputs(line, pfp);
858			}
859			pclose(pfp);
860			pw_log(cnf, mode, W_USER, "%s(%u) new user mail sent",
861			    pwd->pw_name, pwd->pw_uid);
862		}
863		fclose(fp);
864	}
865
866	return EXIT_SUCCESS;
867}
868
869
870static          uid_t
871pw_uidpolicy(struct userconf * cnf, struct cargs * args)
872{
873	struct passwd  *pwd;
874	uid_t           uid = (uid_t) - 1;
875	struct carg    *a_uid = getarg(args, 'u');
876
877	/*
878	 * Check the given uid, if any
879	 */
880	if (a_uid != NULL) {
881		uid = (uid_t) atol(a_uid->val);
882
883		if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
884			errx(EX_DATAERR, "uid `%u' has already been allocated", pwd->pw_uid);
885	} else {
886		struct bitmap   bm;
887
888		/*
889		 * We need to allocate the next available uid under one of
890		 * two policies a) Grab the first unused uid b) Grab the
891		 * highest possible unused uid
892		 */
893		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
894							 * claus^H^H^H^Hheck */
895			cnf->min_uid = 1000;
896			cnf->max_uid = 32000;
897		}
898		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
899
900		/*
901		 * Now, let's fill the bitmap from the password file
902		 */
903		SETPWENT();
904		while ((pwd = GETPWENT()) != NULL)
905			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
906				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
907		ENDPWENT();
908
909		/*
910		 * Then apply the policy, with fallback to reuse if necessary
911		 */
912		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
913			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
914
915		/*
916		 * Another sanity check
917		 */
918		if (uid < cnf->min_uid || uid > cnf->max_uid)
919			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
920		bm_dealloc(&bm);
921	}
922	return uid;
923}
924
925
926static          uid_t
927pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
928{
929	struct group   *grp;
930	gid_t           gid = (uid_t) - 1;
931	struct carg    *a_gid = getarg(args, 'g');
932
933	/*
934	 * If no arg given, see if default can help out
935	 */
936	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
937		a_gid = addarg(args, 'g', cnf->default_group);
938
939	/*
940	 * Check the given gid, if any
941	 */
942	SETGRENT();
943	if (a_gid != NULL) {
944		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
945			gid = (gid_t) atol(a_gid->val);
946			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
947				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
948		}
949		gid = grp->gr_gid;
950	} else if ((grp = GETGRNAM(nam)) != NULL &&
951	    (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
952		gid = grp->gr_gid;  /* Already created? Use it anyway... */
953	} else {
954		struct cargs    grpargs;
955		char            tmp[32];
956
957		LIST_INIT(&grpargs);
958		addarg(&grpargs, 'n', nam);
959
960		/*
961		 * We need to auto-create a group with the user's name. We
962		 * can send all the appropriate output to our sister routine
963		 * bit first see if we can create a group with gid==uid so we
964		 * can keep the user and group ids in sync. We purposely do
965		 * NOT check the gid range if we can force the sync. If the
966		 * user's name dups an existing group, then the group add
967		 * function will happily handle that case for us and exit.
968		 */
969		if (GETGRGID(prefer) == NULL) {
970			snprintf(tmp, sizeof(tmp), "%u", prefer);
971			addarg(&grpargs, 'g', tmp);
972		}
973		if (getarg(args, 'N'))
974		{
975			addarg(&grpargs, 'N', NULL);
976			addarg(&grpargs, 'q', NULL);
977			gid = pw_group(cnf, M_NEXT, &grpargs);
978		}
979		else
980		{
981			pw_group(cnf, M_ADD, &grpargs);
982			if ((grp = GETGRNAM(nam)) != NULL)
983				gid = grp->gr_gid;
984		}
985		a_gid = LIST_FIRST(&grpargs);
986		while (a_gid != NULL) {
987			struct carg    *t = LIST_NEXT(a_gid, list);
988			LIST_REMOVE(a_gid, list);
989			a_gid = t;
990		}
991	}
992	ENDGRENT();
993	return gid;
994}
995
996
997static          time_t
998pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
999{
1000	time_t          result = 0;
1001	time_t          now = time(NULL);
1002	struct carg    *arg = getarg(args, 'p');
1003
1004	if (arg != NULL) {
1005		if ((result = parse_date(now, arg->val)) == now)
1006			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
1007	} else if (cnf->password_days > 0)
1008		result = now + ((long) cnf->password_days * 86400L);
1009	return result;
1010}
1011
1012
1013static          time_t
1014pw_exppolicy(struct userconf * cnf, struct cargs * args)
1015{
1016	time_t          result = 0;
1017	time_t          now = time(NULL);
1018	struct carg    *arg = getarg(args, 'e');
1019
1020	if (arg != NULL) {
1021		if ((result = parse_date(now, arg->val)) == now)
1022			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
1023	} else if (cnf->expire_days > 0)
1024		result = now + ((long) cnf->expire_days * 86400L);
1025	return result;
1026}
1027
1028
1029static char    *
1030pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
1031{
1032	struct carg    *arg = getarg(args, 'd');
1033	static char     home[128];
1034
1035	if (arg)
1036		return (arg->val);
1037
1038	if (cnf->home == NULL || *cnf->home == '\0')
1039		errx(EX_CONFIG, "no base home directory set");
1040	snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
1041
1042	return (home);
1043}
1044
1045static char    *
1046shell_path(char const * path, char *shells[], char *sh)
1047{
1048	if (sh != NULL && (*sh == '/' || *sh == '\0'))
1049		return sh;	/* specified full path or forced none */
1050	else {
1051		char           *p;
1052		char            paths[_UC_MAXLINE];
1053
1054		/*
1055		 * We need to search paths
1056		 */
1057		strlcpy(paths, path, sizeof(paths));
1058		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
1059			int             i;
1060			static char     shellpath[256];
1061
1062			if (sh != NULL) {
1063				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
1064				if (access(shellpath, X_OK) == 0)
1065					return shellpath;
1066			} else
1067				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
1068					snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
1069					if (access(shellpath, X_OK) == 0)
1070						return shellpath;
1071				}
1072		}
1073		if (sh == NULL)
1074			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
1075		errx(EX_CONFIG, "no default shell available or defined");
1076		return NULL;
1077	}
1078}
1079
1080
1081static char    *
1082pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1083{
1084	char           *sh = newshell;
1085	struct carg    *arg = getarg(args, 's');
1086
1087	if (newshell == NULL && arg != NULL)
1088		sh = arg->val;
1089	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1090}
1091
1092#define	SALTSIZE	32
1093
1094static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1095
1096char           *
1097pw_pwcrypt(char *password)
1098{
1099	int             i;
1100	char            salt[SALTSIZE + 1];
1101	char		*cryptpw;
1102
1103	static char     buf[256];
1104
1105	/*
1106	 * Calculate a salt value
1107	 */
1108	for (i = 0; i < SALTSIZE; i++)
1109		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1110	salt[SALTSIZE] = '\0';
1111
1112	cryptpw = crypt(password, salt);
1113	if (cryptpw == NULL)
1114		errx(EX_CONFIG, "crypt(3) failure");
1115	return strcpy(buf, cryptpw);
1116}
1117
1118
1119static char    *
1120pw_password(struct userconf * cnf, struct cargs * args, char const * user)
1121{
1122	int             i, l;
1123	char            pwbuf[32];
1124
1125	switch (cnf->default_password) {
1126	case -1:		/* Random password */
1127		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
1128		for (i = 0; i < l; i++)
1129			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1130		pwbuf[i] = '\0';
1131
1132		/*
1133		 * We give this information back to the user
1134		 */
1135		if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1136		    getarg(args, 'N') == NULL) {
1137			if (isatty(STDOUT_FILENO))
1138				printf("Password for '%s' is: ", user);
1139			printf("%s\n", pwbuf);
1140			fflush(stdout);
1141		}
1142		break;
1143
1144	case -2:		/* No password at all! */
1145		return "";
1146
1147	case 0:		/* No login - default */
1148	default:
1149		return "*";
1150
1151	case 1:		/* user's name */
1152		strlcpy(pwbuf, user, sizeof(pwbuf));
1153		break;
1154	}
1155	return pw_pwcrypt(pwbuf);
1156}
1157
1158
1159static int
1160print_user(struct passwd * pwd, int pretty, int v7)
1161{
1162	if (!pretty) {
1163		char            *buf;
1164
1165		if (!v7)
1166			pwd->pw_passwd = (pwd->pw_passwd == NULL) ? "" : "*";
1167
1168		buf = v7 ? pw_make_v7(pwd) : pw_make(pwd);
1169		printf("%s\n", buf);
1170		free(buf);
1171	} else {
1172		int		j;
1173		char           *p;
1174		struct group   *grp = GETGRGID(pwd->pw_gid);
1175		char            uname[60] = "User &", office[60] = "[None]",
1176		                wphone[60] = "[None]", hphone[60] = "[None]";
1177		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
1178		struct tm *    tptr;
1179
1180		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1181			strlcpy(uname, p, sizeof(uname));
1182			if ((p = strtok(NULL, ",")) != NULL) {
1183				strlcpy(office, p, sizeof(office));
1184				if ((p = strtok(NULL, ",")) != NULL) {
1185					strlcpy(wphone, p, sizeof(wphone));
1186					if ((p = strtok(NULL, "")) != NULL) {
1187						strlcpy(hphone, p,
1188						    sizeof(hphone));
1189					}
1190				}
1191			}
1192		}
1193		/*
1194		 * Handle '&' in gecos field
1195		 */
1196		if ((p = strchr(uname, '&')) != NULL) {
1197			int             l = strlen(pwd->pw_name);
1198			int             m = strlen(p);
1199
1200			memmove(p + l, p + 1, m);
1201			memmove(p, pwd->pw_name, l);
1202			*p = (char) toupper((unsigned char)*p);
1203		}
1204		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1205			strftime(acexpire, sizeof acexpire, "%c", tptr);
1206		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1207			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1208		printf("Login Name: %-15s   #%-12u Group: %-15s   #%u\n"
1209		       " Full Name: %s\n"
1210		       "      Home: %-26.26s      Class: %s\n"
1211		       "     Shell: %-26.26s     Office: %s\n"
1212		       "Work Phone: %-26.26s Home Phone: %s\n"
1213		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
1214		       pwd->pw_name, pwd->pw_uid,
1215		       grp ? grp->gr_name : "(invalid)", pwd->pw_gid,
1216		       uname, pwd->pw_dir, pwd->pw_class,
1217		       pwd->pw_shell, office, wphone, hphone,
1218		       acexpire, pwexpire);
1219	        SETGRENT();
1220		j = 0;
1221		while ((grp=GETGRENT()) != NULL)
1222		{
1223			int     i = 0;
1224			if (grp->gr_mem != NULL) {
1225				while (grp->gr_mem[i] != NULL)
1226				{
1227					if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1228					{
1229						printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1230						break;
1231					}
1232					++i;
1233				}
1234			}
1235		}
1236		ENDGRENT();
1237		printf("%s", j ? "\n" : "");
1238	}
1239	return EXIT_SUCCESS;
1240}
1241
1242char    *
1243pw_checkname(u_char *name, int gecos)
1244{
1245	char showch[8];
1246	u_char const *badchars, *ch, *showtype;
1247	int reject;
1248
1249	ch = name;
1250	reject = 0;
1251	if (gecos) {
1252		/* See if the name is valid as a gecos (comment) field. */
1253		badchars = ":!@";
1254		showtype = "gecos field";
1255	} else {
1256		/* See if the name is valid as a userid or group. */
1257		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1258		showtype = "userid/group name";
1259		/* Userids and groups can not have a leading '-'. */
1260		if (*ch == '-')
1261			reject = 1;
1262	}
1263	if (!reject) {
1264		while (*ch) {
1265			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1266			    *ch == 127) {
1267				reject = 1;
1268				break;
1269			}
1270			/* 8-bit characters are only allowed in GECOS fields */
1271			if (!gecos && (*ch & 0x80)) {
1272				reject = 1;
1273				break;
1274			}
1275			ch++;
1276		}
1277	}
1278	/*
1279	 * A `$' is allowed as the final character for userids and groups,
1280	 * mainly for the benefit of samba.
1281	 */
1282	if (reject && !gecos) {
1283		if (*ch == '$' && *(ch + 1) == '\0') {
1284			reject = 0;
1285			ch++;
1286		}
1287	}
1288	if (reject) {
1289		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1290		    ? "`%c'" : "0x%02x", *ch);
1291		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1292		    showch, (ch - name), showtype);
1293	}
1294	if (!gecos && (ch - name) > LOGNAMESIZE)
1295		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1296		    LOGNAMESIZE);
1297	return (char *)name;
1298}
1299
1300
1301static void
1302rmat(uid_t uid)
1303{
1304	DIR            *d = opendir("/var/at/jobs");
1305
1306	if (d != NULL) {
1307		struct dirent  *e;
1308
1309		while ((e = readdir(d)) != NULL) {
1310			struct stat     st;
1311
1312			if (strncmp(e->d_name, ".lock", 5) != 0 &&
1313			    stat(e->d_name, &st) == 0 &&
1314			    !S_ISDIR(st.st_mode) &&
1315			    st.st_uid == uid) {
1316				char            tmp[MAXPATHLEN];
1317
1318				snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s", e->d_name);
1319				system(tmp);
1320			}
1321		}
1322		closedir(d);
1323	}
1324}
1325
1326static void
1327rmopie(char const * name)
1328{
1329	static const char etcopie[] = "/etc/opiekeys";
1330	FILE   *fp = fopen(etcopie, "r+");
1331
1332	if (fp != NULL) {
1333		char	tmp[1024];
1334		off_t	atofs = 0;
1335		int	length = strlen(name);
1336
1337		while (fgets(tmp, sizeof tmp, fp) != NULL) {
1338			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1339				if (fseek(fp, atofs, SEEK_SET) == 0) {
1340					fwrite("#", 1, 1, fp);	/* Comment username out */
1341				}
1342				break;
1343			}
1344			atofs = ftell(fp);
1345		}
1346		/*
1347		 * If we got an error of any sort, don't update!
1348		 */
1349		fclose(fp);
1350	}
1351}
1352
1353